/// <summary> /// Writes the body of an object in the output /// </summary> public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (graph == null) { writer.WriteAttributeString("nil", "true"); } else { using (MemoryStream ms = new MemoryStream()) { if (isList) { model.Serialize(ms, graph, null); } else { using (ProtoWriter protoWriter = ProtoWriter.Create(out var state, ms, model, null)) { model.Serialize(protoWriter, ref state, key, graph); protoWriter.Close(ref state); } } byte[] buffer = ms.GetBuffer(); writer.WriteBase64(buffer, 0, (int)ms.Length); } } }
public void AppendExtendValue(TypeModel model, IExtensible instance, int tag, BinaryDataFormat format, object value) { #if FEAT_IKVM throw new NotSupportedException(); #else if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } // obtain the extension object and prepare to write IExtension extn = instance.GetExtensionObject(true); if (extn == null) { throw new InvalidOperationException("No extension object available; appended data would be lost."); } bool commit = false; Stream stream = extn.BeginAppend(); try { using (ProtoWriter writer = new ProtoWriter(stream, model, null)) { model.TrySerializeAuxiliaryType(writer, null, format, tag, value, false, true); writer.Close(); } commit = true; } finally { extn.EndAppend(stream, commit); } #endif }
public void GenerateTypeSerializer() { var model = ProtoBuf.Meta.TypeModel.Create(); var head = new TypeSerializer(typeof(CustomerStruct), new int[] { 1, 2 }, new IProtoSerializer[] { new PropertyDecorator(typeof(CustomerStruct), typeof(CustomerStruct).GetProperty("Id"), new TagDecorator(1, WireType.Variant, false, PrimitiveSerializer <Int32Serializer> .Singleton)), new FieldDecorator(typeof(CustomerStruct), typeof(CustomerStruct).GetField("Name"), new TagDecorator(2, WireType.String, false, PrimitiveSerializer <StringSerializer> .Singleton)) }, null, false, true, null, null, null); var ser = CompilerContext.BuildSerializer(head, model); var deser = CompilerContext.BuildDeserializer(head, model); CustomerStruct cs1 = new CustomerStruct { Id = 123, Name = "Fred" }; using (MemoryStream ms = new MemoryStream()) { using (ProtoWriter writer = ProtoWriter.Create(out var state, ms, null, null)) { ser(writer, ref state, cs1); writer.Close(ref state); } byte[] blob = ms.ToArray(); ms.Position = 0; using (ProtoReader reader = ProtoReader.Create(out var state, ms, null, null)) { CustomerStruct?cst = (CustomerStruct?)deser(reader, ref state, null); Assert.True(cst.HasValue); CustomerStruct cs2 = cst.Value; Assert.Equal(cs1.Id, cs2.Id); Assert.Equal(cs1.Name, cs2.Name); } } }
/// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream, /// with a length-prefix. This is useful for socket programming, /// as DeserializeWithLengthPrefix can be used to read the single object back /// from an ongoing stream. /// </summary> /// <param name="type">The type being serialized.</param> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="style">How to encode the length prefix.</param> /// <param name="dest">The destination stream to write to.</param> /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param> public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber) { if (type == null) { if (value == null) { throw new ArgumentNullException("value"); } type = value.GetType(); } int key = GetKey(ref type); using (ProtoWriter writer = new ProtoWriter(dest, this)) { switch (style) { case PrefixStyle.None: Serialize(key, value, writer); break; case PrefixStyle.Base128: case PrefixStyle.Fixed32: case PrefixStyle.Fixed32BigEndian: ProtoWriter.WriteObject(value, key, writer, style, fieldNumber); break; default: throw new ArgumentOutOfRangeException("style"); } writer.Close(); } }
public object DeepClone(object value) { int num2; object obj2; if (value == null) { return(null); } Type type = value.GetType(); int key = this.GetKey(ref type); if ((key >= 0) && !Helpers.IsEnum(type)) { using (MemoryStream stream = new MemoryStream()) { using (ProtoWriter writer = new ProtoWriter(stream, this, null)) { writer.SetRootObject(value); this.Serialize(key, value, writer); writer.Close(); } stream.Position = 0L; using (ProtoReader reader = new ProtoReader(stream, this, null)) { return(this.Deserialize(key, null, reader)); } } } if (type == typeof(byte[])) { byte[] from = (byte[])value; byte[] to = new byte[from.Length]; Helpers.BlockCopy(from, 0, to, 0, from.Length); return(to); } if ((this.GetWireType(Helpers.GetTypeCode(type), DataFormat.Default, ref type, out num2) != WireType.None) && (num2 < 0)) { return(value); } using (MemoryStream stream2 = new MemoryStream()) { using (ProtoWriter writer2 = new ProtoWriter(stream2, this, null)) { if (!this.TrySerializeAuxiliaryType(writer2, type, DataFormat.Default, 1, value, false)) { ThrowUnexpectedType(type); } writer2.Close(); } stream2.Position = 0L; using (ProtoReader reader2 = new ProtoReader(stream2, this, null)) { value = null; this.TryDeserializeAuxiliaryType(reader2, DataFormat.Default, 1, type, ref value, true, false, true, false); obj2 = value; } } return(obj2); }
public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber, SerializationContext context) { if (type == (Type)null) { if (value == null) { throw new ArgumentNullException("value"); } type = MapType(value.GetType()); } int key = GetKey(ref type); using (ProtoWriter protoWriter = new ProtoWriter(dest, this, context)) { if (style != 0) { if ((uint)(style - 1) <= 2u) { ProtoWriter.WriteObject(value, key, protoWriter, style, fieldNumber); goto IL_0069; } throw new ArgumentOutOfRangeException("style"); } Serialize(key, value, protoWriter); goto IL_0069; IL_0069: protoWriter.Close(); } }
/// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream. /// </summary> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="dest">The destination stream to write to.</param> public void Serialize(Stream dest, object value) { using (ProtoWriter writer = new ProtoWriter(dest, this)) { SerializeCore(writer, value); writer.Close(); } }
public void Serialize(Stream dest, object value, SerializationContext context) { using (ProtoWriter protoWriter = new ProtoWriter(dest, this, context)) { protoWriter.SetRootObject(value); SerializeCore(protoWriter, value); protoWriter.Close(); } }
/// <summary> /// Create a deep clone of the supplied instance; any sub-items are also cloned. /// </summary> public object DeepClone(object value) { if (value == null) { return(null); } Type type = value.GetType(); int key = GetKey(ref type); if (key >= 0) { using (MemoryStream ms = new MemoryStream()) { using (ProtoWriter writer = new ProtoWriter(ms, this)) { Serialize(key, value, writer); writer.Close(); } ms.Position = 0; using (ProtoReader reader = new ProtoReader(ms, this)) { return(Deserialize(key, null, reader)); } } } int modelKey; if (type == typeof(byte[])) { byte[] orig = (byte[])value, clone = new byte[orig.Length]; Helpers.BlockCopy(orig, 0, clone, 0, orig.Length); return(clone); } else if (GetWireType(Type.GetTypeCode(type), DataFormat.Default, ref type, out modelKey) != WireType.None && modelKey < 0) { // immutable; just return the original value return(value); } using (MemoryStream ms = new MemoryStream()) { using (ProtoWriter writer = new ProtoWriter(ms, this)) { if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value)) { ThrowUnexpectedType(type); } writer.Close(); } ms.Position = 0; using (ProtoReader reader = new ProtoReader(ms, this)) { value = null; // start from scratch! TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false); return(value); } } }
static LuaObject testLuaProto <T>(T t, byte[] csdata) where T : class { if (null == t) { return(null); } LuaObject luaPacket; byte[] luadata; //读取 UnityEngine.Debug.LogError("========================Lua Read"); using (MemoryStream ms = new MemoryStream(csdata)) { using (ProtoReader pr = new ProtoReader(ms, RuntimeTypeModel.Default, null)) { luaPacket = LuaObject.newObject(t.GetType().Name); if (luaPacket == null) { return(null); } luaPacket.call("Deserialize", pr); } } //写入 UnityEngine.Debug.LogError("========================Lua Write"); using (MemoryStream ms = new MemoryStream()) { using (ProtoWriter pw = new ProtoWriter(ms, RuntimeTypeModel.Default, null)) { luaPacket.call("Serializer", pw); pw.Close(); luadata = ms.ToArray(); } } //校验 if (csdata.Length != luadata.Length) { UnityEngine.Debug.LogError("==========data error= " + csdata.Length + "," + luadata.Length); return(null); } for (int i = 0; i < csdata.Length; ++i) { if (csdata[i] == luadata[i]) { continue; } UnityEngine.Debug.LogError("==========data error"); return(null); } UnityEngine.Debug.LogError("==========data ok"); return(luaPacket); }
public static byte[] toCS(LuaObject luaPacket) { byte[] luadata; using (MemoryStream ms = new MemoryStream()) { using (ProtoWriter pw = new ProtoWriter(ms, RuntimeTypeModel.Default, null)) { luaPacket.call("Serializer", pw); pw.Close(); luadata = ms.ToArray(); } } return(luadata); }
public void Serialize(Stream destination, object clsObj) { SInstance sInstance = clsObj as SInstance; if (sInstance == null) { throw new ArgumentNullException("无效CSLight脚本对象: " + clsObj); } using (ProtoWriter writer = new ProtoWriter(destination, null, null)) { WriteSInstance(writer, sInstance); writer.Close(); } }
public void Dispose() { using (writer) { if (writer != null) { writer.Close(); } } writer = null; using (stream) { if (stream != null) { stream.Close(); } } stream = null; }
//将proto数据包(原始包msgData)封包,encrypt表示是否加密数据包 protected virtual void EncodeMeta(MemoryStream ms) { LuaObject luaPacket = mMetaPacket as LuaObject; if (luaPacket == null) { Serializer.Serialize(ms, mMetaPacket); } else { ProtoWriter pw = new ProtoWriter(ms, RuntimeTypeModel.Default, null); luaPacket.call("Serializer", pw); pw.Close(); } }
byte[] Serialize(TypeModel model, object value) { Type type = value.GetType(); int key = model.GetKey(ref type); using (MemoryStream ms = new MemoryStream()) { using (ProtoWriter writer = ProtoWriter.Create(ms, model, null)) { writer.SetRootObject(value); model.Serialize(key, value, writer); writer.Close(); return(ms.ToArray()); } } }
#pragma warning disable RCS1163 // Unused parameter. public static void Test(object obj, ProtoSerializer serializer, string message, byte[] expected) #pragma warning restore RCS1163 // Unused parameter. { byte[] data; using (MemoryStream ms = new MemoryStream()) { long reported; using (ProtoWriter writer = ProtoWriter.Create(out var state, ms, RuntimeTypeModel.Default, null)) { serializer(writer, ref state, obj); writer.Close(ref state); reported = ProtoWriter.GetLongPosition(writer, ref state); } data = ms.ToArray(); Assert.Equal(reported, data.Length); //, message + ":reported/actual"); } Assert.Equal(expected.Length, data.Length); //, message + ":Length"); for (int i = 0; i < data.Length; i++) { Assert.Equal(expected[i], data[i]); //, message + ":" + i); } }
private void FillBuffer(int requestedLength) { // Only supports 1 data table currently. WriteHeaderIfRequired(); // write the rows while (bufferStream.Length < requestedLength) { // NB protobuf-net only flushes every 1024 bytes. So // it might take a few iterations for bufferStream.Length to // see any change. if (reader.Read()) { rowWriter.WriteRow(reader); } else { resultIndex++; ProtoWriter.EndSubItem(currentResultToken, writer); if (reader.NextResult()) { // Start next data table. isHeaderWritten = false; FillBuffer(requestedLength); } else { // All done, no more results. writer.Close(); Close(); } break; } } }
public object DeepClone(object value) { if (value == null) { return(null); } Type type = value.GetType(); int key = GetKey(ref type); if (key >= 0 && !Helpers.IsEnum(type)) { using (MemoryStream memoryStream = new MemoryStream()) { using (ProtoWriter protoWriter = new ProtoWriter(memoryStream, this, null)) { protoWriter.SetRootObject(value); Serialize(key, value, protoWriter); protoWriter.Close(); } memoryStream.Position = 0L; ProtoReader protoReader = null; try { protoReader = ProtoReader.Create(memoryStream, this, null, -1); return(Deserialize(key, null, protoReader)); } finally { ProtoReader.Recycle(protoReader); } } } if (type == typeof(byte[])) { byte[] array = (byte[])value; byte[] array2 = new byte[array.Length]; Helpers.BlockCopy(array, 0, array2, 0, array.Length); return(array2); } if (GetWireType(Helpers.GetTypeCode(type), DataFormat.Default, ref type, out int modelKey) != WireType.None && modelKey < 0) { return(value); } using (MemoryStream memoryStream2 = new MemoryStream()) { using (ProtoWriter protoWriter2 = new ProtoWriter(memoryStream2, this, null)) { if (!TrySerializeAuxiliaryType(protoWriter2, type, DataFormat.Default, 1, value, isInsideList: false)) { ThrowUnexpectedType(type); } protoWriter2.Close(); } memoryStream2.Position = 0L; ProtoReader reader = null; try { reader = ProtoReader.Create(memoryStream2, this, null, -1); value = null; TryDeserializeAuxiliaryType(reader, DataFormat.Default, 1, type, ref value, skipOtherFields: true, asListItem: false, autoCreate: true, insideList: false); return(value); } finally { ProtoReader.Recycle(reader); } } }
public void CheckPerformanceNotInsanelyBad() { var model = TypeModel.Create(); model.Add(typeof(PropsViaDictionaryDefault), true); model.Add(typeof(PropsViaDictionaryGrouped), true); model.Add(typeof(PropsViaProperties), true); model.CompileInPlace(); var o1 = new PropsViaProperties { Field1 = 123, Field2 = 456, Field3 = 789 }; var o2 = new PropsViaDictionaryDefault() { Values = new List <KeyValuePair> { new KeyValuePair { Key = "Field1", Value = 123 }, new KeyValuePair { Key = "Field2", Value = 456 }, new KeyValuePair { Key = "Field2", Value = 789 }, } }; var o3 = new PropsViaDictionaryGrouped() { Values = new List <KeyValuePair> { new KeyValuePair { Key = "Field1", Value = 123 }, new KeyValuePair { Key = "Field2", Value = 456 }, new KeyValuePair { Key = "Field2", Value = 789 }, } }; int s1, s2, s3, d1, d2, d3; int l1 = BulkTest(model, o1, out s1, out d1); int l2 = BulkTest(model, o2, out s2, out d2); int l3 = BulkTest(model, o2, out s3, out d3); Console.WriteLine("Bytes (props)\t" + l1); Console.WriteLine("Ser (props)\t" + s1); Console.WriteLine("Deser (props)\t" + d1); Console.WriteLine("Bytes (kv-default)\t" + l2); Console.WriteLine("Ser (kv-default)\t" + s2); Console.WriteLine("Deser (kv-default)\t" + d2); Console.WriteLine("Bytes (kv-grouped)\t" + l3); Console.WriteLine("Ser (kv-grouped)\t" + s3); Console.WriteLine("Deser (kv-grouped)\t" + d3); var pw = new ProtoWriter(Stream.Null, null, null); Stopwatch watch = Stopwatch.StartNew(); for (int i = 0; i < LOOP; i++) { ProtoWriter.WriteFieldHeader(1, WireType.String, pw); ProtoWriter.WriteString("Field1", pw); ProtoWriter.WriteFieldHeader(1, WireType.String, pw); ProtoWriter.WriteString("Field2", pw); ProtoWriter.WriteFieldHeader(1, WireType.String, pw); ProtoWriter.WriteString("Field3", pw); } watch.Stop(); pw.Close(); Console.WriteLine("Encoding: " + watch.ElapsedMilliseconds); }
/// <summary> /// Create a deep clone of the supplied instance; any sub-items are also cloned. /// </summary> public object DeepClone(object value) { if (value == null) return null; Type type = value.GetType(); int key = GetKey(ref type); if (key >= 0) { using (MemoryStream ms = new MemoryStream()) { using(ProtoWriter writer = new ProtoWriter(ms, this)) { Serialize(key, value, writer); writer.Close(); } ms.Position = 0; using (ProtoReader reader = new ProtoReader(ms, this)) { return Deserialize(key, null, reader); } } } int modelKey; if (type == typeof(byte[])) { byte[] orig = (byte[])value, clone = new byte[orig.Length]; Helpers.BlockCopy(orig, 0, clone, 0, orig.Length); return clone; } else if (GetWireType(Type.GetTypeCode(type), DataFormat.Default, ref type, out modelKey) != WireType.None && modelKey < 0) { // immutable; just return the original value return value; } using (MemoryStream ms = new MemoryStream()) { using (ProtoWriter writer = new ProtoWriter(ms, this)) { if (!TrySerializeAuxiliaryType(writer, type, DataFormat.Default, Serializer.ListItemTag, value)) ThrowUnexpectedType(type); writer.Close(); } ms.Position = 0; using (ProtoReader reader = new ProtoReader(ms, this)) { value = null; // start from scratch! TryDeserializeAuxiliaryType(reader, DataFormat.Default, Serializer.ListItemTag, type, ref value, true, false); return value; } } }
/// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream, /// with a length-prefix. This is useful for socket programming, /// as DeserializeWithLengthPrefix can be used to read the single object back /// from an ongoing stream. /// </summary> /// <param name="type">The type being serialized.</param> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="style">How to encode the length prefix.</param> /// <param name="dest">The destination stream to write to.</param> /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param> public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber) { if (type == null) { if(value == null) throw new ArgumentNullException("value"); type = value.GetType(); } int key = GetKey(ref type); using (ProtoWriter writer = new ProtoWriter(dest, this)) { switch (style) { case PrefixStyle.None: Serialize(key, value, writer); break; case PrefixStyle.Base128: case PrefixStyle.Fixed32: case PrefixStyle.Fixed32BigEndian: ProtoWriter.WriteObject(value, key, writer, style, fieldNumber); break; default: throw new ArgumentOutOfRangeException("style"); } writer.Close(); } }
/// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream. /// </summary> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="dest">The destination stream to write to.</param> public void Serialize(Stream dest, object value) { using (ProtoWriter writer = new ProtoWriter(dest, this)) { SerializeCore(writer, value); writer.Close(); } }
public object DeepClone(object value) { if (value == null) { return(null); } Type type = value.GetType(); int key = this.GetKey(ref type); object result; if (key >= 0 && !Helpers.IsEnum(type)) { using (MemoryStream ms = new MemoryStream()) { using (ProtoWriter writer = new ProtoWriter(ms, this, null)) { writer.SetRootObject(value); this.Serialize(key, value, writer); writer.Close(); } ms.Position = 0L; ProtoReader reader = null; try { reader = ProtoReader.Create(ms, this, null, -1); result = this.Deserialize(key, null, reader); return(result); } finally { ProtoReader.Recycle(reader); } } } if (type == typeof(byte[])) { byte[] orig = (byte[])value; byte[] clone = new byte[orig.Length]; Helpers.BlockCopy(orig, 0, clone, 0, orig.Length); return(clone); } int modelKey; if (this.GetWireType(Helpers.GetTypeCode(type), DataFormat.Default, ref type, out modelKey) != WireType.None && modelKey < 0) { return(value); } using (MemoryStream ms2 = new MemoryStream()) { using (ProtoWriter writer2 = new ProtoWriter(ms2, this, null)) { if (!this.TrySerializeAuxiliaryType(writer2, type, DataFormat.Default, 1, value, false)) { TypeModel.ThrowUnexpectedType(type); } writer2.Close(); } ms2.Position = 0L; ProtoReader reader2 = null; try { reader2 = ProtoReader.Create(ms2, this, null, -1); value = null; this.TryDeserializeAuxiliaryType(reader2, DataFormat.Default, 1, type, ref value, true, false, true, false); result = value; } finally { ProtoReader.Recycle(reader2); } } return(result); }