LimitedInputStream.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib;
  4. using System;
  5. using System.IO;
  6. namespace Best.HTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO
  7. {
  8. internal class LimitedInputStream
  9. : BaseInputStream
  10. {
  11. private readonly Stream m_stream;
  12. private long m_limit;
  13. internal LimitedInputStream(Stream stream, long limit)
  14. {
  15. this.m_stream = stream;
  16. this.m_limit = limit;
  17. }
  18. internal long CurrentLimit => m_limit;
  19. public override int Read(byte[] buffer, int offset, int count)
  20. {
  21. int numRead = m_stream.Read(buffer, offset, count);
  22. if (numRead > 0)
  23. {
  24. if ((m_limit -= numRead) < 0)
  25. throw new StreamOverflowException("Data Overflow");
  26. }
  27. return numRead;
  28. }
  29. #if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER
  30. public override int Read(Span<byte> buffer)
  31. {
  32. int numRead = m_stream.Read(buffer);
  33. if (numRead > 0)
  34. {
  35. if ((m_limit -= numRead) < 0)
  36. throw new StreamOverflowException("Data Overflow");
  37. }
  38. return numRead;
  39. }
  40. #endif
  41. public override int ReadByte()
  42. {
  43. int b = m_stream.ReadByte();
  44. if (b >= 0)
  45. {
  46. if (--m_limit < 0)
  47. throw new StreamOverflowException("Data Overflow");
  48. }
  49. return b;
  50. }
  51. }
  52. }
  53. #pragma warning restore
  54. #endif