/// <summary> /// Serializes the object, or graph of objects with the specified top (root), to the given stream. /// </summary> /// <param name="stream">The stream to which the graph is to be serialized.</param> /// <param name="value">The object at the root of the graph to serialize.</param> /// <param name="context">An optional serialization context.</param> public void Serialize(Stream stream, object value, object context = null) { if (stream == null) { throw new ArgumentNullException("stream"); } if (value == null) { return; } RootTypeNode graph = GetGraph(value.GetType()); var serializer = (ContextValueNode)graph.CreateSerializer(null); serializer.EndiannessCallback = () => Endianness; serializer.EncodingCallback = () => Encoding; serializer.Value = value; serializer.Context = context; serializer.Bind(); var wrappedStream = new BitStream(stream); serializer.Serialize(wrappedStream, _eventShuttle); wrappedStream.Flush(); }
/// <summary> /// Deserializes the specified stream into an object graph. /// </summary> /// <typeparam name="T">The type of the root of the object graph.</typeparam> /// <param name="stream">The stream from which to deserialize the object graph.</param> /// <param name="context">An optional serialization context.</param> /// <returns>The deserialized object graph.</returns> public T Deserialize <T>(Stream stream, object context = null) { RootTypeNode graph = GetGraph(typeof(T)); var serializer = (ContextValueNode)graph.CreateSerializer(null); serializer.EndiannessCallback = () => Endianness; serializer.EncodingCallback = () => Encoding; serializer.Context = context; serializer.Deserialize(new StreamLimiter(new BitStream(stream)), _eventShuttle); return((T)serializer.Value); }
/// <summary> /// Deserializes the specified stream into an object graph. /// </summary> /// <param name="stream">The stream from which to deserialize the object graph.</param> /// <param name="type">The type of the root of the object graph.</param> /// <param name="context">An optional serialization context.</param> /// <returns>The deserialized object graph.</returns> public object Deserialize(Stream stream, Type type, object context = null) { RootTypeNode graph = GetGraph(type); var serializer = (RootValueNode)graph.CreateSerializer(null); serializer.EndiannessCallback = () => Endianness; serializer.EncodingCallback = () => Encoding; serializer.Context = context; serializer.Deserialize(new BoundedStream(stream), _eventShuttle); return(serializer.Value); }
private RootTypeNode GetGraph(Type valueType) { lock (GraphCacheLock) { RootTypeNode graph; if (GraphCache.TryGetValue(valueType, out graph)) { return(graph); } graph = new RootTypeNode(valueType); GraphCache.Add(valueType, graph); return(graph); } }