city-generation/Game/Assets/Scripts/Utils/SerializationHelper.cs

117 lines
3.6 KiB
C#

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
{
/// <summary>
/// Converts float matrix to byte array
/// </summary>
/// <param name="matrix">Matrix to convert</param>
/// <remarks>
/// Bytes are stored as such:
///
/// Offset Size Content
/// ------------------------
/// 0 4 Width
/// 4 8 Height
/// 8 var 32bit floating point values
///
/// </remarks>
/// <returns>Byte array</returns>
public static byte[] ToByteArray(this float[,] matrix)
{
if (matrix == null)
return null;
int w = matrix.GetLength(0);
int h = matrix.GetLength(1);
List<byte> bytes = new List<byte>();
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();
}
/// <summary>
/// Converts byte array to float matrix
/// </summary>
/// <param name="array">Byte array</param>
/// /// <remarks>
/// Bytes are expected to be stored as such:
///
/// Offset Size Content
/// ------------------------
/// 0 4 Width
/// 4 8 Height
/// 8 var 32bit floating point values
///
/// </remarks>
/// <returns>Float matrix</returns>
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;
}
/// <summary>
/// Deserializes a file
/// </summary>
/// <typeparam name="T">Type to deserialize</typeparam>
/// <param name="filename">File name</param>
/// <returns>Deserialized object</returns>
public static T DeserializeXml<T>(string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var stream = new StreamReader(filename))
{
T data = (T)serializer.Deserialize(stream);
stream.Close();
return data;
}
}
/// <summary>
/// Serializes an object to a file
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
public static void SerializeXml<T>(this T data, string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StreamWriter writer = new StreamWriter(filename))
{
serializer.Serialize(writer, data);
writer.Close();
}
}
}
}