DefiniteLengthInputStream.cs 2.4 KB

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