public void Serialize <T>(T graph, bool IsUpdate) { int key; if (!m_ByType.TryGetValue(graph.GetType(), out key)) { throw new SerializationException(graph.GetType() + " has not been registered with the serializer"); } ICustomBinarySerializable c = (ICustomBinarySerializable)graph; //this will always work due to generic constraint on the Register m_WriteStream.Seek(0L, SeekOrigin.Begin); m_Writer.Write((int)key); c.WriteDataTo(m_Writer); if (indexStream != null && !IsUpdate) { count++; pending++; if (pending % chunckSize == 0) { byte[] buffer = m_IndexWriteStream.ToArray(); indexStream.Write(buffer, 0, buffer.Length); m_IndexWriteStream = new MemoryStream(chunckSize * sizeLength); pending = 0; } m_IndexWriteStream.Write(BitConverter.GetBytes(serializationStream.Position), 0, sizeLength); } serializationStream.Write(BitConverter.GetBytes(m_WriteStream.Position), 0, sizeLength); serializationStream.Write(m_WriteStream.GetBuffer(), 0, (int)m_WriteStream.Position); }
public T Deserialize <T>(bool Full) { if (serializationStream.Read(m_LengthBuffer, 0, sizeLength) != sizeLength) { //throw new SerializationException("Could not read length from the stream."); return(default(T)); } int length = BitConverter.ToInt32(m_LengthBuffer, 0); //TODO make this support partial reads from stream if (serializationStream.Read(m_CopyBuffer, 0, length) != length) { throw new SerializationException("Could not read " + length + " bytes from the stream."); } m_ReadStream.Seek(0L, SeekOrigin.Begin); m_ReadStream.Write(m_CopyBuffer, 0, length); m_ReadStream.Seek(0L, SeekOrigin.Begin); int typeid = m_Reader.ReadInt32(); Type t; if (!m_ById.TryGetValue(typeid, out t)) { throw new SerializationException("TypeId " + typeid + " is not a registerred type id"); } object obj = FormatterServices.GetUninitializedObject(t); ICustomBinarySerializable deserialize = (ICustomBinarySerializable)obj; deserialize.SetDataFrom(m_Reader, Full); if (m_ReadStream.Position != length) { throw new SerializationException("object of type " + t + " did not read its entire buffer during deserialization. This is most likely an inbalance between the writes and the reads of the object."); } return((T)deserialize); }