コード例 #1
0
 public ReflectionCollectionSerializer(
     SerializationContext ownerContext,
     IMessagePackSerializer collectionSerializer)
     : base(ownerContext)
 {
     this._collectionSerializer = collectionSerializer;
 }
コード例 #2
0
        // TODO: Hack! How to get a type of the person object? In XmlSerializer it works, not here!

        private void Initialize()
        {
            if (!base.JustInitialized)
            {
                return;
            }
            _serializer     = MessagePackSerializer.Get(_primaryType);
            JustInitialized = false;
        }
コード例 #3
0
        public void TestIMessagePackSerializerPackTo_ObjectTreeIsNull_ValueType_AsNil()
        {
            IMessagePackSerializer target = CreateTarget <int>();

            using (var buffer = new MemoryStream())
                using (var packer = Packer.Create(buffer))
                {
                    Assert.Throws <SerializationException>(() => target.PackTo(packer, null));
                }
        }
コード例 #4
0
        public void TestIMessagePackSerializerPackTo_ObjectTreeIsOtherType()
        {
            IMessagePackSerializer target = CreateTarget <string>();

            using (var buffer = new MemoryStream())
                using (var packer = Packer.Create(buffer))
                {
                    Assert.Throws <ArgumentException>(() => target.PackTo(packer, Int64.MaxValue));
                }
        }
コード例 #5
0
 private object UnpackFromCore(Unpacker unpacker, IMessagePackSerializer underlyingTypeSerializer)
 {
     if (unpacker.LastReadData.IsNil)
     {
         return(Activator.CreateInstance(TargetType));
     }
     else
     {
         return(_nullableTImplicitOperator.Invoke(null, new object[] { underlyingTypeSerializer.UnpackFrom(unpacker) }));
     }
 }
コード例 #6
0
        public void TestIMessagePackSerializerPackTo_Valid_Success()
        {
            IMessagePackSerializer target = CreateTarget <int>();

            using (var buffer = new MemoryStream())
                using (var packer = Packer.Create(buffer))
                {
                    target.PackTo(packer, 1);
                    Assert.That(buffer.ToArray(), Is.EqualTo(new byte[] { 0x1 }));
                }
        }
コード例 #7
0
        public void TestIMessagePackSerializerUnpackTo_CollectionTypeIsInvalid()
        {
            IMessagePackSerializer target = CreateTarget <int[]>();

            using (var buffer = new MemoryStream(new byte[] { 0x91, 0x1 }))
                using (var unpacker = Unpacker.Create(buffer))
                {
                    var collection = new bool[1];
                    Assert.Throws <ArgumentException>(() => target.UnpackTo(unpacker, collection));
                }
        }
コード例 #8
0
        public void TestIMessagePackSerializerUnpackFrom_Invalid()
        {
            IMessagePackSerializer target = CreateTarget <int>();

            using (var buffer = new MemoryStream(new byte[] { 0xC2 }))
                using (var unpacker = Unpacker.Create(buffer))
                {
                    unpacker.Read();
                    Assert.Throws <SerializationException>(() => target.UnpackFrom(unpacker));
                }
        }
コード例 #9
0
        /// <summary>
        /// Create a new <see cref="FluentdSetting"/> instance.
        /// </summary>
        /// <param name="host">The host of fluentd server.</param>
        /// <param name="port">The port of fluentd server.</param>
        /// <param name="serializer">The MessagePack serializer.</param>
        public FluentdSetting(string host, int port, IMessagePackSerializer serializer)
        {
            if (string.IsNullOrEmpty(host))
            {
                throw new ArgumentNullException(nameof(host));
            }

            Host       = host;
            Port       = port;
            Serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
        }
コード例 #10
0
        public void TestIMessagePackSerializerPackTo_ObjectTreeIsNull_ReferenceType_AsNil()
        {
            IMessagePackSerializer target = CreateTarget <string>();

            using (var buffer = new MemoryStream())
                using (var packer = Packer.Create(buffer))
                {
                    target.PackTo(packer, null);
                    Assert.That(buffer.ToArray(), Is.EqualTo(new byte[] { 0xC0 }));
                }
        }
コード例 #11
0
        public void TestIMessagePackSerializerUnpackTo_CollectionIsNull()
        {
            IMessagePackSerializer target = CreateTarget <int[]>();

            using (var buffer = new MemoryStream(new byte[] { 0x91, 0x1 }))
                using (var unpacker = Unpacker.Create(buffer))
                {
                    unpacker.Read();
                    Assert.Throws <ArgumentNullException>(() => target.UnpackTo(unpacker, null));
                }
        }
コード例 #12
0
        public void TestIMessagePackSerializerUnpackFrom_Valid_Success()
        {
            IMessagePackSerializer target = CreateTarget <int>();

            using (var buffer = new MemoryStream(new byte[] { 0x1 }))
                using (var unpacker = Unpacker.Create(buffer))
                {
                    unpacker.Read();
                    var result = target.UnpackFrom(unpacker);
                    Assert.That(result, Is.EqualTo(1));
                }
        }
コード例 #13
0
        private void PackToCore(Packer packer, object target, IMessagePackSerializer underlyingTypeSerializer)
        {
            {
                if (!(bool)_nullableTValueProperty.GetGetMethod().Invoke(target, new object[0]))
                {
                    packer.PackNull();
                    return;
                }

                underlyingTypeSerializer.PackTo(packer, _nullableTValueProperty.GetGetMethod().Invoke(target, new object[0]));
            };
        }
コード例 #14
0
        public void TestIMessagePackSerializerUnpackTo_StreamContainsNull()
        {
            IMessagePackSerializer target = CreateTarget <int[]>();

            using (var buffer = new MemoryStream(new byte[] { 0xC0 }))
                using (var unpacker = Unpacker.Create(buffer))
                {
                    unpacker.Read();
                    var collection = new int[0];
                    target.UnpackTo(unpacker, collection);
                }
        }
コード例 #15
0
        public void TestIMessagePackSerializerUnpackTo_StreamContentIsInvalid()
        {
            IMessagePackSerializer target = CreateTarget <int[]>();

            using (var buffer = new MemoryStream(new byte[] { 0x1 }))
                using (var unpacker = Unpacker.Create(buffer))
                {
                    unpacker.Read();
                    var collection = new int[1];
                    Assert.Throws <SerializationException>(() => target.UnpackTo(unpacker, collection));
                }
        }
コード例 #16
0
 // ReSharper disable once MemberCanBePrivate.Global
 public FileStreamer(IMessagePackSerializer messagePackSerializer, IFile file,
                     ISemaphoreFactory semaphoreFactory, IDirectory directory, ILogger logger)
 {
     using (logger.BeginScope("{Operation}", nameof(FileStreamer)))
     {
         _messagePackSerializer = messagePackSerializer;
         _file             = file;
         _semaphoreFactory = semaphoreFactory;
         _directory        = directory;
         _logger           = logger;
         _logger.LogInformation("Created file streamer");
     }
 }
コード例 #17
0
        public static object BytesToObj(Type type, byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                return(null);
            }

            IMessagePackSerializer ser    = serDic.GetOrAdd(type, MessagePackSerializer.Create(type));
            MemoryStream           stream = new MemoryStream(data);
            Unpacker up = Unpacker.Create(stream);

            up.Read();
            return(ser.UnpackFrom(up));
        }
コード例 #18
0
        public void TestIMessagePackSerializerUnpackTo_Valid_Success()
        {
            IMessagePackSerializer target = CreateTarget <int[]>();

            using (var buffer = new MemoryStream(new byte[] { 0x91, 0x1 }))
                using (var unpacker = Unpacker.Create(buffer))
                {
                    unpacker.Read();
                    var collection = new int[2];
                    target.UnpackTo(unpacker, collection);
                    // colection[1] is still 0.
                    Assert.That(collection, Is.EqualTo(new[] { 1, 0 }));
                }
        }
コード例 #19
0
        public static byte[] ObjToBytes(object obj)
        {
            if (obj == null)
            {
                return(null);
            }

            Type type = obj.GetType();
            IMessagePackSerializer ser    = serDic.GetOrAdd(type, MessagePackSerializer.Create(type));
            MemoryStream           stream = new MemoryStream();

            ser.PackTo(Packer.Create(stream), obj);
            byte[] data = stream.ToArray();
            return(data);
        }
コード例 #20
0
        /// <summary>
        ///		Sets the serializer instance which can handle <see cref="TargetType" /> type instance correctly.
        /// </summary>
        /// <param name="foundSerializer">The serializer instance which can handle <see cref="TargetType" /> type instance correctly; <c>null</c> when you cannot provide appropriate serializer instance.</param>
        /// <remarks>
        ///		If you decide to delegate serializer generation to MessagePack for CLI infrastructure, do not call this method in your event handler or specify <c>null</c> for <paramref name="foundSerializer"/>.
        /// </remarks>
        public void SetSerializer <T>(MessagePackSerializer <T> foundSerializer)
        {
            if (typeof(T) != this.TargetType)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture,
                              "The serializer must be {0} type.",
                              typeof(MessagePackSerializer <>).MakeGenericType(this.TargetType)
                              )
                          );
            }

            this._foundSerializer = foundSerializer;
        }
コード例 #21
0
        public static void Pack(this IMessagePackSerializer source, Stream stream, object objectTree, PackerCompatibilityOptions packerCompatibilityOptions)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

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

            // Packer does not have finalizer, so just avoiding packer disposing prevents stream closing.
            source.PackTo(Packer.Create(stream, packerCompatibilityOptions), objectTree);
        }
コード例 #22
0
 public NonGenericDictionarySerializer(SerializationContext ownerContext, Type targetType)
     : base(ownerContext)
 {
     if (ownerContext.EmitterFlavor == EmitterFlavor.ReflectionBased)
     {
         this._collectionConstructorWithCapacity =
             targetType.GetConstructor(UnpackHelpers.CollectionConstructorWithCapacityParameterTypes);
         if (this._collectionConstructorWithCapacity == null)
         {
             this._collectionConstructorWithoutCapacity = targetType.GetConstructor(ReflectionAbstractions.EmptyTypes);
             if (this._collectionConstructorWithoutCapacity == null)
             {
                 throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity(targetType);
             }
         }
     }
     else
     {
         this._collectionDeserializer = ownerContext.GetSerializer(targetType);
     }
 }
コード例 #23
0
        /// <summary>
        ///		Deserialize object from the <see cref="Stream"/>.
        /// </summary>
        /// <param name="source"><see cref="IMessagePackSerializer"/> object.</param>
        /// <param name="stream">Source <see cref="Stream"/>.</param>
        /// <returns>Deserialized object.</returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="source"/> is <c>null</c>.
        ///		Or <paramref name="stream"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.Runtime.Serialization.SerializationException">
        ///		Failed to deserialize from <paramref name="stream"/>.
        /// </exception>
        public static object Unpack(this IMessagePackSerializer source, Stream stream)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

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

            // Unpacker does not have finalizer, so just avoiding unpacker disposing prevents stream closing.
            var unpacker = Unpacker.Create(stream);

            if (!unpacker.Read())
            {
                throw SerializationExceptions.NewUnexpectedEndOfStream();
            }

            return(source.UnpackFrom(unpacker));
        }
コード例 #24
0
        protected EnumerableSerializerBase(SerializationContext ownerContext, Type targetType)
            : base(ownerContext)
        {
            this._itemSerializer = ownerContext.GetSerializer <TItem>();
            if (ownerContext.EmitterFlavor == EmitterFlavor.ReflectionBased)
            {
                // First use abstract type instead of surrogate concrete type.
                var traits = typeof(T).GetCollectionTraits();
                if (traits.AddMethod != null)
                {
                    this._addItem = traits.AddMethod;
                }
                else
                {
                    // Try use concrete type method... it might fail.
                    traits = targetType.GetCollectionTraits();
                    if (traits.AddMethod != null)
                    {
                        this._addItem = traits.AddMethod;
                    }
                }

                this._collectionConstructorWithCapacity =
                    targetType.GetConstructor(UnpackHelpers.CollectionConstructorWithCapacityParameterTypes);
                if (this._collectionConstructorWithCapacity == null)
                {
                    this._collectionConstructorWithoutCapacity = targetType.GetConstructor(ReflectionAbstractions.EmptyTypes);
                    if (this._collectionConstructorWithoutCapacity == null)
                    {
                        throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity(targetType);
                    }
                }
            }
            else
            {
                this._collectionDeserializer = ownerContext.GetSerializer(targetType);
            }
        }
コード例 #25
0
        internal NullableMessagePackSerializer(Type type, SerializationContext context, EmitterFlavor emitterFlavor)
            : base(type, (context ?? SerializationContext.Default).CompatibilityOptions.PackerCompatibilityOptions)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            Contract.EndContractBlock();

            if (!IsNullable(type))
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "'{0}' is not nullable type.", type));
            }

            var underlyingType = Nullable.GetUnderlyingType(type);

            this._nullableTHasValueProperty = type.GetProperty("HasValue");
            this._nullableTValueProperty    = type.GetProperty("Value");
            this._nullableTImplicitOperator = type.GetMethod("op_Implicit", new Type[] { type });


            this._underlyingTypeSerializer = context.GetSerializer(underlyingType);
        }
コード例 #26
0
 public override void BeforeRuns(Test test)
 {
     m_Serializer = MessagePackSerializer.Get(test.GetPayloadRootType());
 }
コード例 #27
0
 /// <summary>
 /// Create a new <see cref="FluentdClient"/> instance.
 /// </summary>
 /// <param name="host">The host of fluentd server.</param>
 /// <param name="port">The port of fluentd server.</param>
 /// <param name="serializer">The MessagePack serializer.</param>
 public FluentdClient(string host, int port, IMessagePackSerializer serializer)
     : this(new FluentdSetting(host, port, serializer))
 {
 }
コード例 #28
0
        public static void GetMetadata(
            IList <SerializingMember> members,
            SerializationContext context,
            out Func <object, object>[] getters,
            out Action <object, object>[] setters,
            out MemberInfo[] memberInfos,
            out DataMemberContract[] contracts,
            out IMessagePackSerializer[] serializers)
        {
            getters     = new Func <object, object> [members.Count];
            setters     = new Action <object, object> [members.Count];
            memberInfos = new MemberInfo[members.Count];
            contracts   = new DataMemberContract[members.Count];
            serializers = new IMessagePackSerializer[members.Count];

            for (var i = 0; i < members.Count; i++)
            {
                var member = members[i];
                if (member.Member == null)
                {
#if UNITY
                    contracts[i] = DataMemberContract.Null;
#endif // UNITY
                    continue;
                }

                FieldInfo asField;
                if ((asField = member.Member as FieldInfo) != null)
                {
                    getters[i] = asField.GetValue;
                    setters[i] = asField.SetValue;
                }
                else
                {
                    var property = member.Member as PropertyInfo;
#if DEBUG && !UNITY
                    Contract.Assert(property != null, "member.Member is PropertyInfo");
#endif // DEBUG && !UNITY
                    getters[i] = target => property.GetGetMethod(true).InvokePreservingExceptionType(target, null);
                    var setter = property.GetSetMethod(true);
                    if (setter != null)
                    {
                        setters[i] = (target, value) => setter.InvokePreservingExceptionType(target, new[] { value });
                    }
                }

                memberInfos[i] = member.Member;
#if !UNITY
                contracts[i] = member.Contract;
#else
                contracts[i] = member.Contract ?? DataMemberContract.Null;
#endif // !UNITY
                var memberType = member.Member.GetMemberValueType();
                if (memberType.GetIsEnum())
                {
                    serializers[i] =
                        context.GetSerializer(
                            memberType,
                            EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod(
                                context,
                                memberType,
                                member.GetEnumMemberSerializationMethod()
                                )
                            );
                }
                else if (DateTimeMessagePackSerializerHelpers.IsDateTime(memberType))
                {
                    serializers[i] =
                        context.GetSerializer(
                            memberType,
                            DateTimeMessagePackSerializerHelpers.DetermineDateTimeConversionMethod(
                                context,
                                member.GetDateTimeMemberConversionMethod()
                                )
                            );
                }
                else
                {
                    serializers[i] = context.GetSerializer(memberType, PolymorphismSchema.Create(context, memberType, member));
                }
            }
        }
コード例 #29
0
        public MapReflectionMessagePackSerializer(Type type, SerializationContext context, CollectionTraits traits)
            : base(type, (context ?? SerializationContext.Default).CompatibilityOptions.PackerCompatibilityOptions)
        {
            Contract.Assert(typeof(IEnumerable).IsAssignableFrom(type), type + " is IEnumerable");
            Contract.Assert(traits.ElementType == typeof(DictionaryEntry) || (traits.ElementType.GetIsGenericType() && traits.ElementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)), "Element type " + traits.ElementType + " is not KeyValuePair<TKey,TValue>.");
            this._traits = traits;
            this._keySerializer = traits.ElementType.GetIsGenericType() ? context.GetSerializer(traits.ElementType.GetGenericArguments()[0]) : context.GetSerializer(typeof(MessagePackObject));
            this._valueSerializer = traits.ElementType.GetIsGenericType() ? context.GetSerializer(traits.ElementType.GetGenericArguments()[1]) : context.GetSerializer(typeof(MessagePackObject));
            this._getCount = ReflectionSerializerLogics.CreateGetCount(type, traits);

            var constructor = ReflectionSerializerLogics.GetCollectionConstructor(context, type);

            if (constructor == null)
            {
                this._createInstance = () => { throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity(type); };
                this._createInstanceWithCapacity = null;
            }
            else if (constructor.GetParameters().Length == 1)
            {
                this._createInstance = null;

                this._createInstanceWithCapacity = length => constructor.Invoke(new object[] { length });
            }
            else
            {
                this._createInstanceWithCapacity = null;
                this._createInstance = () => constructor.Invoke(new object[0]);
            }

            var keyType = traits.ElementType.GetIsGenericType() ? traits.ElementType.GetGenericArguments()[0] : typeof(MessagePackObject);
            var valueType = traits.ElementType.GetIsGenericType() ? traits.ElementType.GetGenericArguments()[1] : typeof(MessagePackObject);
            var keyProperty = traits.ElementType.GetProperty("Key");
            var valueProperty = traits.ElementType.GetProperty("Value");

            this._packToCore = (Packer packer, object objectTree, IMessagePackSerializer keySerializer, IMessagePackSerializer valueSerializer) =>
                {
                    packer.PackMapHeader(this._getCount(objectTree));
                    foreach (var kvp in (IEnumerable)objectTree)
                    {
                        keySerializer.PackTo(packer, keyProperty.GetValue(kvp, new object[0]));
                        valueSerializer.PackTo(packer, valueProperty.GetValue(kvp, new object[0]));
                    }
                };

            if (traits.ElementType.GetIsGenericType())
            {
                /*
                 * UnpackHelpers.UnpackMapTo<TKey,TValue>( unpacker, keySerializer, valueSerializer, instance );
                 */
                var unpackMapToMethod =   Metadata._UnpackHelpers.UnpackMapTo_2; //.MakeGenericMethod(keyType, valueType);
                this._unpackToCore = (Unpacker unpacker, object objectTree, IMessagePackSerializer keySerializer, IMessagePackSerializer valueSerializer) =>
                    {
                        
                        unpackMapToMethod.Invoke(null, new object[] { unpacker, keySerializer, valueSerializer, objectTree });
                    };
            }
            else
            {
                /*
                 * UnpackHelpers.UnpackNonGenericMapTo( unpacker, instance );
                 */
                this._unpackToCore = (Unpacker unpacker, object objectTree, IMessagePackSerializer keySerializer, IMessagePackSerializer valueSerializer) => UnpackHelpers.UnpackMapTo(unpacker, (IDictionary)objectTree);
            }
        }
コード例 #30
0
        protected SequenceReflectionMessagePackSerializer(Type type, SerializationContext context, CollectionTraits traits)
            : base(type, (context ?? SerializationContext.Default).CompatibilityOptions.PackerCompatibilityOptions)
        {
            Contract.Assert(type.IsArray || typeof(IEnumerable).IsAssignableFrom(type), type + " is not array nor IEnumerable");
            this._traits            = traits;
            this._elementSerializer = context.GetSerializer(traits.ElementType);
            this._getCount          = ReflectionSerializerLogics.CreateGetCount(type, traits);

            //var packerParameter = Expression.Parameter(typeof(Packer), "packer");
            //var objectTreeParameter = Expression.Parameter(typeof(T), "objectTree");
            //var elementSerializerParameter = Expression.Parameter(typeof(IMessagePackSerializer), "elementSerializer");

            this._packToCore = (Packer packer, object objectTree, IMessagePackSerializer elementSerializer) =>
            {
                var length = this._getCount(objectTree);
                packer.PackArrayHeader(length);
                foreach (var item in (IEnumerable)objectTree)
                {
                    elementSerializer.PackTo(packer, item);
                }
            };


            /*
             *	for ( int i = 0; i < count; i++ )
             *	{
             *		if ( !unpacker.Read() )
             *		{
             *			throw SerializationExceptions.NewMissingItem( i );
             *		}
             *
             *		T item;
             *		if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
             *		{
             *			item = this.ElementSerializer.UnpackFrom( unpacker );
             *		}
             *		else
             *		{
             *			using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
             *			{
             *				item = this.ElementSerializer.UnpackFrom( subtreeUnpacker );
             *			}
             *		}
             *
             *		instance[ i ] = item; -- OR -- instance.Add( item );
             *	}
             */

            // FIXME: use UnpackHelper

            if (type.IsArray)
            {
                var arrayUnpackerMethod = _UnpackHelpers.UnpackArrayTo_1.MakeGenericMethod(traits.ElementType);
                this._unpackToCore = (Unpacker unpacker, object instance, IMessagePackSerializer elementSerializer) =>
                {
                    arrayUnpackerMethod.Invoke(null, new object[] { unpacker, elementSerializer, instance });
                };
            }
            else
            {
                this._unpackToCore = (Unpacker unpacker, object instance, IMessagePackSerializer elementSerializer) =>
                {
                    var count = UnpackHelpers.GetItemsCount(unpacker);
                    for (int i = 0; i < count; i++)
                    {
                        if (!unpacker.Read())
                        {
                            throw SerializationExceptions.NewMissingItem(i);
                        }
                        object item;
                        if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
                        {
                            item = elementSerializer.UnpackFrom(unpacker);
                        }
                        else
                        {
                            using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
                            {
                                item = elementSerializer.UnpackFrom(subtreeUnpacker);
                            }
                        }
                        traits.AddMethod.Invoke(instance, new object[] { item });
                    }
                };
            }
        }
コード例 #31
0
        public void TestIMessagePackSerializerPackTo_PackerIsNull()
        {
            IMessagePackSerializer target = CreateTarget <int>();

            Assert.Throws <ArgumentNullException>(() => target.PackTo(null, 0));
        }
コード例 #32
0
        // TODO: Hack! How to get a type of the person object? In XmlSerializer it works, not here!

        private void Initialize()
        {
            if (!base.JustInitialized) return;
            _serializer = MessagePackSerializer.Get(_primaryType);
            JustInitialized = false;
        }
コード例 #33
0
        protected SequenceReflectionMessagePackSerializer(Type type, SerializationContext context, CollectionTraits traits)
            : base(type, (context ?? SerializationContext.Default).CompatibilityOptions.PackerCompatibilityOptions)
        {
            Contract.Assert(type.IsArray || typeof(IEnumerable).IsAssignableFrom(type), type + " is not array nor IEnumerable");
            this._traits = traits;
            this._elementSerializer = context.GetSerializer(traits.ElementType);
            this._getCount = ReflectionSerializerLogics.CreateGetCount(type, traits);

            //var packerParameter = Expression.Parameter(typeof(Packer), "packer");
            //var objectTreeParameter = Expression.Parameter(typeof(T), "objectTree");
            //var elementSerializerParameter = Expression.Parameter(typeof(IMessagePackSerializer), "elementSerializer");

            this._packToCore = (Packer packer, object objectTree, IMessagePackSerializer elementSerializer) =>
                {
                    var length = this._getCount(objectTree);
                    packer.PackArrayHeader(length);
                    foreach (var item in (IEnumerable)objectTree)
                    {
                        elementSerializer.PackTo(packer, item);
                    }
                };


            /*
             *	for ( int i = 0; i < count; i++ )
             *	{
             *		if ( !unpacker.Read() )
             *		{
             *			throw SerializationExceptions.NewMissingItem( i );
             *		}
             *	
             *		T item;
             *		if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
             *		{
             *			item = this.ElementSerializer.UnpackFrom( unpacker );
             *		}
             *		else
             *		{
             *			using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
             *			{
             *				item = this.ElementSerializer.UnpackFrom( subtreeUnpacker );
             *			}
             *		}
             *
             *		instance[ i ] = item; -- OR -- instance.Add( item );
             *	}
             */

            // FIXME: use UnpackHelper

            if (type.IsArray)
            {
                var arrayUnpackerMethod = _UnpackHelpers.UnpackArrayTo_1.MakeGenericMethod(traits.ElementType);
                this._unpackToCore = (Unpacker unpacker, object instance, IMessagePackSerializer elementSerializer) =>
                {
                    arrayUnpackerMethod.Invoke(null, new object[] { unpacker, elementSerializer, instance });
                };
            }
            else
            {
                this._unpackToCore = (Unpacker unpacker, object instance, IMessagePackSerializer elementSerializer) =>
                {
                    var count = UnpackHelpers.GetItemsCount(unpacker);
                    for (int i = 0; i < count; i++)
                    {
                        if (!unpacker.Read())
                        {
                            throw SerializationExceptions.NewMissingItem(i);
                        }
                        object item;
                        if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
                        {
                            item = elementSerializer.UnpackFrom(unpacker);
                        }
                        else
                        {
                            using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
                            {
                                item = elementSerializer.UnpackFrom(subtreeUnpacker);
                            }
                        }
                        traits.AddMethod.Invoke(instance, new object[] { item });
                    }
                };
            }
        }
コード例 #34
0
 public override void BeforeRuns(Test test)
 {
     m_Serializer = MessagePackSerializer.Get(test.GetPayloadRootType());
 }