BufferedSubStream.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.IO;
  3. namespace SharpCompress.IO
  4. {
  5. internal class BufferedSubStream : Stream
  6. {
  7. private long position;
  8. private int cacheOffset;
  9. private int cacheLength;
  10. private readonly byte[] cache;
  11. public BufferedSubStream(Stream stream, long origin, long bytesToRead)
  12. {
  13. Stream = stream;
  14. position = origin;
  15. BytesLeftToRead = bytesToRead;
  16. cache = new byte[32 << 10];
  17. }
  18. protected override void Dispose(bool disposing)
  19. {
  20. if (disposing)
  21. {
  22. //Stream.Dispose();
  23. }
  24. }
  25. private long BytesLeftToRead { get; set; }
  26. public Stream Stream { get; }
  27. public override bool CanRead => true;
  28. public override bool CanSeek => false;
  29. public override bool CanWrite => false;
  30. public override void Flush()
  31. {
  32. throw new NotSupportedException();
  33. }
  34. public override long Length => BytesLeftToRead;
  35. public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
  36. public override int Read(byte[] buffer, int offset, int count)
  37. {
  38. if (count > BytesLeftToRead)
  39. {
  40. count = (int)BytesLeftToRead;
  41. }
  42. if (count > 0)
  43. {
  44. if (cacheLength == 0)
  45. {
  46. cacheOffset = 0;
  47. Stream.Position = position;
  48. cacheLength = Stream.Read(cache, 0, cache.Length);
  49. position += cacheLength;
  50. }
  51. if (count > cacheLength)
  52. {
  53. count = cacheLength;
  54. }
  55. Buffer.BlockCopy(cache, cacheOffset, buffer, offset, count);
  56. cacheOffset += count;
  57. cacheLength -= count;
  58. BytesLeftToRead -= count;
  59. }
  60. return count;
  61. }
  62. public override long Seek(long offset, SeekOrigin origin)
  63. {
  64. throw new NotSupportedException();
  65. }
  66. public override void SetLength(long value)
  67. {
  68. throw new NotSupportedException();
  69. }
  70. public override void Write(byte[] buffer, int offset, int count)
  71. {
  72. throw new NotSupportedException();
  73. }
  74. }
  75. }