|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | + |
| 4 | +namespace ApplicationUtility; |
| 5 | + |
| 6 | +class SubStream : Stream |
| 7 | +{ |
| 8 | + readonly Stream baseStream; |
| 9 | + readonly long length; |
| 10 | + readonly long offsetInParentStream; |
| 11 | + |
| 12 | + public override bool CanRead => true; |
| 13 | + public override bool CanSeek => true; |
| 14 | + public override bool CanWrite => false; |
| 15 | + public override long Length => length; |
| 16 | + |
| 17 | + public override long Position { |
| 18 | + get => throw new NotSupportedException (); |
| 19 | + set => throw new NotSupportedException (); |
| 20 | + } |
| 21 | + |
| 22 | + public SubStream (Stream baseStream, long offsetInParentStream, long length) |
| 23 | + { |
| 24 | + if (!baseStream.CanSeek) { |
| 25 | + throw new InvalidOperationException ($"Base stream must support seeking"); |
| 26 | + } |
| 27 | + |
| 28 | + if (!baseStream.CanRead) { |
| 29 | + throw new InvalidOperationException ($"Base stream must support reading"); |
| 30 | + } |
| 31 | + |
| 32 | + if (offsetInParentStream >= baseStream.Length) { |
| 33 | + throw new ArgumentOutOfRangeException (nameof (offsetInParentStream), $"{offsetInParentStream} exceeds length of the base stream ({baseStream.Length})"); |
| 34 | + } |
| 35 | + |
| 36 | + if (offsetInParentStream + length > baseStream.Length) { |
| 37 | + throw new InvalidOperationException ($"Not enough data in base stream after offset {offsetInParentStream}, length of {length} bytes is too big."); |
| 38 | + } |
| 39 | + |
| 40 | + this.baseStream = baseStream; |
| 41 | + this.length = length; |
| 42 | + this.offsetInParentStream = offsetInParentStream; |
| 43 | + } |
| 44 | + |
| 45 | + public override int Read (byte [] buffer, int offset, int count) |
| 46 | + { |
| 47 | + return baseStream.Read (buffer, offset, count); |
| 48 | + } |
| 49 | + |
| 50 | + public override long Seek (long offset, SeekOrigin origin) |
| 51 | + { |
| 52 | + return baseStream.Seek (offset + offsetInParentStream, origin); |
| 53 | + } |
| 54 | + |
| 55 | + public override void Flush () |
| 56 | + { |
| 57 | + throw new NotSupportedException (); |
| 58 | + } |
| 59 | + |
| 60 | + public override void SetLength (long value) |
| 61 | + { |
| 62 | + throw new NotSupportedException (); |
| 63 | + } |
| 64 | + |
| 65 | + public override void Write (byte [] buffer, int offset, int count) |
| 66 | + { |
| 67 | + throw new NotSupportedException (); |
| 68 | + } |
| 69 | +} |
0 commit comments