IndefiniteLengthInputStream.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Asn1
  6. {
  7. class IndefiniteLengthInputStream
  8. : LimitedInputStream
  9. {
  10. private int _lookAhead;
  11. private bool _eofOn00 = true;
  12. internal IndefiniteLengthInputStream(Stream inStream, int limit)
  13. : base(inStream, limit)
  14. {
  15. _lookAhead = RequireByte();
  16. if (0 == _lookAhead)
  17. {
  18. CheckEndOfContents();
  19. }
  20. }
  21. internal void SetEofOn00(bool eofOn00)
  22. {
  23. _eofOn00 = eofOn00;
  24. if (_eofOn00 && 0 == _lookAhead)
  25. {
  26. CheckEndOfContents();
  27. }
  28. }
  29. private void CheckEndOfContents()
  30. {
  31. if (0 != RequireByte())
  32. throw new IOException("malformed end-of-contents marker");
  33. _lookAhead = -1;
  34. SetParentEofDetect();
  35. }
  36. public override int Read(byte[] buffer, int offset, int count)
  37. {
  38. // Only use this optimisation if we aren't checking for 00
  39. if (_eofOn00 || count <= 1)
  40. return base.Read(buffer, offset, count);
  41. if (_lookAhead < 0)
  42. return 0;
  43. int numRead = _in.Read(buffer, offset + 1, count - 1);
  44. if (numRead <= 0)
  45. throw new EndOfStreamException();
  46. buffer[offset] = (byte)_lookAhead;
  47. _lookAhead = RequireByte();
  48. return numRead + 1;
  49. }
  50. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  51. public override int Read(Span<byte> buffer)
  52. {
  53. // Only use this optimisation if we aren't checking for 00
  54. if (_eofOn00 || buffer.Length <= 1)
  55. return base.Read(buffer);
  56. if (_lookAhead < 0)
  57. return 0;
  58. int numRead = _in.Read(buffer[1..]);
  59. if (numRead <= 0)
  60. throw new EndOfStreamException();
  61. buffer[0] = (byte)_lookAhead;
  62. _lookAhead = RequireByte();
  63. return numRead + 1;
  64. }
  65. #endif
  66. public override int ReadByte()
  67. {
  68. if (_eofOn00 && _lookAhead <= 0)
  69. {
  70. if (0 == _lookAhead)
  71. {
  72. CheckEndOfContents();
  73. }
  74. return -1;
  75. }
  76. int result = _lookAhead;
  77. _lookAhead = RequireByte();
  78. return result;
  79. }
  80. private int RequireByte()
  81. {
  82. int b = _in.ReadByte();
  83. if (b < 0)
  84. throw new EndOfStreamException();
  85. return b;
  86. }
  87. }
  88. }
  89. #pragma warning restore
  90. #endif