using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
namespace SCSI.Multimedia
{
public class SCSIStream : Stream
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private long _Position;
/// <summary>Leaves the device open!</summary>
public SCSIStream(SCSIDevice device) { this.Device = device; }
public SCSIDevice Device { get; private set; }
protected override void Dispose(bool disposing) { if (disposing) { this.Flush(); this.Device = null; } base.Dispose(disposing); }
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanWrite { get { return true; } }
public override void Flush() { this.Device.SynchronizeCache(new SynchronizeCache10Command()); }
public override long Length { get { return this.Device.Capacity.LogicalBlockAddress * this.Device.Capacity.BlockLength; } }
public override long Position { get { return this._Position; } set { this._Position = value; } }
public override int Read(byte[] buffer, int offset, int count)
{
long pos = this.Position;
if (pos % this.Device.Capacity.BlockLength != 0) { throw new DataMisalignedException(); }
this.Device.Read10(new Read10Command(false, (uint)(pos / this.Device.Capacity.BlockLength), (ushort)count), buffer, offset);
return count;
}
public override long Seek(long offset, SeekOrigin origin)
{
long newPos;
if (origin == SeekOrigin.Begin)
{
if (offset % this.Device.Capacity.BlockLength != 0) { throw new DataMisalignedException(); }
newPos = offset / this.Device.Capacity.BlockLength;
this.Device.Seek10(new Seek10Command(checked((uint)newPos)));
}
else { throw new NotImplementedException(); }
this._Position = newPos;
return this._Position;
}
public override void SetLength(long value) { throw new NotImplementedException(); }
public override void Write(byte[] buffer, int offset, int count)
{
long pos = this._Position;
if (pos % this.Device.Capacity.BlockLength != 0) { throw new DataMisalignedException(); }
unsafe
{
fixed (byte* pBuffer = &buffer[offset])
{
var buf = new Helper.BufferWithSize(pBuffer, buffer.Length - offset).ExtractSegment(0, count);
this.Device.Write10(new Write10Command(false, (uint)(pos / this.Device.Capacity.BlockLength)), buf);
}
}
this._Position = pos + count;
}
}
}