public static void GetConcreteSerializer(
			SerializationContext context,
			PolymorphismSchema schema,
			Type abstractType,
			Type targetType,
			Type exampleType,
			out ICollectionInstanceFactory factory,
			out MessagePackSerializer serializer
		)
		{
			if ( abstractType == targetType )
			{
				throw SerializationExceptions.NewNotSupportedBecauseCannotInstanciateAbstractType( abstractType );
			}

			serializer = context.GetSerializer( targetType, schema );
			factory = serializer as ICollectionInstanceFactory;
			if ( factory == null && (serializer as IPolymorphicDeserializer) == null )
			{
				throw SerializationExceptions.NewIncompatibleCollectionSerializer( abstractType, serializer.GetType(), exampleType );
			}
		}
Beispiel #2
0
        protected override ILConstruct EmitGetSerializerExpression(AssemblyBuilderEmittingContext context, Type targetType, SerializingMember?memberInfo, PolymorphismSchema itemsSchema)
        {
            var realSchema   = itemsSchema ?? PolymorphismSchema.Create(context.SerializationContext, targetType, memberInfo);
            var instructions =
                context.Emitter.RegisterSerializer(
                    targetType,
                    memberInfo == null
                                                ? EnumMemberSerializationMethod.Default
                                                : memberInfo.Value.GetEnumMemberSerializationMethod(),
                    memberInfo == null
                                                ? DateTimeMemberConversionMethod.Default
                                                : memberInfo.Value.GetDateTimeMemberConversionMethod(),
                    realSchema,
                    () => this.EmitConstructPolymorphismSchema(context, realSchema)
                    );

            return
                (ILConstruct.Instruction(
                     "getserializer",
                     typeof(MessagePackSerializer <>).MakeGenericType(targetType),
                     false,
                     // Both of this pointer for FieldBasedSerializerEmitter and context argument of methods for ContextBasedSerializerEmitter are 0.
                     il => instructions(il, 0)
                     ));
        }
        public static void GetMetadata(
            Type targetType,
            IList <SerializingMember> members,
            SerializationContext context,
            out Func <object, object>[] getters,
            out Action <object, object>[] setters,
            out MemberInfo[] memberInfos,
            out DataMemberContract[] contracts,
            out MessagePackSerializer[] 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 MessagePackSerializer[members.Count];

            for (var i = 0; i < members.Count; i++)
            {
                var member = members[i];

                if (member.Member == null)
                {
                    // Missing member exist because of unconbinous Id of MessagePackMember or Order of DataMember.
#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
                    Contract.Assert(property != null, "member.Member is PropertyInfo");
#endif // DEBUG
                    var getter = property.GetGetMethod(true);
                    if (getter == null)
                    {
                        ThrowMissingGetterException(targetType, i, property);
                    }

                    getters[i] = target => getter.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(memberType, member));
                }
            }
        }
Beispiel #4
0
 public static MessagePackSerializer <T> Create <T>(SerializationContext context, PolymorphismSchema itemsSchema)
 {
     return(Create(context, typeof(T), itemsSchema) as MessagePackSerializer <T>);
 }
Beispiel #5
0
 /// <summary>
 ///		Initializes a new instance of the <see cref="EnumerableMessagePackSerializer{TCollection, TItem}"/> class.
 /// </summary>
 /// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
 /// <param name="schema">
 ///		The schema for collection itself or its items for the member this instance will be used to.
 ///		<c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
 /// </param>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="ownerContext"/> is <c>null</c>.
 /// </exception>
 protected EnumerableMessagePackSerializer(SerializationContext ownerContext, PolymorphismSchema schema)
     : base(ownerContext, schema)
 {
 }
Beispiel #6
0
        public string GetSerializerFieldName(Type targetType, EnumMemberSerializationMethod enumSerializationMethod, DateTimeMemberConversionMethod dateTimeConversionMethod, PolymorphismSchema polymorphismSchema)
        {
            var key = new SerializerFieldKey(targetType, enumSerializationMethod, dateTimeConversionMethod, polymorphismSchema);

            string fieldName;

            if (!this._dependentSerializers.TryGetValue(key, out fieldName))
            {
                fieldName = "_serializer" + this._dependentSerializers.Count.ToString(CultureInfo.InvariantCulture);
                this._dependentSerializers.Add(key, fieldName);
            }

            return(fieldName);
        }
Beispiel #7
0
 protected NonGenericEnumerableMessagePackSerializerBase(SerializationContext ownerContext, PolymorphismSchema schema)
     : base(ownerContext)
 {
     this._itemSerializer = ownerContext.GetSerializer(typeof(object), (schema ?? PolymorphismSchema.Default).ItemSchema);
 }
Beispiel #8
0
        private TConstruct EmitUnpackToCollectionLoopBody(TContext context, ForLoopContext forLoopContext, CollectionTraits traitsOfTheCollection, TConstruct unpacker, TConstruct collection, PolymorphismSchema itemsSchema)
        {
            /*
             *  if ( !unpacker.Read() )
             *      {
             *              throw SerializationExceptions.NewMissingItem( i );
             *      }
             *
             *      T item;
             *      if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
             *      {
             *              item = serializer.UnpackFrom( unpacker );
             *      }
             *      else
             *      {
             *              using ( Unpacker subtreeUnpacker = unpacker.ReadSubtree() )
             *              {
             *                      item = serializer.UnpackFrom( subtreeUnpacker );
             *              }
             *      }
             *
             *      addition( item );
             */

            return
                (this.EmitUnpackItemValueExpression(
                     context,
                     traitsOfTheCollection.ElementType,
                     context.CollectionItemNilImplication,
                     unpacker,
                     forLoopContext.Counter,
                     this.EmitInvariantStringFormat(context, "item{0}", forLoopContext.Counter),
                     null,
                     null,
                     null,
                     itemsSchema,
                     unpackedItem =>
                     this.EmitAppendCollectionItem(
                         context,
                         null,
                         traitsOfTheCollection,
                         collection,
                         unpackedItem
                         )
                     ));
        }
Beispiel #9
0
        protected DictionaryMessagePackSerializerBase(SerializationContext ownerContext, PolymorphismSchema schema)
            : base(ownerContext)
        {
            var safeSchema = schema ?? PolymorphismSchema.Default;

            this._keySerializer   = ownerContext.GetSerializer <TKey>(safeSchema.KeySchema);
            this._valueSerializer = ownerContext.GetSerializer <TValue>(safeSchema.ItemSchema);
        }
Beispiel #10
0
        private void BuildCollectionUnpackFromCore(TContext context, Type concreteType, PolymorphismSchema schema)
        {
            this.EmitMethodPrologue(context, SerializerMethod.UnpackFromCore);

            TConstruct construct = null;

            try
            {
                var instanceType = concreteType ?? typeof(TObject);
                var collection   =
                    this.DeclareLocal(
                        context,
                        instanceType,
                        "collection"
                        );
                construct =
                    this.EmitSequentialStatements(
                        context,
                        collection.ContextType,
                        this.EmitCollectionUnpackFromStatements(context, instanceType, schema, collection)
                        );
            }
            finally
            {
                this.EmitMethodEpilogue(context, SerializerMethod.UnpackFromCore, construct);
            }
        }
Beispiel #11
0
        private IEnumerable <TConstruct> EmitCollectionUnpackFromStatements(TContext context, Type instanceType, PolymorphismSchema schema, TConstruct collection)
        {
            /*
             * #if ARRAY
             *	if (!unpacker.IsArrayHeader)
             * #else
             *	if (!unpacker.IsMapHeader)
             * #endif
             *	{
             *		throw SerializationExceptions.NewIsNotArrayHeader();
             *	}
             *	int capacity = ITEMS_COUNT(unpacker);
             *	TCollection collection = new ...;
             * #if HAS_ADD_IN_TYPE
             *	this.UnpackToCore(unpacker, array);
             * #else // Add only exists in concrete type
             *  UNPACK_TO_SPECIFIED_COLLECTION
             * #endif
             *	return collection;
             */
            var ctor = UnpackHelpers.GetCollectionConstructor(instanceType);

            yield return
                (CollectionTraitsOfThis.CollectionType == CollectionKind.Array
                                        ? this.EmitCheckIsArrayHeaderExpression(context, context.Unpacker)
                                        : this.EmitCheckIsMapHeaderExpression(context, context.Unpacker));

            var itemsCount = this.DeclareLocal(context, typeof(int), "itemsCount");

            yield return(itemsCount);

            yield return
                (this.EmitStoreVariableStatement(
                     context,
                     itemsCount,
                     this.EmitGetItemsCountExpression(context, context.Unpacker)
                     ));

            yield return(collection);

            if (CollectionTraitsOfThis.CollectionType == CollectionKind.Array && CollectionTraitsOfThis.AddMethod == null)
            {
                // deserialize with concrete collection's UnpackTo.
                yield return
                    (this.EmitStoreVariableStatement(
                         context,
                         collection,
                         this.EmitCreateNewObjectExpression(
                             context,
                             collection,
                             ctor,
                             ctor.GetParameters().Length == 0
                                                                ? NoConstructs
                                                                : new[] { itemsCount }
                             )
                         ));

                yield return
                    (this.EmitForLoop(
                         context,
                         itemsCount,
                         flc =>
                         this.EmitUnpackToCollectionLoopBody(
                             context,
                             flc,
                             instanceType.GetCollectionTraits(),
                             context.Unpacker,
                             collection,
                             (schema ?? PolymorphismSchema.Default).ItemSchema
                             )
                         ));
            }
            else
            {
                // use generated AddItem override.
                yield return
                    (this.EmitUnpackCollectionWithUnpackToExpression(
                         context,
                         ctor,
                         itemsCount,
                         context.Unpacker,
                         collection
                         ));
            }

            yield return
                (this.EmitRetrunStatement(
                     context,
                     this.EmitLoadVariableExpression(context, collection)
                     ));
        }
Beispiel #12
0
 /// <summary>
 ///		Initializes a new instance of the <see cref="DictionaryMessagePackSerializer{TDictionary, TKey, TValue}"/> class.
 /// </summary>
 /// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
 /// <param name="schema">
 ///		The schema for collection itself or its items for the member this instance will be used to.
 ///		<c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
 /// </param>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="ownerContext"/> is <c>null</c>.
 /// </exception>
 protected DictionaryMessagePackSerializer(SerializationContext ownerContext, PolymorphismSchema schema)
     : base(ownerContext, schema)
 {
 }
Beispiel #13
0
 public ComparablePolymorphismSchema(PolymorphismSchema value)
 {
     this._value = value;
     this._key   = new MessagePackString(Pack(value), true);
 }
Beispiel #14
0
 public SerializerFieldKey(Type targetType, EnumMemberSerializationMethod enumMemberSerializationMethod, DateTimeMemberConversionMethod dateTimeConversionMethod, PolymorphismSchema polymorphismSchema)
 {
     this.TypeHandle = targetType.TypeHandle;
     this.EnumSerializationMethod  = enumMemberSerializationMethod;
     this.DateTimeConversionMethod = dateTimeConversionMethod;
     this._schema = new ComparablePolymorphismSchema(polymorphismSchema);
 }
			public static TypeTableEntry Create( MemberInfo member, PolymorphismTarget targetType, PolymorphismSchema defaultSchema )
			{
				var result = new TypeTableEntry();
				var memberName = member.ToString();
				foreach (
					var attribute in
						member.GetCustomAttributes( false )
							.OfType<IPolymorphicHelperAttribute>()
							.Where( a => a.Target == targetType )
				)
				{
					// TupleItem schema should never come here, so passing -1 as tupleItemNumber is OK.
					result.Interpret( attribute, memberName, -1 );
				}

				if ( defaultSchema != null )
				{
					// TupleItem schema should never come here, so passing -1 as tupleItemNumber is OK.
					result.SetDefault( targetType, memberName, -1, defaultSchema );
				}

				return result;
			}
Beispiel #16
0
        public static void GetMetadata(
            Type targetType,
            IList <SerializingMember> members,
            SerializationContext context,
            out Func <object, object>[] getters,
            out Action <object, object>[] setters,
            out MemberInfo[] memberInfos,
            out DataMemberContract[] contracts,
            out MessagePackSerializer[] serializers
            )
        {
            SerializationTarget.VerifyCanSerializeTargetType(context, targetType);

            if (members.Count == 0)
            {
                if (!typeof(IPackable).IsAssignableFrom(targetType))
                {
                    throw new SerializationException(
                              String.Format(
                                  CultureInfo.CurrentCulture,
                                  "At least one serializable member is required because type '{0}' does not implement IPackable interface.",
                                  targetType
                                  )
                              );
                }

                if (!typeof(IUnpackable).IsAssignableFrom(targetType))
                {
                    throw new SerializationException(
                              String.Format(
                                  CultureInfo.CurrentCulture,
                                  "At least one serializable member is required because type '{0}' does not implement IUnpackable interface.",
                                  targetType
                                  )
                              );
                }

#if FEATURE_TAP
                if (context.SerializerOptions.WithAsync)
                {
                    if (!typeof(IAsyncPackable).IsAssignableFrom(targetType))
                    {
                        throw new SerializationException(
                                  String.Format(
                                      CultureInfo.CurrentCulture,
                                      "At least one serializable member is required because type '{0}' does not implement IAsyncPackable interface.",
                                      targetType
                                      )
                                  );
                    }

                    if (!typeof(IAsyncUnpackable).IsAssignableFrom(targetType))
                    {
                        throw new SerializationException(
                                  String.Format(
                                      CultureInfo.CurrentCulture,
                                      "At least one serializable member is required because type '{0}' does not implement IAsyncUnpackable interface.",
                                      targetType
                                      )
                                  );
                    }
                }
#endif // FEATURE_TAP
            }

            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 MessagePackSerializer[members.Count];

            for (var i = 0; i < members.Count; i++)
            {
                var member = members[i];

                if (member.Member == null)
                {
                    // Missing member exist because of unconbinous Id of MessagePackMember or Order of DataMember.
#if UNITY
                    contracts[i] = DataMemberContract.Null;
#endif // UNITY
                    continue;
                }

                FieldInfo asField;
                if ((asField = member.Member as FieldInfo) != null)
                {
                    if (context.SerializerOptions.DisablePrivilegedAccess && !asField.GetIsPublic())
                    {
                        continue;
                    }

                    getters[i] = asField.GetValue;
                    if (!asField.IsInitOnly)
                    {
                        setters[i] = asField.SetValue;
                    }
                }
                else
                {
                    var property = member.Member as PropertyInfo;
#if DEBUG
                    Contract.Assert(property != null, "member.Member is PropertyInfo");
#endif // DEBUG
                    if (context.SerializerOptions.DisablePrivilegedAccess && !property.GetIsPublic())
                    {
                        continue;
                    }

                    var getter = property.GetGetMethod(true);
                    if (getter == null)
                    {
                        ThrowMissingGetterException(targetType, i, property);
                    }

                    getters[i] = target => getter.InvokePreservingExceptionType(target, null);
                    var setter = property.GetSetMethod(true);
                    if (setter != null && (!context.SerializerOptions.DisablePrivilegedAccess || setter.GetIsPublic()))
                    {
                        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(memberType, member));
                }
            }
        }
 /// <summary>
 ///		Initializes a new instance of the <see cref="CollectionMessagePackSerializerBase{TCollection, TItem}"/> class.
 /// </summary>
 /// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
 /// <param name="schema">
 ///		The schema for collection itself or its items for the member this instance will be used to.
 ///		<c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
 /// </param>
 /// <param name="capabilities">A serializer calability flags represents capabilities of this instance.</param>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="ownerContext"/> is <c>null</c>.
 /// </exception>
 protected CollectionMessagePackSerializerBase(SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities)
     : base(ownerContext, schema, capabilities)
 {
 }
Beispiel #18
0
            public MessagePackSerializer Create(SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo)
            {
                var itemSchema = schema ?? PolymorphismSchema.Default;

                return(new ReflectionCollectionMessagePackSerializer <TCollection, TItem>(context, targetType, collectionTraits, itemSchema, targetInfo));
            }
 public ImmutableDictionarySerializer(SerializationContext ownerContext, PolymorphismSchema keysSchema, PolymorphismSchema valuesSchema)
     : base(ownerContext)
 {
     this._keySerializer   = ownerContext.GetSerializer <TKey>(keysSchema);
     this._valueSerializer = ownerContext.GetSerializer <TValue>(valuesSchema);
 }
Beispiel #20
0
 public MessagePackSerializer Create(SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo)
 {
     return(new ReflectionDictionaryMessagePackSerializer <TDictionary, TKey, TValue>(context, targetType, collectionTraits, schema, targetInfo));
 }
 public FSharpCollectionSerializer(SerializationContext ownerContext, PolymorphismSchema itemsSchema, string factoryTypeName)
     : base(ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom)
 {
     this._itemSerializer = ownerContext.GetSerializer <TItem>(itemsSchema);
     this._factory        = FindFactory(factoryTypeName);
 }
Beispiel #22
0
        public static MessagePackSerializer CreateCollectionSerializer <T>(
#endif // !UNITY
            SerializationContext context,
            Type targetType,
            CollectionTraits traits,
            PolymorphismSchema schema
            )
        {
            var targetInfo = UnpackHelpers.DetermineCollectionSerializationStrategy(targetType, context.CompatibilityOptions.AllowAsymmetricSerializer);

            switch (traits.DetailedCollectionType)
            {
            case CollectionDetailedKind.Array:
            {
                return(ArraySerializer.Create <T>(context, schema));
            }

            case CollectionDetailedKind.GenericList:
#if !NET35 && !UNITY
            case CollectionDetailedKind.GenericSet:
#endif // !NET35 && !UNITY
            case CollectionDetailedKind.GenericCollection:
            {
                return
                    (#if !UNITY
                     (MessagePackSerializer <T>)
                     ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>(
                         typeof(CollectionSerializerFactory <,>).MakeGenericType(typeof(T), traits.ElementType)
                         ).Create(context, targetType, traits, schema, targetInfo));
#else
                     new ReflectionCollectionMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo);
#endif // !UNITY
            }

            case CollectionDetailedKind.GenericEnumerable:
            {
                return
                    (#if !UNITY
                     (MessagePackSerializer <T>)
                     ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>(
                         typeof(EnumerableSerializerFactory <,>).MakeGenericType(typeof(T), traits.ElementType)
                         ).Create(context, targetType, traits, schema, targetInfo));
#else
                     new ReflectionEnumerableMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo);
#endif // !Enumerable
            }

            case CollectionDetailedKind.GenericDictionary:
            {
                var genericArgumentOfKeyValuePair = traits.ElementType.GetGenericArguments();
                return
                    (#if !UNITY
                     (MessagePackSerializer <T>)
                     ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>(
                         typeof(DictionarySerializerFactory <, ,>).MakeGenericType(
                             typeof(T),
                             genericArgumentOfKeyValuePair[0],
                             genericArgumentOfKeyValuePair[1]
                             )
                         ).Create(context, targetType, traits, schema, targetInfo));
#else
                     new ReflectionDictionaryMessagePackSerializer(
                         context,
                         typeof(T),
                         targetType,
                         genericArgumentOfKeyValuePair[0],
                         genericArgumentOfKeyValuePair[1],
                         traits,
                         schema,
                         targetInfo
                         );
#endif // !UNITY
            }

            case CollectionDetailedKind.NonGenericList:
            {
                return
                    (#if !UNITY
                     (MessagePackSerializer <T>)
                     ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>(
                         typeof(NonGenericListSerializerFactory <>).MakeGenericType(typeof(T))
                         ).Create(context, targetType, traits, schema, targetInfo));
#else
                     new ReflectionNonGenericListMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo);
#endif // !UNITY
            }

            case CollectionDetailedKind.NonGenericCollection:
            {
                return
                    (#if !UNITY
                     (MessagePackSerializer <T>)
                     ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>(
                         typeof(NonGenericCollectionSerializerFactory <>).MakeGenericType(typeof(T))
                         ).Create(context, targetType, traits, schema, targetInfo));
#else
                     new ReflectionNonGenericCollectionMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo);
#endif // !UNITY
            }

            case CollectionDetailedKind.NonGenericEnumerable:
            {
                return
                    (#if !UNITY
                     (MessagePackSerializer <T>)
                     ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>(
                         typeof(NonGenericEnumerableSerializerFactory <>).MakeGenericType(typeof(T))
                         ).Create(context, targetType, traits, schema, targetInfo));
#else
                     new ReflectionNonGenericEnumerableMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo);
#endif // !UNITY
            }

            case CollectionDetailedKind.NonGenericDictionary:
            {
                return
                    (#if !UNITY
                     (MessagePackSerializer <T>)
                     ReflectionExtensions.CreateInstancePreservingExceptionType <IVariantReflectionSerializerFactory>(
                         typeof(NonGenericDictionarySerializerFactory <>).MakeGenericType(typeof(T))
                         ).Create(context, targetType, traits, schema, targetInfo));
#else
                     new ReflectionNonGenericDictionaryMessagePackSerializer(context, typeof(T), targetType, traits, schema, targetInfo);
#endif // !UNITY
            }

            default:
            {
                return(null);
            }
            }
        }
Beispiel #23
0
        public static IMessagePackSingleObjectSerializer Create(SerializationContext context, Type targetType, PolymorphismSchema itemsSchema)
        {
#if DEBUG && !UNITY
            Contract.Assert(targetType.IsArray, "targetType.IsArray");
#endif // DEBUG && !UNITY

            // Check the T is SZArray -- Type.GetArrayRank() returns 1 for single dimension, non-zero based arrays, so use (SZArrayType).IsAssinableFrom() instead.
            if (targetType.GetElementType().MakeArrayType().IsAssignableFrom(targetType))
            {
                return
                    ((GetPrimitiveArraySerializer(context, targetType)
#if !UNITY
                      ?? ReflectionExtensions.CreateInstancePreservingExceptionType(
                          typeof(ArraySerializer <>).MakeGenericType(targetType.GetElementType()),
                          context,
                          itemsSchema
                          )
#else
                      ?? new UnityArraySerializer(context, targetType.GetElementType(), itemsSchema)
#endif
                      ) as IMessagePackSingleObjectSerializer);
            }
            else
            {
                return
                    (#if !UNITY
                     ReflectionExtensions.CreateInstancePreservingExceptionType(
                         typeof(MultidimensionalArraySerializer <,>).MakeGenericType(targetType, targetType.GetElementType()),
                         context,
                         itemsSchema
                         ) as IMessagePackSingleObjectSerializer);
#else
                     new UnityMultidimensionalArraySerializer(context, targetType.GetElementType(), itemsSchema);
#endif
            }
        }
        public KnownTypePolymorphicMessagePackSerializer(SerializationContext ownerContext, PolymorphismSchema schema)
            : base(ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo)
        {
            if (typeof(T).GetIsValueType())
            {
                throw SerializationExceptions.NewValueTypeCannotBePolymorphic(typeof(T));
            }

            this._schema        = schema.FilterSelf();
            this._typeHandleMap = BuildTypeCodeTypeHandleMap(schema.CodeTypeMapping);
            this._typeCodeMap   = BuildTypeHandleTypeCodeMap(schema.CodeTypeMapping);
        }
Beispiel #25
0
        protected override void BuildSerializerCodeCore(ISerializerCodeGenerationContext context, Type concreteType, PolymorphismSchema itemSchema)
        {
            var asAssemblyBuilderCodeGenerationContext = context as AssemblyBuilderCodeGenerationContext;

            if (asAssemblyBuilderCodeGenerationContext == null)
            {
                throw new ArgumentException(
                          "'context' was not created with CreateGenerationContextForCodeGeneration method.",
                          "context"
                          );
            }

            var emittingContext =
                asAssemblyBuilderCodeGenerationContext.CreateEmittingContext(
                    typeof(TObject),
                    BaseClass
                    );

            this.BuildSerializer(emittingContext, concreteType, itemSchema);
            // Finish type creation, and discard returned ctor.
            emittingContext.Emitter.CreateConstructor <TObject>();
        }
 /// <summary>
 ///		Creates the serializer type built now and returns its new instance.
 /// </summary>
 /// <typeparam name="T">Target type to be serialized/deserialized.</typeparam>
 /// <param name="context">The <see cref="SerializationContext"/> to holds serializers.</param>
 /// <param name="schema">The <see cref="PolymorphismSchema"/> for this instance.</param>
 /// <returns>
 ///		Newly built <see cref="MessagePackSerializer{T}"/> instance.
 ///		This value will not be <c>null</c>.
 ///	</returns>
 public MessagePackSerializer <T> CreateInstance <T>(SerializationContext context, PolymorphismSchema schema)
 {
     return(this.CreateConstructor <T>()(context, schema));
 }
        public TypeEmbedingPolymorphicMessagePackSerializer(SerializationContext ownerContext, PolymorphismSchema schema)
            : base(ownerContext, SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo)
        {
            if (typeof(T).GetIsValueType())
            {
                throw SerializationExceptions.NewValueTypeCannotBePolymorphic(typeof(T));
            }

            this._schema = schema.FilterSelf();
        }
Beispiel #28
0
        public string RegisterSerializer(Type targetType, EnumMemberSerializationMethod enumSerializationMethod, DateTimeMemberConversionMethod dateTimeConversionMethod, PolymorphismSchema polymorphismSchema)
        {
            var key = new SerializerFieldKey(targetType, enumSerializationMethod, dateTimeConversionMethod, polymorphismSchema);

            string fieldName;

            if (!this._dependentSerializers.TryGetValue(key, out fieldName))
            {
                fieldName = "_serializer" + this._dependentSerializers.Count.ToString(CultureInfo.InvariantCulture);
                this._dependentSerializers.Add(key, fieldName);
                this._buildingType.Members.Add(
                    new CodeMemberField(
                        typeof(MessagePackSerializer <>).MakeGenericType(Type.GetTypeFromHandle(key.TypeHandle)),
                        fieldName
                        )
                {
                    Attributes = MemberAttributes.Private
                }
                    );
            }

            return(fieldName);
        }
 public MessagePackSerializer Create(SerializationContext context, Type targetType, CollectionTraits collectionTraits, PolymorphismSchema schema, SerializationTarget targetInfo)
 {
     return(new ReflectionNonGenericEnumerableMessagePackSerializer <T>(context, targetType, collectionTraits, schema, targetInfo));
 }
 protected UnityEnumerableMessagePackSerializerBase(SerializationContext ownerContext, Type targetType, Type itemType, PolymorphismSchema schema)
     : base(ownerContext, targetType)
 {
     this._itemSerializer = ownerContext.GetSerializer(itemType, (schema ?? PolymorphismSchema.Default).ItemSchema);
 }
			public static TypeTable Create( MemberInfo member, PolymorphismSchema defaultSchema )
			{
				return
					new TypeTable(
						TypeTableEntry.Create( member, PolymorphismTarget.Member, defaultSchema ),
						TypeTableEntry.Create( member, PolymorphismTarget.CollectionItem, defaultSchema.TryGetItemSchema() ),
						TypeTableEntry.Create( member, PolymorphismTarget.DictionaryKey, defaultSchema.TryGetKeySchema() )
#if !NETFX_35 && !UNITY
						, TypeTableEntry.CreateTupleItems( member )
#endif // !NETFX_35 && !UNITY
					);
			}
 protected EnumerableMessagePackSerializerBase(SerializationContext ownerContext, PolymorphismSchema schema)
     : base(ownerContext)
 {
     this._itemSerializer = ownerContext.GetSerializer <TItem>((schema ?? PolymorphismSchema.Default).ItemSchema);
 }
			private void SetDefault( PolymorphismTarget target, string memberName, int tupleItemNumber, PolymorphismSchema defaultSchema )
			{
				if ( this._useTypeEmbedding || this._knownTypeMapping.Count > 0 )
				{
					// Default is not required.
					return;
				}

				switch ( defaultSchema.PolymorphismType )
				{
					case PolymorphismType.KnownTypes:
					{
						foreach ( var typeMapping in defaultSchema.CodeTypeMapping )
						{
							this.SetKnownType( target, memberName, tupleItemNumber, typeMapping.Key, typeMapping.Value );
						}

						break;
					}
					case PolymorphismType.RuntimeType:
					{
						this.SetRuntimeType( target, memberName, tupleItemNumber, defaultSchema.TypeVerifier );
						break;
					}
				}
			}
 /// <summary>
 ///		Initializes a new instance of the <see cref="CollectionMessagePackSerializerBase{TCollection, TItem}"/> class.
 /// </summary>
 /// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
 /// <param name="schema">
 ///		The schema for collection itself or its items for the member this instance will be used to.
 ///		<c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
 /// </param>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="ownerContext"/> is <c>null</c>.
 /// </exception>
 protected CollectionMessagePackSerializerBase(SerializationContext ownerContext, PolymorphismSchema schema)
     : base(ownerContext, schema)
 {
 }