ReadOnlySubStream.cs 2.1 KB

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