PushbackStream.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.Utilities.IO
  6. {
  7. public class PushbackStream
  8. : FilterStream
  9. {
  10. private int m_buf = -1;
  11. public PushbackStream(Stream s)
  12. : base(s)
  13. {
  14. }
  15. #if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || (UNITY_2021_2_OR_NEWER && (NET_STANDARD_2_0 || NET_STANDARD_2_1))
  16. public override void CopyTo(Stream destination, int bufferSize)
  17. {
  18. if (m_buf != -1)
  19. {
  20. destination.WriteByte((byte)m_buf);
  21. m_buf = -1;
  22. }
  23. s.CopyTo(destination, bufferSize);
  24. }
  25. #endif
  26. public override int Read(byte[] buffer, int offset, int count)
  27. {
  28. Streams.ValidateBufferArguments(buffer, offset, count);
  29. if (m_buf != -1)
  30. {
  31. if (count < 1)
  32. return 0;
  33. buffer[offset] = (byte)m_buf;
  34. m_buf = -1;
  35. return 1;
  36. }
  37. return s.Read(buffer, offset, count);
  38. }
  39. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  40. public override int Read(Span<byte> buffer)
  41. {
  42. if (m_buf != -1)
  43. {
  44. if (buffer.IsEmpty)
  45. return 0;
  46. buffer[0] = (byte)m_buf;
  47. m_buf = -1;
  48. return 1;
  49. }
  50. return s.Read(buffer);
  51. }
  52. #endif
  53. public override int ReadByte()
  54. {
  55. if (m_buf != -1)
  56. {
  57. int tmp = m_buf;
  58. m_buf = -1;
  59. return tmp;
  60. }
  61. return base.ReadByte();
  62. }
  63. public virtual void Unread(int b)
  64. {
  65. if (m_buf != -1)
  66. throw new InvalidOperationException("Can only push back one byte");
  67. m_buf = b & 0xFF;
  68. }
  69. }
  70. }
  71. #pragma warning restore
  72. #endif