using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace TransportGame.Utils
{
public static class SerializationHelper
{
///
/// Converts float matrix to byte array
///
/// Matrix to convert
///
/// Bytes are stored as such:
///
/// Offset Size Content
/// ------------------------
/// 0 4 Width
/// 4 8 Height
/// 8 var 32bit floating point values
///
///
/// Byte array
public static byte[] ToByteArray(this float[,] matrix)
{
if (matrix == null)
return null;
int w = matrix.GetLength(0);
int h = matrix.GetLength(1);
List bytes = new List();
bytes.AddRange(BitConverter.GetBytes(w));
bytes.AddRange(BitConverter.GetBytes(h));
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++)
bytes.AddRange(BitConverter.GetBytes(matrix[x, y]));
return bytes.ToArray();
}
///
/// Converts byte array to float matrix
///
/// Byte array
/// ///
/// Bytes are expected to be stored as such:
///
/// Offset Size Content
/// ------------------------
/// 0 4 Width
/// 4 8 Height
/// 8 var 32bit floating point values
///
///
/// Float matrix
public static float[,] GetFloatMatrix(this byte[] array)
{
if (array == null)
return null;
int pos = 0;
int w = BitConverter.ToInt32(array, pos); pos += sizeof(int);
int h = BitConverter.ToInt32(array, pos); pos += sizeof(int);
float[,] grid = new float[w, h];
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++)
{
grid[x, y] = BitConverter.ToSingle(array, pos);
pos += sizeof(float);
}
return grid;
}
///
/// Deserializes a file
///
/// Type to deserialize
/// File name
/// Deserialized object
public static T DeserializeXml(string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var stream = new StreamReader(filename))
{
T data = (T)serializer.Deserialize(stream);
stream.Close();
return data;
}
}
///
/// Serializes an object to a file
///
///
///
public static void SerializeXml(this T data, string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StreamWriter writer = new StreamWriter(filename))
{
serializer.Serialize(writer, data);
writer.Close();
}
}
}
}