示例#1
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);
         }
     }
 }
 public override void Write(object value, ProtoWriter dest)
 {
     if (!object.Equals(value, defaultValue))
     {
         Tail.Write(value, dest);
     }
 }
示例#3
0
        public void Writer(ProtoWriter writer, object instance)
        {
            DateTime dt = (DateTime)instance;
            byte kind = (byte)dt.Kind;
            long ticks;

            if (dt.Kind == DateTimeKind.Local)
            {
                ticks = dt.ToUniversalTime().Ticks;
            }
            else
            {
                ticks = dt.Ticks;
            }

            int offset = 0;
            byte[] buffer = new byte[9];

            buffer[offset++] = (byte)((ticks) & 0xFF);
            buffer[offset++] = (byte)((ticks >> 8) & 0xFF);
            buffer[offset++] = (byte)((ticks >> 16) & 0xFF);
            buffer[offset++] = (byte)((ticks >> 24) & 0xFF);
            buffer[offset++] = (byte)((ticks >> 32) & 0xFF);
            buffer[offset++] = (byte)((ticks >> 40) & 0xFF);
            buffer[offset++] = (byte)((ticks >> 48) & 0xFF);
            buffer[offset++] = (byte)((ticks >> 56) & 0xFF);
            buffer[offset++] = kind;

            writer.Write(buffer);
        }
示例#4
0
        public RowWriter(
            ProtoWriter writer,
            IEnumerable<ProtoDataColumn> columns,
            ProtoDataWriterOptions options)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            if (columns == null)
            {
                throw new ArgumentNullException("columns");
            }

            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            this.writer = writer;
            this.columns = columns;
            this.options = options;
            rowIndex = 0;
        }
 public override void Write(object value, ProtoWriter dest)
 {
     if(getSpecified == null || (bool)getSpecified.Invoke(value, null))
     {
         Tail.Write(value, dest);
     }
 }
        public override void Write(object value, ProtoWriter dest)
        {
            Helpers.DebugAssert(value != null);
            value = field.GetValue(value);
			//if (value!=null) Tail.Write(value, dest);
			if (!Helpers.IsDefault(value)) Tail.Write(value, dest);
        }
示例#7
0
 public void Writer(ProtoWriter writer, object instance)
 {
     switch (this.typeCode)
     {
         case TypeCode.Byte:
             writer.Write((uint)(byte)instance);
             break;
         case TypeCode.SByte:
             writer.Write((uint)(sbyte)instance);
             break;
         case TypeCode.Int16:
             writer.Write((uint)(short)instance);
             break;
         case TypeCode.Int32:
             writer.Write((uint)(int)instance);
             break;
         case TypeCode.UInt16:
             writer.Write((uint)(ushort)instance);
             break;
         case TypeCode.UInt32:
             writer.Write((uint)instance);
             break;
         case TypeCode.Int64:
             writer.Write((ulong)(long)instance);
             break;
         case TypeCode.UInt64:
             writer.Write((ulong)instance);
             break;
     }
 }
 public void Write(object value, ProtoWriter dest)
 {
     for(int i = 0 ; i < tails.Length ; i++)
     {
         object val = GetValue(value, i);
         if(val != null) tails[i].Write(val, dest);
     }
 }
示例#9
0
 public void Writer(ProtoWriter writer, object instance)
 {
     unsafe
     {
         double n = (double)instance;
         writer.Write(*((ulong*)&n));
     }
 }
示例#10
0
 public override void Write(object value, ProtoWriter dest)
 {
     value = this.field.GetValue(value);
     if (value != null)
     {
         this.Tail.Write(value, dest);
     }
 }
示例#11
0
 public void Writer(ProtoWriter writer, object instance)
 {
     unsafe
     {
         float n = (float)instance;
         writer.Write(*((uint*)&n));
     }
 }
示例#12
0
        public void Writer(ProtoWriter writer, object instance)
        {
            int[] bits = Decimal.GetBits((decimal)instance);
            byte[] buffer = new byte[Buffer.ByteLength(bits)];
            Buffer.BlockCopy(bits, 0, buffer, 0, buffer.Length);

            writer.Write(buffer);
        }
        public HeaderWriter(ProtoWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            this.writer = writer;
        }
示例#14
0
 public void Writer(ProtoWriter writer, object instance)
 {
     if (instance == null)
     {
         writer.WriteNull();
     }
     else
     {
         writer.Write((String)instance);
     }
 }
示例#15
0
 void IProtoSerializer.Write(object value, ProtoWriter dest)
 {
     if (recursionCheck)
     {
         ProtoWriter.WriteObject(value, key, dest);
     }
     else
     {
         ProtoWriter.WriteRecursionSafeObject(value, key, dest);
     }
 }
示例#16
0
 public void Writer(ProtoWriter writer, object instance)
 {
     if (instance == null)
     {
         writer.WriteNull();
     }
     else
     {
         typeDescription.NestedMessageSerializer.Writer(writer, instance);
     }
 }
示例#17
0
 public void Writer(ProtoWriter writer, object instance)
 {
     if (instance == null)
     {
         writer.WriteNull();
     }
     else
     {
         int messageId = writer.BeginSubMessage();
         this.itemSerializer.Writer(writer, instance);
         writer.EndSubMessage(messageId);
     }
 }
示例#18
0
        public void Writer(ProtoWriter writer, object instance)
        {
            bool value = (bool)instance;

            if (value)
            {
                writer.Write((uint)1);
            }
            else
            {
                writer.Write((uint)0);
            }
        }
 public void Write(object value, ProtoWriter dest)
 {
     if (map == null)
     {
         ProtoWriter.WriteInt32(EnumToWire(value), dest);
     }
     else
     {
         for (int i = 0; i < map.Length; i++) {
             if (object.Equals(map[i].Value, value)) {
                 ProtoWriter.WriteInt32(map[i].WireValue, dest);
                 return;
             }
         }
         ProtoWriter.ThrowEnumException(dest, value);
     }            
 }
 /// <summary>
 /// Writes the body of an object in the output
 /// </summary>
 public override void WriteObjectContent(System.Xml.XmlDictionaryWriter writer, object graph)
 {
     if (graph == null)
     {
         writer.WriteAttributeString("nil", "true");
     }
     else
     {
         using (MemoryStream ms = new MemoryStream())
         {
             using (ProtoWriter protoWriter = new ProtoWriter(ms, model, null))
             {
                 model.Serialize(key, graph, protoWriter);
             }
             byte[] buffer = ms.GetBuffer();
             writer.WriteBase64(buffer, 0, (int)ms.Length);
         }
     }
 }
示例#21
0
        public void Writer(ProtoWriter writer, object instance)
        {
            IEnumerable enumerable = (IEnumerable)instance;

            int messageId = writer.BeginSubMessage();

            foreach (var e in enumerable)
            {
                if (e == null)
                {
                    writer.SetFieldNumber(1);
                    writer.WriteNull();
                }
                else
                {
                    writer.SetFieldNumber(1);
                    this.typeDescription.NestedMessageSerializer.Writer(writer, e);
                }
            }

            writer.EndSubMessage(messageId);
        }
示例#22
0
 /// <summary>
 /// Writes a DateTime to a protobuf stream, including the <c>Kind</c>
 /// </summary>
 public static void WriteDateTimeWithKind(DateTime value, ProtoWriter dest)
 {
     WriteDateTimeImpl(value, dest, true);
 }
示例#23
0
 public abstract void Write(object value, ProtoWriter dest);
示例#24
0
 /// <summary>
 /// Writes a protocol-buffer representation of the given instance to the supplied stream.
 /// </summary>
 /// <param name="key">Represents the type (including inheritance) to consider.</param>
 /// <param name="value">The existing instance to be serialized (cannot be null).</param>
 /// <param name="dest">The destination stream to write to.</param>
 protected internal override void Serialize(int key, object value, ProtoWriter dest)
 {
     //Helpers.DebugWriteLine("Serialize", value);
     ((MetaType)types[key]).Serializer.Write(value, dest);
 }
示例#25
0
 public void Write(object value, ProtoWriter dest)
 {
     BclHelpers.WriteDecimal((decimal)value, dest);
 }
示例#26
0
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteBoolean((bool)value, dest);
 }
示例#27
0
 public override void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest);
     Tail.Write(value, dest);
 }
示例#28
0
 void IProtoSerializer.Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteObject(value, key, dest);
 }
 void IProtoSerializer.Write(object value, ProtoWriter dest)
 {
     serializer(value, dest);
 }
示例#30
0
 public void Write(ProtoWriter dest, ref ProtoWriter.State state, object value)
 {
     ProtoWriter.WriteByte((byte)value, dest, ref state);
 }
示例#31
0
        protected override void EmitWrite(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom)
        {
            using (Compiler.Local list = ctx.GetLocalWithValue(ExpectedType, valueFrom))
            {
                MethodInfo getEnumerator = GetEnumeratorInfo(out MethodInfo moveNext, out MethodInfo current);
                Helpers.DebugAssert(moveNext != null);
                Helpers.DebugAssert(current != null);
                Helpers.DebugAssert(getEnumerator != null);
                Type enumeratorType = getEnumerator.ReturnType;
                bool writePacked    = WritePacked;
                using (Compiler.Local iter = new Compiler.Local(ctx, enumeratorType))
                           using (Compiler.Local token = writePacked ? new Compiler.Local(ctx, typeof(SubItemToken)) : null)
                           {
                               if (writePacked)
                               {
                                   ctx.LoadValue(fieldNumber);
                                   ctx.LoadValue((int)WireType.String);
                                   ctx.LoadWriter(true);
                                   ctx.EmitCall(ProtoWriter.GetStaticMethod("WriteFieldHeader"));

                                   ctx.LoadValue(list);
                                   ctx.LoadWriter(true);
                                   ctx.EmitCall(ProtoWriter.GetStaticMethod("StartSubItem"));
                                   ctx.StoreValue(token);

                                   ctx.LoadValue(fieldNumber);
                                   ctx.LoadWriter(false);
                                   ctx.EmitCall(typeof(ProtoWriter).GetMethod("SetPackedField"));
                               }

                               ctx.LoadAddress(list, ExpectedType);
                               ctx.EmitCall(getEnumerator, ExpectedType);
                               ctx.StoreValue(iter);
                               using (ctx.Using(iter))
                               {
                                   Compiler.CodeLabel body = ctx.DefineLabel(), next = ctx.DefineLabel();
                                   ctx.Branch(next, false);

                                   ctx.MarkLabel(body);

                                   ctx.LoadAddress(iter, enumeratorType);
                                   ctx.EmitCall(current, enumeratorType);
                                   Type itemType = Tail.ExpectedType;
                                   if (itemType != typeof(object) && current.ReturnType == typeof(object))
                                   {
                                       ctx.CastFromObject(itemType);
                                   }
                                   Tail.EmitWrite(ctx, null);

                                   ctx.MarkLabel(@next);
                                   ctx.LoadAddress(iter, enumeratorType);
                                   ctx.EmitCall(moveNext, enumeratorType);
                                   ctx.BranchIfTrue(body, false);
                               }

                               if (writePacked)
                               {
                                   ctx.LoadValue(token);
                                   ctx.LoadWriter(true);
                                   ctx.EmitCall(ProtoWriter.GetStaticMethod("EndSubItem"));
                               }
                           }
            }
        }
示例#32
0
 public override void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteFieldHeader(this.fieldNumber, this.wireType, dest);
     this.Tail.Write(value, dest);
 }
示例#33
0
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteUInt32((uint)value, dest);
 }
示例#34
0
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteSByte((sbyte)value, dest);
 }
示例#35
0
 public void Write(object value, ProtoWriter dest)
 {
     BclHelpers.WriteNetObject(value, dest, key, options);
 }
 public virtual void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteUInt16((ushort)value, dest);
 }
 public abstract void Write(object value, ProtoWriter dest);
示例#38
0
        /// <summary>
        /// This is the more "complete" version of Serialize, which handles single instances of mapped types.
        /// The value is written as a complete field, including field-header and (for sub-objects) a
        /// length-prefix
        /// In addition to that, this provides support for:
        ///  - basic values; individual int / string / Guid / etc
        ///  - IEnumerable sequences of any type handled by TrySerializeAuxiliaryType
        ///
        /// </summary>
        internal bool TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, int tag, object value)
        {
            if (type == null)
            {
                type = value.GetType();
            }

            TypeCode typecode = Type.GetTypeCode(type);
            int      modelKey;
            // note the "ref type" here normalizes against proxies
            WireType wireType = GetWireType(typecode, format, ref type, out modelKey);


            if (modelKey >= 0)
            {   // write the header, but defer to the model
                ProtoWriter.WriteFieldHeader(tag, wireType, writer);
                switch (wireType)
                {
                case WireType.None:
                    throw ProtoWriter.CreateException(writer);

                case WireType.StartGroup:
                case WireType.String:
                    // needs a wrapping length etc
                    SubItemToken token = ProtoWriter.StartSubItem(value, writer);
                    Serialize(modelKey, value, writer);
                    ProtoWriter.EndSubItem(token, writer);
                    return(true);

                default:
                    Serialize(modelKey, value, writer);
                    return(true);
                }
            }

            if (wireType != WireType.None)
            {
                ProtoWriter.WriteFieldHeader(tag, wireType, writer);
            }
            switch (typecode)
            {
            case TypeCode.Int16: ProtoWriter.WriteInt16((short)value, writer); return(true);

            case TypeCode.Int32: ProtoWriter.WriteInt32((int)value, writer); return(true);

            case TypeCode.Int64: ProtoWriter.WriteInt64((long)value, writer); return(true);

            case TypeCode.UInt16: ProtoWriter.WriteUInt16((ushort)value, writer); return(true);

            case TypeCode.UInt32: ProtoWriter.WriteUInt32((uint)value, writer); return(true);

            case TypeCode.UInt64: ProtoWriter.WriteUInt64((ulong)value, writer); return(true);

            case TypeCode.Boolean: ProtoWriter.WriteBoolean((bool)value, writer); return(true);

            case TypeCode.SByte: ProtoWriter.WriteSByte((sbyte)value, writer); return(true);

            case TypeCode.Byte: ProtoWriter.WriteByte((byte)value, writer); return(true);

            case TypeCode.Char: ProtoWriter.WriteUInt16((ushort)(char)value, writer); return(true);

            case TypeCode.Double: ProtoWriter.WriteDouble((double)value, writer); return(true);

            case TypeCode.Single: ProtoWriter.WriteSingle((float)value, writer); return(true);

            case TypeCode.DateTime: BclHelpers.WriteDateTime((DateTime)value, writer); return(true);

            case TypeCode.Decimal: BclHelpers.WriteDecimal((decimal)value, writer); return(true);

            case TypeCode.String: ProtoWriter.WriteString((string)value, writer); return(true);
            }
            if (type == typeof(byte[]))
            {
                ProtoWriter.WriteBytes((byte[])value, writer); return(true);
            }
            if (type == typeof(TimeSpan))
            {
                BclHelpers.WriteTimeSpan((TimeSpan)value, writer); return(true);
            }
            if (type == typeof(Guid))
            {
                BclHelpers.WriteGuid((Guid)value, writer); return(true);
            }
            if (type == typeof(Uri))
            {
                ProtoWriter.WriteString(((Uri)value).AbsoluteUri, writer); return(true);
            }

            // by now, we should have covered all the simple cases; if we wrote a field-header, we have
            // forgotten something!
            Helpers.DebugAssert(wireType == WireType.None);

            // now attempt to handle sequences (including arrays and lists)
            IEnumerable sequence = value as IEnumerable;

            if (sequence != null)
            {
                foreach (object item in sequence)
                {
                    if (item == null)
                    {
                        throw new NullReferenceException();
                    }
                    if (!TrySerializeAuxiliaryType(writer, null, format, tag, item))
                    {
                        ThrowUnexpectedType(item.GetType());
                    }
                }
                return(true);
            }
            return(false);
        }
 public void Write(object value, ProtoWriter dest)
 {
     BclHelpers.WriteTimeSpan((TimeSpan)value, dest);
 }
 void IProtoSerializer.Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteObject(value, key, dest);
 }
示例#41
0
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteDouble((double)value, dest);
 }
示例#42
0
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteString((string)value, dest);
 }
 public void Write(object value, ProtoWriter writer)
 {
     rootTail.Write(toTail.Invoke(null, new object[] { value }), writer);
 }
示例#44
0
 public override void Write(object value, ProtoWriter dest)
 {
     Tail.Write(((Uri)value).OriginalString, dest);
 }
示例#45
0
        private static void WriteTimeSpanImpl(TimeSpan timeSpan, ProtoWriter dest, DateTimeKind kind)
        {
            if (dest == null)
            {
                throw new ArgumentNullException(nameof(dest));
            }
            switch (dest.WireType)
            {
            case WireType.String:
            case WireType.StartGroup:
                TimeSpanScale scale;
                long          value = timeSpan.Ticks;
                if (timeSpan == TimeSpan.MaxValue)
                {
                    value = 1;
                    scale = TimeSpanScale.MinMax;
                }
                else if (timeSpan == TimeSpan.MinValue)
                {
                    value = -1;
                    scale = TimeSpanScale.MinMax;
                }
                else if (value % TimeSpan.TicksPerDay == 0)
                {
                    scale  = TimeSpanScale.Days;
                    value /= TimeSpan.TicksPerDay;
                }
                else if (value % TimeSpan.TicksPerHour == 0)
                {
                    scale  = TimeSpanScale.Hours;
                    value /= TimeSpan.TicksPerHour;
                }
                else if (value % TimeSpan.TicksPerMinute == 0)
                {
                    scale  = TimeSpanScale.Minutes;
                    value /= TimeSpan.TicksPerMinute;
                }
                else if (value % TimeSpan.TicksPerSecond == 0)
                {
                    scale  = TimeSpanScale.Seconds;
                    value /= TimeSpan.TicksPerSecond;
                }
                else if (value % TimeSpan.TicksPerMillisecond == 0)
                {
                    scale  = TimeSpanScale.Milliseconds;
                    value /= TimeSpan.TicksPerMillisecond;
                }
                else
                {
                    scale = TimeSpanScale.Ticks;
                }

                SubItemToken token = ProtoWriter.StartSubItemWithoutWritingHeader(null, dest);

                if (value != 0)
                {
                    ProtoWriter.WriteFieldHeader(FieldTimeSpanValue, WireType.SignedVariant, dest);
                    ProtoWriter.WriteInt64(value, dest);
                }
                if (scale != TimeSpanScale.Days)
                {
                    ProtoWriter.WriteFieldHeader(FieldTimeSpanScale, WireType.Variant, dest);
                    ProtoWriter.WriteInt32((int)scale, dest);
                }
                if (kind != DateTimeKind.Unspecified)
                {
                    ProtoWriter.WriteFieldHeader(FieldTimeSpanKind, WireType.Variant, dest);
                    ProtoWriter.WriteInt32((int)kind, dest);
                }
                ProtoWriter.EndSubItem(token, dest);
                break;

            case WireType.Fixed64:
                ProtoWriter.WriteInt64(timeSpan.Ticks, dest);
                break;

            default:
                throw new ProtoException("Unexpected wire-type: " + dest.WireType.ToString());
            }
        }
 public void Write(object value, ProtoWriter dest)
 {
     BclHelpers.WriteNetObject(value, dest, this.key, this.options);
 }
示例#47
0
 /// <summary>
 /// Writes a TimeSpan to a protobuf stream
 /// </summary>
 public static void WriteTimeSpan(TimeSpan timeSpan, ProtoWriter dest)
 {
     WriteTimeSpanImpl(timeSpan, dest, DateTimeKind.Unspecified);
 }
示例#48
0
 // Token: 0x06003564 RID: 13668 RVA: 0x00133E01 File Offset: 0x00132201
 public void Write(object value, ProtoWriter dest)
 {
     BclHelpers.WriteGuid((Guid)value, dest);
 }
示例#49
0
 public override void Write(object value, ProtoWriter dest)
 {
     Helpers.DebugAssert(value != null);
     value = property.GetValue(value, null);
     if (value != null) Tail.Write(value, dest);
 }
示例#50
0
 public override void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteUInt16((ushort)(char)value, dest);
 }
示例#51
0
 public override void Write(object value, ProtoWriter dest)
 {
     IList arr = (IList)value;
     int len = arr.Count;
     SubItemToken token;
     bool writePacked = (options & OPTIONS_WritePacked) != 0;
     if (writePacked)
     {
         ProtoWriter.WriteFieldHeader(fieldNumber, WireType.String, dest);
         token = ProtoWriter.StartSubItem(value, dest);
         ProtoWriter.SetPackedField(fieldNumber, dest);
     }
     else
     {
         token = new SubItemToken(); // default
     }
     bool checkForNull = !SupportNull;
     for (int i = 0; i < len; i++)
     {
         object obj = arr[i];
         if (checkForNull && obj == null) { throw new NullReferenceException(); }
         Tail.Write(obj, dest);
     }
     if (writePacked)
     {
         ProtoWriter.EndSubItem(token, dest);
     }            
 }
示例#52
0
        }                                                            // updates field directly
#if FEAT_COMPILER
        void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
        {
            Type expected = ExpectedType;

            using (Compiler.Local loc = ctx.GetLocalWithValue(expected, valueFrom))
            {
                // pre-callbacks
                EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.BeforeSerialize);

                Compiler.CodeLabel startFields = ctx.DefineLabel();
                // inheritance
                if (CanHaveInheritance)
                {
                    for (int i = 0; i < serializers.Length; i++)
                    {
                        IProtoSerializer ser     = serializers[i];
                        Type             serType = ser.ExpectedType;
                        if (serType != ExpectedType)
                        {
                            Compiler.CodeLabel ifMatch = ctx.DefineLabel(), nextTest = ctx.DefineLabel();
                            ctx.LoadValue(loc);
                            ctx.TryCast(serType);
                            ctx.CopyValue();
                            ctx.BranchIfTrue(ifMatch, true);
                            ctx.DiscardValue();
                            ctx.Branch(nextTest, true);
                            ctx.MarkLabel(ifMatch);
                            if (Helpers.IsValueType(serType))
                            {
                                ctx.DiscardValue();
                                ctx.LoadValue(loc);
                                ctx.CastFromObject(serType);
                            }
                            ser.EmitWrite(ctx, null);
                            ctx.Branch(startFields, false);
                            ctx.MarkLabel(nextTest);
                        }
                    }

                    if (constructType != null && constructType != ExpectedType)
                    {
                        using (Compiler.Local actualType = new Compiler.Local(ctx, typeof(Type)))
                        {
                            // would have jumped to "fields" if an expected sub-type, so two options:
                            // a: *exactly* that type, b: an *unexpected* type
                            ctx.LoadValue(loc);
                            ctx.EmitCall(typeof(object).GetMethod("GetType"));
                            ctx.CopyValue();
                            ctx.StoreValue(actualType);
                            ctx.LoadValue(ExpectedType);
                            ctx.BranchIfEqual(startFields, true);

                            ctx.LoadValue(actualType);
                            ctx.LoadValue(constructType);
                            ctx.BranchIfEqual(startFields, true);
                        }
                    }
                    else
                    {
                        // would have jumped to "fields" if an expected sub-type, so two options:
                        // a: *exactly* that type, b: an *unexpected* type
                        ctx.LoadValue(loc);
                        ctx.EmitCall(typeof(object).GetMethod("GetType"));
                        ctx.LoadValue(ExpectedType);
                        ctx.BranchIfEqual(startFields, true);
                    }
                    // unexpected, then... note that this *might* be a proxy, which
                    // is handled by ThrowUnexpectedSubtype
                    ctx.LoadValue(ExpectedType);
                    ctx.LoadValue(loc);
                    ctx.EmitCall(typeof(object).GetMethod("GetType"));
                    ctx.EmitCall(typeof(TypeModel).GetMethod("ThrowUnexpectedSubtype",
                                                             BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static));
                }
                // fields

                ctx.MarkLabel(startFields);
                for (int i = 0; i < serializers.Length; i++)
                {
                    IProtoSerializer ser = serializers[i];
                    if (ser.ExpectedType == ExpectedType)
                    {
                        ser.EmitWrite(ctx, loc);
                    }
                }

                // extension data
                if (isExtensible)
                {
                    ctx.LoadValue(loc);
                    ctx.LoadWriter(true);
                    ctx.EmitCall(ProtoWriter.GetStaticMethod("AppendExtensionData"));
                }
                // post-callbacks
                EmitCallbackIfNeeded(ctx, loc, TypeModel.CallbackType.AfterSerialize);
            }
        }
示例#53
0
 public void Writer(ProtoWriter writer, object instance)
 {
     writer.Write(((Uri)instance).ToString());
 }
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteUInt64((ulong)value, dest);
 }
示例#55
0
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteSingle((float)value, dest);
 }
示例#56
0
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteByte((byte)value, dest);
 }
示例#57
0
 /// <summary>
 /// Writes a protocol-buffer representation of the given instance to the supplied stream.
 /// </summary>
 /// <param name="key">Represents the type (including inheritance) to consider.</param>
 /// <param name="value">The existing instance to be serialized (cannot be null).</param>
 /// <param name="dest">The destination stream to write to.</param>
 protected internal abstract void Serialize(int key, object value, ProtoWriter dest);
示例#58
0
        static void Main(string[] args)
        {
            Console.WriteLine($"Begin");
            Console.WriteLine();

            byte[]    data;
            ValueDemo model;

            byte[]       data1;
            MemoryStream ms;
            ProtoWriter  writestate;
            var          typeModel = RuntimeTypeModel.Create();

            // Bool
            ms         = new MemoryStream();
            writestate = ProtoBuf.ProtoWriter.Create(ms, typeModel);
            ProtoWriter.WriteFieldHeader(3, WireType.Variant, writestate);
            ProtoWriter.WriteBoolean(true, writestate);
            writestate.Close();
            ms.Position = 0;

            data  = ms.ToArray();
            model = new ValueDemo {
                Success = true
            };
            data1 = ProtoBufSerializer.Serialize(model);
            ms.Close();
            ms = null;

            Print("bool");

            // Int32
            ms         = new MemoryStream();
            writestate = ProtoBuf.ProtoWriter.Create(ms, typeModel);
            ProtoWriter.WriteFieldHeader(5, WireType.Variant, writestate);
            ProtoWriter.WriteInt32(500, writestate);
            writestate.Close();
            ms.Position = 0;

            data  = ms.ToArray();
            model = new ValueDemo {
                Value = 500
            };
            data1 = ProtoBufSerializer.Serialize(model);
            ms.Close();
            ms = null;

            Print("int32");

            // Uint32
            ms         = new MemoryStream();
            writestate = ProtoBuf.ProtoWriter.Create(ms, typeModel);
            ProtoWriter.WriteFieldHeader(4, WireType.Variant, writestate);
            ProtoWriter.WriteUInt32(UInt32.MaxValue, writestate);
            writestate.Close();
            ms.Position = 0;

            data  = ms.ToArray();
            model = new ValueDemo {
                Values = UInt32.MaxValue
            };
            data1 = ProtoBufSerializer.Serialize(model);
            ms.Close();
            ms = null;

            Print("uint32");

            Console.WriteLine();
            Console.WriteLine($"End");

            // Int32


            void Print(string s)
            {
                Console.WriteLine($"{s} - wri: {BitConverter.ToString(data)}");
                Console.WriteLine($"{s} - ser: {BitConverter.ToString(data1)}");
            }
        }
示例#59
0
 public void Write(object value, ProtoWriter dest)
 {
     BclHelpers.WriteDecimal((decimal)value, dest);
 }
示例#60
0
 public void Write(object value, ProtoWriter dest)
 {
     ProtoWriter.WriteString(value.ToString(), dest);
 }