0.2.0-dev Download ZIP
37 lines ·916 B Raw
| 1 | namespace EvilEngine.Mounts; |
| 2 | |
| 3 | public sealed class StreamAccess : IRandomAccess |
| 4 | { |
| 5 | private readonly Lock _lock = new(); |
| 6 | private readonly Stream _stream; |
| 7 | |
| 8 | public StreamAccess(Stream stream) |
| 9 | { |
| 10 | if (!stream.CanSeek || !stream.CanRead) |
| 11 | throw new ArgumentException("Reading at an offset needs a readable, seekable stream.", nameof(stream)); |
| 12 | _stream = stream; |
| 13 | Length = stream.Length; |
| 14 | } |
| 15 | |
| 16 | public long Length { get; } |
| 17 | |
| 18 | public int Read(long offset, Span<byte> buffer) |
| 19 | { |
| 20 | if (offset >= Length) |
| 21 | return 0; |
| 22 | var wanted = (int)Math.Min(buffer.Length, Length - offset); |
| 23 | lock (_lock) |
| 24 | { |
| 25 | _stream.Position = offset; |
| 26 | return _stream.ReadAtLeast(buffer[..wanted], wanted, false); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | public void Dispose() |
| 31 | { |
| 32 | lock (_lock) |
| 33 | { |
| 34 | _stream.Dispose(); |
| 35 | } |
| 36 | } |
| 37 | } |