TarReadOnlySubStream.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.IO;
  3. namespace SharpCompress.Common.Tar
  4. {
  5. internal class TarReadOnlySubStream : Stream
  6. {
  7. private bool _isDisposed;
  8. private long _amountRead;
  9. public TarReadOnlySubStream(Stream stream, long bytesToRead)
  10. {
  11. Stream = stream;
  12. BytesLeftToRead = bytesToRead;
  13. }
  14. protected override void Dispose(bool disposing)
  15. {
  16. if (_isDisposed)
  17. {
  18. return;
  19. }
  20. _isDisposed = true;
  21. if (disposing)
  22. {
  23. long skipBytes = _amountRead % 512;
  24. if (skipBytes == 0)
  25. {
  26. return;
  27. }
  28. skipBytes = 512 - skipBytes;
  29. if (skipBytes == 0)
  30. {
  31. return;
  32. }
  33. var buffer = new byte[skipBytes];
  34. Stream.ReadFully(buffer);
  35. }
  36. }
  37. private long BytesLeftToRead { get; set; }
  38. public Stream Stream { get; }
  39. public override bool CanRead => true;
  40. public override bool CanSeek => false;
  41. public override bool CanWrite => false;
  42. public override void Flush()
  43. {
  44. throw new NotSupportedException();
  45. }
  46. public override long Length => throw new NotSupportedException();
  47. public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
  48. public override int Read(byte[] buffer, int offset, int count)
  49. {
  50. if (BytesLeftToRead < count)
  51. {
  52. count = (int)BytesLeftToRead;
  53. }
  54. int read = Stream.Read(buffer, offset, count);
  55. if (read > 0)
  56. {
  57. BytesLeftToRead -= read;
  58. _amountRead += read;
  59. }
  60. return read;
  61. }
  62. public override int ReadByte()
  63. {
  64. if (BytesLeftToRead <= 0)
  65. {
  66. return -1;
  67. }
  68. int value = Stream.ReadByte();
  69. if (value != -1)
  70. {
  71. --BytesLeftToRead;
  72. ++_amountRead;
  73. }
  74. return value;
  75. }
  76. public override long Seek(long offset, SeekOrigin origin)
  77. {
  78. throw new NotSupportedException();
  79. }
  80. public override void SetLength(long value)
  81. {
  82. throw new NotSupportedException();
  83. }
  84. public override void Write(byte[] buffer, int offset, int count)
  85. {
  86. throw new NotSupportedException();
  87. }
  88. }
  89. }