XCI-Explorer/XTSSharp/SectorStream.cs

120 lines
3.2 KiB
C#
Raw Normal View History

2018-06-17 18:21:52 +00:00
using System;
using System.IO;
2019-04-14 17:17:26 +00:00
namespace XTSSharp
{
public class SectorStream : Stream
{
private readonly Stream _baseStream;
private readonly long _offset;
private ulong _currentSector;
public int SectorSize {
get;
private set;
}
public override bool CanRead => _baseStream.CanRead;
public override bool CanSeek => _baseStream.CanSeek;
public override bool CanWrite => _baseStream.CanWrite;
public override long Length => _baseStream.Length - _offset;
public override long Position {
get {
return _baseStream.Position - _offset;
}
set {
ValidateSizeMultiple(value);
_baseStream.Position = value + _offset;
_currentSector = (ulong)(value / SectorSize);
}
}
protected ulong CurrentSector => _currentSector;
public SectorStream(Stream baseStream, int sectorSize)
2019-04-14 17:17:26 +00:00
: this(baseStream, sectorSize, 0L)
{
}
2019-04-14 17:17:26 +00:00
public SectorStream(Stream baseStream, int sectorSize, long offset)
{
SectorSize = sectorSize;
_baseStream = baseStream;
_offset = offset;
}
2019-04-14 17:17:26 +00:00
private void ValidateSizeMultiple(long value)
{
if (value % SectorSize == 0L)
{
return;
}
throw new ArgumentException($"Value needs to be a multiple of {SectorSize}");
}
2019-04-14 17:17:26 +00:00
protected void ValidateSize(long value)
{
if (value == SectorSize)
{
return;
}
throw new ArgumentException($"Value needs to be {SectorSize}");
}
2019-04-14 17:17:26 +00:00
protected void ValidateSize(int value)
{
if (value == SectorSize)
{
return;
}
throw new ArgumentException($"Value needs to be {SectorSize}");
}
2019-04-14 17:17:26 +00:00
public override void Flush()
{
_baseStream.Flush();
}
2019-04-14 17:17:26 +00:00
public override long Seek(long offset, SeekOrigin origin)
{
long num;
2019-04-14 17:17:26 +00:00
switch (origin)
{
case SeekOrigin.Begin:
num = offset;
break;
case SeekOrigin.End:
num = Length - offset;
break;
default:
num = Position + offset;
break;
}
Position = num;
return num;
}
2019-04-14 17:17:26 +00:00
public override void SetLength(long value)
{
ValidateSizeMultiple(value);
_baseStream.SetLength(value);
}
2019-04-14 17:17:26 +00:00
public override int Read(byte[] buffer, int offset, int count)
{
ValidateSize(count);
int result = _baseStream.Read(buffer, offset, count);
_currentSector++;
return result;
}
2019-04-14 17:17:26 +00:00
public override void Write(byte[] buffer, int offset, int count)
{
ValidateSize(count);
_baseStream.Write(buffer, offset, count);
_currentSector++;
}
}
2018-06-17 18:21:52 +00:00
}