using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tools.DotNETCommon
{
public static class BinaryWriterExtensions
{
///
/// Writes an array to a binary writer.
///
/// The array element type
/// Writer to serialize to
/// Array of items
/// Delegate to call to serialize each element
public static void Write(this BinaryWriter Writer, T[] Items, Action WriteElement)
{
if(Items == null)
{
Writer.Write(-1);
}
else
{
Writer.Write(Items.Length);
for(int Idx = 0; Idx < Items.Length; Idx++)
{
WriteElement(Writer, Items[Idx]);
}
}
}
///
/// Writes a list to a binary writer.
///
/// The list element type
/// Writer to serialize to
/// List of items
/// Delegate to call to serialize each element
public static void Write(this BinaryWriter Writer, List Items, Action WriteElement)
{
if (Items == null)
{
Writer.Write(-1);
}
else
{
Writer.Write(Items.Count);
for (int Idx = 0; Idx < Items.Count; Idx++)
{
WriteElement(Writer, Items[Idx]);
}
}
}
///
/// Writes a value of a specific type to a binary writer
///
/// Writer for output data
/// Type of value to write
/// The value to output
public static void Write(this BinaryWriter Writer, Type FieldType, object Value)
{
if(FieldType == typeof(string))
{
Writer.Write((string)Value);
}
else if(FieldType == typeof(bool))
{
Writer.Write((bool)Value);
}
else if(FieldType == typeof(int))
{
Writer.Write((int)Value);
}
else if(FieldType == typeof(float))
{
Writer.Write((float)Value);
}
else if(FieldType == typeof(double))
{
Writer.Write((double)Value);
}
else if(FieldType.IsEnum)
{
Writer.Write((int)Value);
}
else if(FieldType == typeof(string[]))
{
Writer.Write((string[])Value, (x, y) => x.Write(y));
}
else
{
throw new Exception(String.Format("Unsupported type '{0}' for binary serialization", FieldType.Name));
}
}
}
}