DefiniteLengthInputStream.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.IO;
  4. using Org.BouncyCastle.Utilities.IO;
  5. namespace Org.BouncyCastle.Asn1
  6. {
  7. class DefiniteLengthInputStream
  8. : LimitedInputStream
  9. {
  10. private static readonly byte[] EmptyBytes = new byte[0];
  11. private readonly int _originalLength;
  12. private int _remaining;
  13. internal DefiniteLengthInputStream(
  14. Stream inStream,
  15. int length)
  16. : base(inStream, length)
  17. {
  18. if (length < 0)
  19. throw new ArgumentException("negative lengths not allowed", "length");
  20. this._originalLength = length;
  21. this._remaining = length;
  22. if (length == 0)
  23. {
  24. SetParentEofDetect(true);
  25. }
  26. }
  27. internal int Remaining
  28. {
  29. get { return _remaining; }
  30. }
  31. public override int ReadByte()
  32. {
  33. if (_remaining == 0)
  34. return -1;
  35. int b = _in.ReadByte();
  36. if (b < 0)
  37. throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
  38. if (--_remaining == 0)
  39. {
  40. SetParentEofDetect(true);
  41. }
  42. return b;
  43. }
  44. public override int Read(
  45. byte[] buf,
  46. int off,
  47. int len)
  48. {
  49. if (_remaining == 0)
  50. return 0;
  51. int toRead = System.Math.Min(len, _remaining);
  52. int numRead = _in.Read(buf, off, toRead);
  53. if (numRead < 1)
  54. throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
  55. if ((_remaining -= numRead) == 0)
  56. {
  57. SetParentEofDetect(true);
  58. }
  59. return numRead;
  60. }
  61. internal void ReadAllIntoByteArray(byte[] buf)
  62. {
  63. if (_remaining != buf.Length)
  64. throw new ArgumentException("buffer length not right for data");
  65. if ((_remaining -= Streams.ReadFully(_in, buf)) != 0)
  66. throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
  67. SetParentEofDetect(true);
  68. }
  69. internal byte[] ToArray()
  70. {
  71. if (_remaining == 0)
  72. return EmptyBytes;
  73. byte[] bytes = new byte[_remaining];
  74. if ((_remaining -= Streams.ReadFully(_in, bytes)) != 0)
  75. throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining);
  76. SetParentEofDetect(true);
  77. return bytes;
  78. }
  79. }
  80. }
  81. #endif