using System;
using System.Collections.Generic;
namespace Be.Windows.Forms
{
///
/// Byte provider for a small amount of data.
///
public class DynamicByteProvider : IByteProvider
{
///
/// Contains information about changes.
///
bool _hasChanges;
///
/// Contains a byte collection.
///
List _bytes;
///
/// Initializes a new instance of the DynamicByteProvider class.
///
///
public DynamicByteProvider(byte[] data) : this(new List(data))
{
}
///
/// Initializes a new instance of the DynamicByteProvider class.
///
///
public DynamicByteProvider(List bytes)
{
_bytes = bytes;
}
///
/// Raises the Changed event.
///
void OnChanged(EventArgs e)
{
_hasChanges = true;
if(Changed != null)
Changed(this, e);
}
///
/// Raises the LengthChanged event.
///
void OnLengthChanged(EventArgs e)
{
if(LengthChanged != null)
LengthChanged(this, e);
}
///
/// Gets the byte collection.
///
public List Bytes
{
get { return _bytes; }
}
#region IByteProvider Members
///
/// True, when changes are done.
///
public bool HasChanges()
{
return _hasChanges;
}
///
/// Applies changes.
///
public void ApplyChanges()
{
_hasChanges = false;
}
///
/// Occurs, when the write buffer contains new changes.
///
public event EventHandler Changed;
///
/// Occurs, when InsertBytes or DeleteBytes method is called.
///
public event EventHandler LengthChanged;
///
/// Reads a byte from the byte collection.
///
/// the index of the byte to read
/// the byte
public byte ReadByte(long index)
{ return _bytes[(int)index]; }
///
/// Write a byte into the byte collection.
///
/// the index of the byte to write.
/// the byte
public void WriteByte(long index, byte value)
{
_bytes[(int)index] = value;
OnChanged(EventArgs.Empty);
}
///
/// Deletes bytes from the byte collection.
///
/// the start index of the bytes to delete.
/// the length of bytes to delete.
public void DeleteBytes(long index, long length)
{
int internal_index = (int)Math.Max(0, index);
int internal_length = (int)Math.Min((int)Length, length);
_bytes.RemoveRange(internal_index, internal_length);
OnLengthChanged(EventArgs.Empty);
OnChanged(EventArgs.Empty);
}
///
/// Inserts byte into the byte collection.
///
/// the start index of the bytes in the byte collection
/// the byte array to insert
public void InsertBytes(long index, byte[] bs)
{
_bytes.InsertRange((int)index, bs);
OnLengthChanged(EventArgs.Empty);
OnChanged(EventArgs.Empty);
}
///
/// Gets the length of the bytes in the byte collection.
///
public long Length
{
get
{
return _bytes.Count;
}
}
///
/// Returns true
///
public virtual bool SupportsWriteByte()
{
return true;
}
///
/// Returns true
///
public virtual bool SupportsInsertBytes()
{
return true;
}
///
/// Returns true
///
public virtual bool SupportsDeleteBytes()
{
return true;
}
#endregion
}
}