public void ReadWriteAutomated_StreamReaderWriter(bool withState) { var model = RuntimeTypeModel.Create(); model.AutoCompile = false; using var ms = new MemoryStream(); var obj = new C { AVal = 123, BVal = 456, CVal = 789 }; if (withState) { using var writeState = ProtoWriter.State.Create(ms, model); writeState.SerializeRoot(obj); Assert.Equal(0, writeState.Depth); writeState.Close(); } else { #pragma warning disable CS0618 using var writer = ProtoWriter.Create(ms, model); model.Serialize(writer, obj); #pragma warning restore CS0618 Assert.Equal(0, writer.Depth); } var hex = BitConverter.ToString(ms.GetBuffer(), 0, (int)ms.Length); Assert.Equal("22-08-2A-03-18-95-06-10-C8-03-08-7B", hex); // 22 = field 4, type String // 08 = length 8 // 2A = field 5, type String // 03 = length 3 // 18 = field 3, type Variant // 95-06 = 789 (raw) or -395 (zigzag) // 10 = field 2, type Variant // C8-03 = 456(raw) or 228(zigzag) // 08 = field 1, type Variant // 7B = 123(raw) or - 62(zigzag) ms.Position = 0; A raw; if (withState) { using var readState = ProtoReader.State.Create(ms, model); raw = readState.DeserializeRoot <A>(null); } else { #pragma warning disable CS0618 using var reader = ProtoReader.Create(ms, model); #pragma warning restore CS0618 raw = reader.DefaultState().DeserializeRoot <A>(null); } var clone = Assert.IsType <C>(raw); Assert.NotSame(obj, clone); Assert.Equal(123, clone.AVal); Assert.Equal(456, clone.BVal); Assert.Equal(789, clone.CVal); }
internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } // TODO //model.CheckTagNotInUse(tag); // 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 = ProtoWriter.Create(stream, model, null)) { model.TrySerializeAuxiliaryType(writer, null, format, tag, value, false, null); writer.Close(); } commit = true; } finally { extn.EndAppend(stream, commit); } }