Пример #1
0
        public object Deserialize(Stream serializationStream)
        {
            if (serializationStream.Read(_lengthBuffer, 0, 4) != 4)
            {
                throw new SerializationException("Could not read length from the stream.");
            }
            var length = new IntToBytes(_lengthBuffer[0], _lengthBuffer[1], _lengthBuffer[2], _lengthBuffer[3]);

            //TODO make this support partial reads from stream
            if (serializationStream.Read(_copyBuffer, 0, length.I32) != length.I32)
            {
                throw new SerializationException("Could not read " + length + " bytes from the stream.");
            }
            _readStream.Seek(0L, SeekOrigin.Begin);
            _readStream.Write(_copyBuffer, 0, length.I32);
            _readStream.Seek(0L, SeekOrigin.Begin);
            var  typeid = _reader.ReadInt32();
            Type t;

            if (!_byId.TryGetValue(typeid, out t))
            {
                throw new SerializationException("TypeId " + typeid + " is not a registerred type id");
            }
            var obj         = FormatterServices.GetUninitializedObject(t);
            var deserialize = (ICustomBinarySerializable)obj;

            deserialize.SetDataFrom(_reader);
            if (_readStream.Position != length.I32)
            {
                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(deserialize);
        }
Пример #2
0
        public void Serialize(Stream serializationStream, object graph)
        {
            int key;

            if (!_byType.TryGetValue(graph.GetType(), out key))
            {
                throw new SerializationException(graph.GetType() + " has not been registered with the serializer");
            }
            var c = (ICustomBinarySerializable)graph;  //this will always work due to generic constraint on the Register

            _writeStream.Seek(0L, SeekOrigin.Begin);
            _writer.Write(key);
            c.WriteDataTo(_writer);
            var length = new IntToBytes((int)_writeStream.Position);

            serializationStream.WriteByte(length.B0);
            serializationStream.WriteByte(length.B1);
            serializationStream.WriteByte(length.B2);
            serializationStream.WriteByte(length.B3);
            serializationStream.Write(_writeStream.GetBuffer(), 0, (int)_writeStream.Position);
        }