An exercise in overcomplication
Ok, there really isn't a need for doing this, but since i'm already stuck on creating compact language independent binary representations, here's a quick struct with an int, a fixed sized string and a variable data field that implements a quick and dirty serialization to go along with it
/// <summary>
/// Example of completely manual serialization of a struct containing a fixed
/// sized string and a variable sized data block
/// </summary>
struct FixedStringAndVariableData
{
// the fixed size of the valueString
const int VALUE_SIZE = 10;
Int32 id;
string valueString;
byte[] data;
public int Id
{
get { return id; }
set { id = value; }
}
public int ValueSize
{
get { return VALUE_SIZE; }
}
public string Value
{
get
{
if( valueString == null )
{
valueString = "".PadRight(10,' ');
}
return valueString;
}
set
{
if( value == null )
{
valueString = "".PadRight(10,' ');
}
else if( value.Length < 10 )
{
valueString = value.PadRight(10,' ');
}
else if( value.Length > 10 )
{
valueString = value.Substring(0,10);
}
}
}
public byte[] Data
{
get { return data; }
set { data = value; }
}
public FixedStringAndVariableData(byte[] pRaw)
{
id = BitConverter.ToInt32(pRaw,0);
Int32 offset = Marshal.SizeOf(id.GetType());
valueString = Encoding.ASCII.GetString(pRaw,offset,VALUE_SIZE);
offset += VALUE_SIZE;
Int32 remainder = pRaw.Length - offset;
data = new byte[remainder];
for(int i=0;i<remainder;i++)
{
data[i] = pRaw[offset+i];
}
}
public byte[] Serialize()
{
Int32 size = Marshal.SizeOf(id.GetType())+VALUE_SIZE+data.Length;
IntPtr pnt = Marshal.AllocHGlobal(size);
byte[] serialized = new byte[size];
int position = 0;
byte[] buffer = BitConverter.GetBytes(id);
buffer.CopyTo(serialized,position);
position += buffer.Length;
buffer = Encoding.ASCII.GetBytes(this.Value);
buffer.CopyTo(serialized,position);
position += buffer.Length;
data.CopyTo(serialized,position);
return serialized;
}
}
Ok, i'll get off this subject now :)