Example #1
0
        public object Read(ProtoReader reader)
        {
            IList list = (isArray ? new ArrayList() : (IList)Activator.CreateInstance(listType));

            int fieldNumber;
            int messageSize = reader.BeginSubMessage();
            while ((fieldNumber = reader.ReadTag()) > 0)
            {
                object value;

                if (reader.WireType == WireType.Null)
                {
                    value = reader.ReadNull();
                }
                else
                {
                    value = this.typeDescription.NestedMessageSerializer.Read(reader);
                }

                list.Add(value);
            }
            reader.EndSubMessage(messageSize);

            if (isArray)
            {
                int length = list.Count;

                Array array = Array.CreateInstance(elementType, length);
                list.CopyTo(array, 0);

                return array;
            }

            return list;
        }
Example #2
0
 public void GenerateTypeSerializer()
 {
     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,  new Int32Serializer())),
             new FieldDecorator(typeof(CustomerStruct), typeof(CustomerStruct).GetField("Name"), new TagDecorator(2, WireType.String,false,  new StringSerializer()))
         }, null, false, true, null, null, null);
     var ser = CompilerContext.BuildSerializer(head);
     var deser = CompilerContext.BuildDeserializer(head);
     CustomerStruct cs1 = new CustomerStruct { Id = 123, Name = "Fred" };
     using (MemoryStream ms = new MemoryStream())
     {
         using (ProtoWriter writer = new ProtoWriter(ms, null, null))
         {
             ser(cs1, writer);
         }
         byte[] blob = ms.ToArray();
         ms.Position = 0;
         using (ProtoReader reader = new ProtoReader(ms, null, null))
         {
             CustomerStruct? cst = (CustomerStruct?)deser(null, reader);
             Assert.IsTrue(cst.HasValue);
             CustomerStruct cs2 = cst.Value;
             Assert.AreEqual(cs1.Id, cs2.Id);
             Assert.AreEqual(cs1.Name, cs2.Name);
         }
     }
 }
Example #3
0
        //TODO: TimeZone
        public object Read(ProtoReader reader)
        {
            long ticks = 0;

            int offset = 0;
            byte[] buffer = reader.ReadByteArray();

            ticks |= (long)buffer[offset++];
            ticks |= (long)buffer[offset++] << 8;
            ticks |= (long)buffer[offset++] << 16;
            ticks |= (long)buffer[offset++] << 24;
            ticks |= (long)buffer[offset++] << 32;
            ticks |= (long)buffer[offset++] << 40;
            ticks |= (long)buffer[offset++] << 48;
            ticks |= (long)buffer[offset++] << 56;

            DateTimeKind kind = (DateTimeKind)buffer[offset++];

            if (kind == DateTimeKind.Local)
            {
                return new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
            }

            return new DateTime(ticks, kind);
        }
        public override object Read(object value, ProtoReader source)
        {
            Helpers.DebugAssert(value == null); // not expecting incoming
            string s = (string)Tail.Read(null, source);

            return s.Length == 0 ? null : typeConstructor.Invoke(new object[] { s });
        }
 public object Read(object value, ProtoReader source)
 {
     return this.parse.Invoke(null, new object[]
     {
         source.ReadString()
     });
 }
Example #6
0
 public override object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(fieldNumber == source.FieldNumber);
     if (strict) { source.Assert(wireType); }
     else if (NeedsHint) { source.Hint(wireType); }
     return Tail.Read(value, source);
 }
Example #7
0
 public override object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value != null);
     object newValue = Tail.Read((Tail.RequiresOldValue ? field.GetValue(value) : null), source);
     if(newValue != null) field.SetValue(value,newValue);
     return null;
 }
Example #8
0
 public object Read(ProtoReader reader)
 {
     ulong raw = reader.ReadVarint64();
     unsafe
     {
         return *((double*)&raw);
     }
 }
Example #9
0
 public object Read(ProtoReader reader)
 {
     uint raw = reader.ReadVarint();
     unsafe
     {
         return *((float*)&raw);
     }
 }
Example #10
0
 public override object Read(object value, ProtoReader source)
 {
     object obj = this.Tail.Read((!this.Tail.RequiresOldValue) ? null : this.field.GetValue(value), source);
     if (obj != null)
     {
         this.field.SetValue(value, obj);
     }
     return null;
 }
Example #11
0
        public object Read(ProtoReader reader)
        {
            int[] bits = new int[4];
            byte[] buffer = reader.ReadByteArray();

            Buffer.BlockCopy(buffer, 0, bits, 0, buffer.Length);

            return new Decimal(bits);
        }
Example #12
0
        public object Read(ProtoReader reader)
        {
            if (reader.WireType == WireType.Null)
            {
                return reader.ReadNull();
            }

            return typeDescription.NestedMessageSerializer.Read(reader);
        }
 public object Read(object value, ProtoReader source)
 {
     // convert the incoming value
     object[] args = { value };
     value = toTail.Invoke(null, args);
     
     // invoke the tail and convert the outgoing value
     args[0] = rootTail.Read(value, source);
     return fromTail.Invoke(null, args);
 }
Example #14
0
 public object Read(ProtoReader reader)
 {
     if (reader.WireType == WireType.Null)
     {
         return reader.ReadNull();
     }
     else
     {
         return reader.ReadString();
     }
 }
Example #15
0
        public object Read(ProtoReader reader)
        {
            int fn = reader.ReadTag();

            if (fn == 0)
            {
                throw new InvalidProgramException();
            }

            return this.itemSerializer.Read(reader);
        }
 public override object Read(object value, ProtoReader source)
 {
     object result = this.Tail.Read(value, source);
     if (this.setSpecified != null)
     {
         this.setSpecified.Invoke(value, new object[]
         {
             true
         });
     }
     return result;
 }
        public override object Read(object value, ProtoReader source)
        {
            Helpers.DebugAssert(value != null);

            object oldVal = Tail.RequiresOldValue ? property.GetValue(value, null) : null;
            object newVal = Tail.Read(oldVal, source);
            if (readOptionsWriteValue)
            {
                property.SetValue(value, newVal, null);
            }
            return null;
        }
        /// <summary>
        /// Initializes a new instance of a <see cref="ProtoBuf.Data.ProtoDataReader"/> type.
        /// </summary>
        /// <param name="stream">The <see cref="System.IO.Stream"/> to read from.</param>

        public ProtoDataReader(Stream stream)

        {
            if (stream == null) throw new ArgumentNullException("stream");
            this.stream = stream;
            reader = new ProtoReader(stream, null, null);
            colReaders = new List<ColReader>();

            AdvanceToNextField();
            if (currentField != 1)
                throw new InvalidOperationException("No results found! Invalid/corrupt stream.");

            ReadNextTableHeader();
        }
Example #19
0
 public object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value == null); // since replaces
     int wireValue = source.ReadInt32();
     if(map == null) {
         return WireToEnum(wireValue);
     }
     for(int i = 0 ; i < map.Length ; i++) {
         if(map[i].WireValue == wireValue) {
             return map[i].Value;
         }
     }
     source.ThrowEnumException(ExpectedType, wireValue);
     return null; // to make compiler happy
 }
Example #20
0
        public object Read(ProtoReader reader)
        {
            if (reader.WireType == WireType.Null)
            {
                return reader.ReadNull();
            }

            object value = null;

            int messageSize = reader.BeginSubMessage();
            value = this.itemSerializer.Read(reader);
            reader.EndSubMessage(messageSize);

            return value;
        }
Example #21
0
 public object Read(ProtoReader reader)
 {
     switch (this.typeCode)
     {
         case TypeCode.Byte:
         case TypeCode.SByte:
         case TypeCode.Int16:
         case TypeCode.Int32:
         case TypeCode.UInt16:
         case TypeCode.UInt32:
             return Enum.ToObject(enumType, reader.ReadVarint());
         case TypeCode.Int64:
         case TypeCode.UInt64:
         default:
             return Enum.ToObject(enumType, reader.ReadVarint64());
     }
 }
Example #22
0
 public object Read(object value, ProtoReader source)
 {
     int num = source.ReadInt32();
     if (this.map == null)
     {
         return this.WireToEnum(num);
     }
     for (int i = 0; i < this.map.Length; i++)
     {
         if (this.map[i].WireValue == num)
         {
             return this.map[i].TypedValue;
         }
     }
     source.ThrowEnumException(this.ExpectedType, num);
     return null;
 }
Example #23
0
        public object Read(ProtoReader reader)
        {
            object instance = Activator.CreateInstance(objectType);
            int fn;

            while((fn = reader.ReadTag()) > 0)
            {
                IMemberSerializer serializer = GetSerializerByFieldNumber(fn);

                if (serializer == null)
                    continue;

                serializer.Read(reader, instance);
            }

            return instance;
        }
Example #24
0
 public override object Read(object value, ProtoReader source)
 {
     SubItemToken token = ProtoReader.StartSubItem(source);
     int num;
     while ((num = source.ReadFieldHeader()) > 0)
     {
         if (num == 1)
         {
             value = this.Tail.Read(value, source);
         }
         else
         {
             source.SkipField();
         }
     }
     ProtoReader.EndSubItem(token, source);
     return value;
 }
Example #25
0
        public override object Read(object value, ProtoReader source)
        {
            Helpers.DebugAssert(value != null);

            object oldVal = Tail.RequiresOldValue ? property.GetValue(value, null) : null;
            object newVal = Tail.Read(oldVal, source);
            if (readOptionsWriteValue && newVal != null) // if the tail returns a null, intepret that as *no assign*
            {
                if (shadowSetter == null)
                {
                    property.SetValue(value, newVal, null);
                }
                else
                {
                    shadowSetter.Invoke(value, new object[] { newVal });
                }
            }
            return null;
        }
Example #26
0
 /// <summary>
 /// Reads the body of an object
 /// </summary>
 public override object ReadObject(System.Xml.XmlDictionaryReader reader, bool verifyObjectName)
 {
     if (reader.GetAttribute("nil") == "true") return null;
     reader.ReadStartElement(PROTO_ELEMENT);
     try
     {
         using (MemoryStream ms = new MemoryStream(reader.ReadContentAsBase64()))
         {
             using (ProtoReader protoReader = new ProtoReader(ms, model, null))
             {
                 return model.Deserialize(key, null, protoReader);
             }
         }
     }
     finally
     {
         reader.ReadEndElement();
     }
 }
 public override object Read(object value, ProtoReader source)
 {
     object obj = this.builderFactory.Invoke(null, null);
     int fieldNumber = source.FieldNumber;
     object[] array = new object[1];
     if (base.AppendToCollection && value != null && ((IList)value).Count != 0)
     {
         if (this.addRange != null)
         {
             array[0] = value;
             this.addRange.Invoke(obj, array);
         }
         else
         {
             foreach (object current in ((IList)value))
             {
                 array[0] = current;
                 this.add.Invoke(obj, array);
             }
         }
     }
     if (this.packedWireType != WireType.None && source.WireType == WireType.String)
     {
         SubItemToken token = ProtoReader.StartSubItem(source);
         while (ProtoReader.HasSubValue(this.packedWireType, source))
         {
             array[0] = this.Tail.Read(null, source);
             this.add.Invoke(obj, array);
         }
         ProtoReader.EndSubItem(token, source);
     }
     else
     {
         do
         {
             array[0] = this.Tail.Read(null, source);
             this.add.Invoke(obj, array);
         }
         while (source.TryReadFieldHeader(fieldNumber));
     }
     return this.finish.Invoke(obj, null);
 }
Example #28
0
 public override object Read(object value, ProtoReader source)
 {
     object value2 = (!this.Tail.RequiresOldValue) ? null : this.property.GetValue(value, null);
     object obj = this.Tail.Read(value2, source);
     if (this.readOptionsWriteValue && obj != null)
     {
         if (this.shadowSetter == null)
         {
             this.property.SetValue(value, obj, null);
         }
         else
         {
             this.shadowSetter.Invoke(value, new object[]
             {
                 obj
             });
         }
     }
     return null;
 }
Example #29
0
        public void RunStructDesrializerForEmptyStream()
        {
            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, new Int32Serializer())),
                    new FieldDecorator(typeof(CustomerStruct), typeof(CustomerStruct).GetField("Name"), new TagDecorator(2, WireType.String, false, new StringSerializer()))
                }, null, false, true, null, null, null);
            var deser = CompilerContext.BuildDeserializer(head);

            using (var reader = new ProtoReader(Stream.Null, null, null))
            {
                Assert.IsInstanceOfType(typeof(CustomerStruct), deser(null, reader));
            }
            using (var reader = new ProtoReader(Stream.Null, null, null))
            {
                CustomerStruct before = new CustomerStruct { Id = 123, Name = "abc" };
                CustomerStruct after = (CustomerStruct)deser(before, reader);
                Assert.AreEqual(before.Id, after.Id);
                Assert.AreEqual(before.Name, after.Name);
            }
        }
Example #30
0
 public object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return(BclHelpers.ReadTimeSpan(source));
 }
 public virtual object Read(object value, ProtoReader source)
 {
     return(source.ReadUInt16());
 }
Example #32
0
 object IProtoSerializer.Read(ProtoReader source, ref ProtoReader.State state, object value)
 {
     return(ProtoReader.ReadObject(value, key, source, ref state));
 }
 public override object Read(object value, ProtoReader source)
 {
     return(Tail.Read(value, source));
 }
Example #34
0
 public virtual object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return(ValueObject.Get(source.ReadUInt16()));
 }
 object IProtoSerializer.Read(ProtoReader source, ref ProtoReader.State state, object value)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return(source.ReadType(ref state));
 }
Example #36
0
        object BuildBody(uint realEMsg, Stream str)
        {
            EMsg eMsg = MsgUtil.GetMsg(realEMsg);

            if (eMsg == EMsg.ClientLogonGameServer)
            {
                eMsg = EMsg.ClientLogon; // temp hack for now
            }
            else if (eMsg == EMsg.ClientGamesPlayedWithDataBlob)
            {
                eMsg = EMsg.ClientGamesPlayed;
            }

            var protomsgType = typeof(CMClient).Assembly.GetTypes().ToList().Find(type =>
            {
                if (type.GetInterfaces().ToList().Find(inter => inter == typeof(IExtensible)) == null)
                {
                    return(false);
                }

                if (type.Name.EndsWith(eMsg.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                return(false);
            });

            if (protomsgType != null)
            {
                return(RuntimeTypeModel.Default.Deserialize(str, null, protomsgType));
            }

            // lets first find the type by checking all EMsgs we have
            var msgType = typeof(CMClient).Assembly.GetTypes().ToList().Find(type =>
            {
                if (type.GetInterfaces().ToList().Find(inter => inter == typeof(ISteamSerializableMessage)) == null)
                {
                    return(false);
                }

                var gcMsg = Activator.CreateInstance(type) as ISteamSerializableMessage;

                return(gcMsg.GetEMsg() == eMsg);
            });

            string eMsgName = eMsg.ToString();

            eMsgName = eMsgName.Replace("Econ", "").Replace("AM", "");

            // check name
            if (msgType == null)
            {
                msgType = GetSteamKitType(string.Format("SteamKit2.Msg{0}", eMsgName));
            }


            if (msgType != null)
            {
                var body = Activator.CreateInstance(msgType) as ISteamSerializableMessage;
                body.Deserialize(str);

                return(body);
            }

            msgType = GetSteamKitType(string.Format("SteamKit2.CMsg{0}", eMsgName));
            if (msgType != null)
            {
                return(Deserialize(msgType, str));
            }

            if (eMsg == EMsg.ClientToGC || eMsg == EMsg.ClientFromGC)
            {
                return(Serializer.Deserialize <CMsgGCClient>(str));
            }

            var gcMsgName = BuildEMsg(realEMsg);
            var gcMsgPossibleTypePrefixes = new[]
            {
                "SteamKit2.GC.Internal.CMsg",
                "SteamKit2.GC.Dota.Internal.CMsg",
                "SteamKit2.GC.CSGO.Internal.CMsg",
                "SteamKit2.GC.TF.Internal.CMsg",
            };

            var typeMsgName = gcMsgName
                              .Replace("GC", string.Empty)
                              .Replace("k_", string.Empty)
                              .Replace("ESOMsg", string.Empty)
                              .TrimStart('_')
                              .Replace("EMsg", string.Empty);


            if (typeMsgName == "Create" || typeMsgName == "Destroy" || typeMsgName == "Update")
            {
                typeMsgName = "SingleObject";
            }
            else if (typeMsgName == "Multiple")
            {
                typeMsgName = "MultipleObjects";
            }

            var possibleTypes = from type in typeof(CMClient).Assembly.GetTypes()
                                from typePrefix in gcMsgPossibleTypePrefixes
                                where type.GetInterfaces().Contains(typeof(IExtensible))
                                where type.FullName.StartsWith(typePrefix) && type.FullName.EndsWith(typeMsgName)
                                select type;

            foreach (var type in possibleTypes)
            {
                var streamPos = str.Position;
                try
                {
                    return(Deserialize(type, str));
                }
                catch (Exception)
                {
                    str.Position = streamPos;
                }
            }

            if (!MsgUtil.IsProtoBuf(realEMsg))
            {
                return(null);
            }

            // try reading it as a protobuf
            using (ProtoReader reader = new ProtoReader(str, null, null))
            {
                var fields = new Dictionary <int, List <object> >();

                while (true)
                {
                    int field = reader.ReadFieldHeader();

                    if (field == 0)
                    {
                        break;
                    }

                    object fieldValue = null;

                    switch (reader.WireType)
                    {
                    case WireType.Variant:
                    case WireType.Fixed32:
                    case WireType.Fixed64:
                    case WireType.SignedVariant:
                    {
                        try
                        {
                            fieldValue = reader.ReadInt64();
                        }
                        catch (Exception)
                        {
                            fieldValue = "Unable to read Variant (debugme)";
                        }

                        break;
                    }

                    case WireType.String:
                    {
                        try
                        {
                            fieldValue = reader.ReadString();
                        }
                        catch (Exception)
                        {
                            fieldValue = "Unable to read String (debugme)";
                        }

                        break;
                    }

                    default:
                    {
                        fieldValue = string.Format("{0} is not implemented", reader.WireType);
                        break;
                    }
                    }

                    if (!fields.ContainsKey(field))
                    {
                        fields[field] = new List <object>();
                    }

                    fields[field].Add(fieldValue);
                }

                if (fields.Count > 0)
                {
                    return(fields);
                }
            }

            return(null);
        }
 public object Read(ProtoReader source, ref ProtoReader.State state, object value)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return(parse.Invoke(null, new object[] { source.ReadString(ref state) }));
 }
 public object Read(object value, ProtoReader source)
 {
     return(BclHelpers.ReadNetObject(value, source, key, type == typeof(object) ? null : type, options));
 }
Example #39
0
 // Token: 0x06000264 RID: 612 RVA: 0x0000250E File Offset: 0x0000070E
 object IProtoTypeSerializer.CreateInstance(ProtoReader source)
 {
     throw new NotSupportedException();
 }
 // Token: 0x060001BE RID: 446 RVA: 0x0000329C File Offset: 0x0000149C
 public object Read(object value, ProtoReader source)
 {
     return(BclHelpers.ReadDecimal(source));
 }
Example #41
0
 object IProtoSerializer.Read(object value, ProtoReader source)
 {
     return(deserializer(value, source));
 }
Example #42
0
 object IProtoTypeSerializer.CreateInstance(ProtoReader source)
 {
     return(head.CreateInstance(source));
 }
Example #43
0
 public object Read(object value, ProtoReader source)
 {
     return(source.ReadInt16());
 }
Example #44
0
 public object Read(object value, ProtoReader source)
 {
     return(ProtoReader.AppendBytes((byte[])value, source));
 }
Example #45
0
 public override object Read(object value, ProtoReader source)
 {
     try
     {
         int    field     = source.FieldNumber;
         object origValue = value;
         if (value == null)
         {
             value = Activator.CreateInstance(concreteType);
         }
         bool isList = IsList && !SuppressIList;
         if (packedWireType != WireType.None && source.WireType == WireType.String)
         {
             SubItemToken token = ProtoReader.StartSubItem(source);
             if (isList)
             {
                 IList list = (IList)value;
                 while (ProtoReader.HasSubValue(packedWireType, source))
                 {
                     list.Add(Tail.Read(null, source));
                 }
             }
             else
             {
                 object[] args = new object[1];
                 while (ProtoReader.HasSubValue(packedWireType, source))
                 {
                     args[0] = Tail.Read(null, source);
                     add.Invoke(value, args);
                 }
             }
             ProtoReader.EndSubItem(token, source);
         }
         else
         {
             if (isList)
             {
                 IList list = (IList)value;
                 do
                 {
                     list.Add(Tail.Read(null, source));
                 } while (source.TryReadFieldHeader(field));
             }
             else
             {
                 object[] args = new object[1];
                 do
                 {
                     args[0] = Tail.Read(null, source);
                     add.Invoke(value, args);
                 } while (source.TryReadFieldHeader(field));
             }
         }
         return(origValue == value ? null : value);
     } catch (TargetInvocationException tie)
     {
         if (tie.InnerException != null)
         {
             throw tie.InnerException;
         }
         throw;
     }
 }
 public object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return(parse.Invoke(null, new object[] { source.ReadString() }));
 }
#pragma warning restore xUnit1004 // Test methods should not be skipped
        public void CanSerializeLongData()
        {
            Console.WriteLine($"PID: {Process.GetCurrentProcess().Id}");
            const string path  = "large.data";
            var          watch = Stopwatch.StartNew();
            const int    COUNT = 50000000;

            Console.WriteLine($"Creating model with {COUNT} items...");
            var outer = CreateOuterModel(COUNT);

            watch.Stop();
            Console.WriteLine($"Created in {watch.ElapsedMilliseconds}ms");

            var model = new MyModelWrapper {
                Group = outer
            };
            int oldHash = model.GetHashCode();

            using (var file = File.Create(path))
            {
                Console.Write("Serializing...");
                watch = Stopwatch.StartNew();
                Serializer.Serialize(file, model);
                watch.Stop();
                Console.WriteLine();
                Console.WriteLine($"Wrote: {COUNT} in {file.Length >> 20} MiB ({file.Length / COUNT} each), {watch.ElapsedMilliseconds}ms");
            }

            using (var file = File.OpenRead(path))
            {
                Console.WriteLine($"Verifying {file.Length >> 20} MiB...");
                watch = Stopwatch.StartNew();
                using (var reader = ProtoReader.Create(out var state, file, null, null))
                {
                    int i = -1;
                    try
                    {
                        Assert.Equal(2, reader.ReadFieldHeader(ref state));
                        Assert.Equal(WireType.StartGroup, reader.WireType);
                        var tok = ProtoReader.StartSubItem(reader, ref state);

                        for (i = 0; i < COUNT; i++)
                        {
                            Assert.Equal(1, reader.ReadFieldHeader(ref state));
                            Assert.Equal(WireType.String, reader.WireType);
                            reader.SkipField(ref state);
                        }
                        Assert.False(reader.ReadFieldHeader(ref state) > 0);
                        ProtoReader.EndSubItem(tok, reader, ref state);
                    }
                    catch
                    {
                        Console.WriteLine($"field 2, {i} of {COUNT}, @ {reader.GetPosition(ref state)}");
                        throw;
                    }
                }
                watch.Start();
                Console.WriteLine($"Verified {file.Length >> 20} MiB in {watch.ElapsedMilliseconds}ms");
            }
            using (var file = File.OpenRead(path))
            {
                Console.WriteLine($"Deserializing {file.Length >> 20} MiB");
                watch = Stopwatch.StartNew();
                var clone = Serializer.Deserialize <MyModelWrapper>(file);
                watch.Stop();
                var newHash = clone.GetHashCode();
                Console.WriteLine($"{oldHash} vs {newHash}, {newHash == oldHash}, {watch.ElapsedMilliseconds}ms");
            }
        }
Example #48
0
        /// <summary>
        /// Reads the body of an object
        /// </summary>
        public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }
            reader.MoveToContent();
            bool isSelfClosed = reader.IsEmptyElement, isNil = reader.GetAttribute("nil") == "true";

            reader.ReadStartElement(PROTO_ELEMENT);

            // explicitly null
            if (isNil)
            {
                if (!isSelfClosed)
                {
                    reader.ReadEndElement();
                }
                return(null);
            }
            if (isSelfClosed) // no real content
            {
                if (isList || isEnum)
                {
                    return(model.Deserialize(Stream.Null, null, type, null));
                }
                ProtoReader protoReader = null;
                try
                {
                    protoReader = ProtoReader.Create(Stream.Null, model, null, ProtoReader.TO_EOF);
                    return(model.Deserialize(key, null, protoReader));
                }
                finally
                {
                    ProtoReader.Recycle(protoReader);
                }
            }

            object result;

            Helpers.DebugAssert(reader.CanReadBinaryContent, "CanReadBinaryContent");
            using (MemoryStream ms = new MemoryStream(reader.ReadContentAsBase64()))
            {
                if (isList || isEnum)
                {
                    result = model.Deserialize(ms, null, type, null);
                }
                else
                {
                    ProtoReader protoReader = null;
                    try
                    {
                        protoReader = ProtoReader.Create(ms, model, null, ProtoReader.TO_EOF);
                        result      = model.Deserialize(key, null, protoReader);
                    }
                    finally
                    {
                        ProtoReader.Recycle(protoReader);
                    }
                }
            }
            reader.ReadEndElement();
            return(result);
        }
Example #49
0
 public static object PrecompDeserialize(ProtobufSerializerPrecompiled model, int num, object obj, ProtoReader reader)
 {
     return(DeserializeFunc.Invoke(model, new object[] { num, obj, reader }));
 }
Example #50
0
 object IProtoSerializer.Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return(source.ReadType());
 }
Example #51
0
 public object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return(source.ReadUInt32());
 }
Example #52
0
 object IProtoTypeSerializer.CreateInstance(ProtoReader source)
 {
     return(((IProtoTypeSerializer)proxy.Serializer).CreateInstance(source));
 }
 public object CreateInstance(ProtoReader source)
 {
     return(((IProtoTypeSerializer)Tail).CreateInstance(source));
 }
Example #54
0
 /// <summary>Indicates the number of bytes expected for the next message.</summary>
 /// <param name="source">The stream containing the data to investigate for a length.</param>
 /// <param name="style">The algorithm used to encode the length.</param>
 /// <param name="length">The length of the message, if it could be identified.</param>
 /// <returns>True if a length could be obtained, false otherwise.</returns>
 public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length)
 {
     length = ProtoReader.ReadLengthPrefix(source, false, style, out int fieldNumber, out int bytesRead);
     return(bytesRead > 0);
 }
Example #55
0
    public static bool Prefix_Deserialize(ProtobufSerializerPrecompiled __instance, int num, object obj, ProtoReader reader, ref object __result)
    {
        bool shouldnotcontinue;

        __result = AlternativeSerializer.Deserialize(num, obj, reader, __instance, out shouldnotcontinue);
        return(!shouldnotcontinue);
    }
 public override object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return((char)source.ReadUInt16());
 }
Example #57
0
 object IProtoSerializer.Read(object value, ProtoReader source)
 {
     return(ProtoReader.ReadObject(value, key, source));
 }
 public override object Read(ProtoReader source, ref ProtoReader.State state, object value)
 {
     return(Tail.Read(source, ref state, value));
 }
Example #59
0
 public object Read(object value, ProtoReader source)
 {
     Helpers.DebugAssert(value == null); // since replaces
     return BclHelpers.ReadDecimal(source);
 }
Example #60
0
        public object Read(object value, ProtoReader source)
        {
            if (isRootType && value != null)
            {
                Callback(value, TypeModel.CallbackType.BeforeDeserialize, source.Context);
            }
            int  fieldNumber, lastFieldNumber = 0, lastFieldIndex = 0;
            bool fieldHandled;

            //Helpers.DebugWriteLine(">> Reading fields for " + forType.FullName);
            while ((fieldNumber = source.ReadFieldHeader()) > 0)
            {
                fieldHandled = false;
                if (fieldNumber < lastFieldNumber)
                {
                    lastFieldNumber = lastFieldIndex = 0;
                }
                for (int i = lastFieldIndex; i < fieldNumbers.Length; i++)
                {
                    if (fieldNumbers[i] == fieldNumber)
                    {
                        IProtoSerializer ser = serializers[i];
                        //Helpers.DebugWriteLine(": " + ser.ToString());
                        Type serType = ser.ExpectedType;
                        if (value == null)
                        {
                            if (serType == forType)
                            {
                                value = CreateInstance(source, true);
                            }
                        }
                        else
                        {
                            if (serType != forType && ((IProtoTypeSerializer)ser).CanCreateInstance() &&
                                serType
#if WINRT
                                .GetTypeInfo()
#endif
                                .IsSubclassOf(value.GetType()))
                            {
                                value = ProtoReader.Merge(source, value, ((IProtoTypeSerializer)ser).CreateInstance(source));
                            }
                        }

                        if (ser.ReturnsValue)
                        {
                            value = ser.Read(value, source);
                        }
                        else     // pop
                        {
                            ser.Read(value, source);
                        }

                        lastFieldIndex  = i;
                        lastFieldNumber = fieldNumber;
                        fieldHandled    = true;
                        break;
                    }
                }
                if (!fieldHandled)
                {
                    //Helpers.DebugWriteLine(": [" + fieldNumber + "] (unknown)");
                    if (value == null)
                    {
                        value = CreateInstance(source, true);
                    }
                    if (isExtensible)
                    {
                        source.AppendExtensionData((IExtensible)value);
                    }
                    else
                    {
                        source.SkipField();
                    }
                }
            }
            //Helpers.DebugWriteLine("<< Reading fields for " + forType.FullName);
            if (value == null)
            {
                value = CreateInstance(source, true);
            }
            if (isRootType)
            {
                Callback(value, TypeModel.CallbackType.AfterDeserialize, source.Context);
            }
            return(value);
        }