using System; using System.IO; namespace Susurrus.UnitTests { /// /// A seekable stream that reports a length different from the bytes it holds, as a damaged or hostile source can. /// public class ClaimedLengthStream : Stream { private readonly byte[] data; private readonly long claimedLength; public ClaimedLengthStream(byte[] data, long claimedLength) { this.data = data; this.claimedLength = claimedLength; } public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; public override long Length => claimedLength; public override long Position { get; set; } public override int Read(byte[] buffer, int offset, int count) { if (Position >= data.Length) { return 0; } int read = (int)Math.Min(count, data.Length - Position); Buffer.BlockCopy(data, (int)Position, buffer, offset, read); Position += read; return read; } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: Position = offset; break; case SeekOrigin.Current: Position += offset; break; default: Position = claimedLength + offset; break; } return Position; } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } }