コード例 #1
0
        public DataNode BaselineWriteSeedDataDefinition()
        {
            var mapping = new MappingDataNode();

            mapping.Add("id", Seed.ID);
            mapping.Add("name", Seed.Name);
            mapping.Add("seedName", Seed.SeedName);
            mapping.Add("displayName", Seed.DisplayName);
            mapping.Add("productPrototypes", Seed.ProductPrototypes);
            mapping.Add("harvestRepeat", Seed.HarvestRepeat.ToString());
            mapping.Add("lifespan", Seed.Lifespan.ToString(CultureInfo.InvariantCulture));
            mapping.Add("maturation", Seed.Maturation.ToString(CultureInfo.InvariantCulture));
            mapping.Add("production", Seed.Production.ToString(CultureInfo.InvariantCulture));
            mapping.Add("yield", Seed.Yield.ToString(CultureInfo.InvariantCulture));
            mapping.Add("potency", Seed.Potency.ToString(CultureInfo.InvariantCulture));
            mapping.Add("growthStages", Seed.GrowthStages.ToString(CultureInfo.InvariantCulture));
            mapping.Add("idealLight", Seed.IdealLight.ToString(CultureInfo.InvariantCulture));
            mapping.Add("idealHeat", Seed.IdealHeat.ToString(CultureInfo.InvariantCulture));

            var chemicals = new MappingDataNode();

            foreach (var(name, quantity) in Seed.Chemicals)
            {
                chemicals.Add(name, new MappingDataNode
                {
                    ["Min"]            = new ValueDataNode(quantity.Min.ToString(CultureInfo.InvariantCulture)),
                    ["Max"]            = new ValueDataNode(quantity.Max.ToString(CultureInfo.InvariantCulture)),
                    ["PotencyDivisor"] = new ValueDataNode(quantity.PotencyDivisor.ToString(CultureInfo.InvariantCulture))
                });
            }

            mapping.Add("chemicals", chemicals);

            return(mapping);
        }
コード例 #2
0
        public void DeserializeNullDefinitionTest()
        {
            var node       = new MappingDataNode().Add("unit", "null");
            var definition = Serialization.Read <FixedPoint2TestDefinition>(node);

            Assert.That(definition.Unit, Is.Null);
        }
コード例 #3
0
        ValidationNode ITypeValidator <Rsi, MappingDataNode> .Validate(ISerializationManager serializationManager,
                                                                       MappingDataNode node,
                                                                       IDependencyCollection dependencies,
                                                                       ISerializationContext?context)
        {
            if (!node.TryGet("sprite", out var pathNode) || pathNode is not ValueDataNode valuePathNode)
            {
                return(new ErrorNode(node, "Missing/Invalid sprite node"));
            }

            if (!node.TryGet("state", out var stateNode) || stateNode is not ValueDataNode)
            {
                return(new ErrorNode(node, "Missing/Invalid state node"));
            }

            var path = serializationManager.ValidateNode(typeof(ResourcePath),
                                                         new ValueDataNode($"{SharedSpriteComponent.TextureRoot / valuePathNode.Value}"), context);

            if (path is ErrorNode)
            {
                return(path);
            }

            return(new ValidatedValueNode(node));
        }
コード例 #4
0
 DeserializationResult ITypeReader <SpriteSpecifier, MappingDataNode> .Read(
     ISerializationManager serializationManager, MappingDataNode node,
     IDependencyCollection dependencies,
     bool skipHook, ISerializationContext?context)
 {
     return(((ITypeReader <Rsi, MappingDataNode>) this).Read(serializationManager, node, dependencies, skipHook, context));
 }
コード例 #5
0
        public void DeserializeNullDefinitionTest()
        {
            var node       = new MappingDataNode().Add("unit", "null");
            var definition = Serialization.ReadValueOrThrow <ReagentUnitTestDefinition>(node);

            Assert.That(definition.Unit, Is.Null);
        }
コード例 #6
0
 ValidationNode ITypeValidator <SpriteSpecifier, MappingDataNode> .Validate(
     ISerializationManager serializationManager, MappingDataNode node,
     IDependencyCollection dependencies,
     ISerializationContext?context)
 {
     return(((ITypeReader <Rsi, MappingDataNode>) this).Validate(serializationManager, node, dependencies, context));
 }
コード例 #7
0
        public DataNode Write(ISerializationManager serializationManager, Rsi value, bool alwaysWrite = false,
                              ISerializationContext?context = null)
        {
            var mapping = new MappingDataNode();

            mapping.Add("sprite", serializationManager.WriteValue(value.RsiPath));
            mapping.Add("state", new ValueDataNode(value.RsiState));
            return(mapping);
        }
コード例 #8
0
        public DeserializationResult Populate(
            object target,
            MappingDataNode mapping,
            ISerializationManager serialization,
            ISerializationContext?context,
            bool skipHook)
        {
            var fields = _deserialize(mapping, serialization, context, skipHook);

            return(_populate(target, fields, DefaultValues));
        }
コード例 #9
0
        ValidationNode Validate(ISerializationManager serializationManager, MappingDataNode node, ISerializationContext?context)
        {
            var mapping = new Dictionary <ValidationNode, ValidationNode>();

            foreach (var(key, val) in node.Children)
            {
                mapping.Add(serializationManager.ValidateNode(typeof(TKey), key, context), serializationManager.ValidateNode(typeof(TValue), val, context));
            }

            return(new ValidatedMappingNode(mapping));
        }
コード例 #10
0
        private SerializeDelegateSignature EmitSerializeDelegate()
        {
            MappingDataNode SerializeDelegate(
                object obj,
                ISerializationManager manager,
                ISerializationContext?context,
                bool alwaysWrite,
                object?[] defaultValues)
            {
                var mapping = new MappingDataNode();

                for (var i = BaseFieldDefinitions.Length - 1; i >= 0; i--)
                {
                    var fieldDefinition = BaseFieldDefinitions[i];

                    if (fieldDefinition.Attribute.ReadOnly)
                    {
                        continue;
                    }

                    if (fieldDefinition.Attribute.ServerOnly &&
                        !IoCManager.Resolve <INetManager>().IsServer)
                    {
                        continue;
                    }

                    var value = FieldAccessors[i](ref obj);

                    if (value == null)
                    {
                        continue;
                    }

                    if (!fieldDefinition.Attribute.Required &&
                        !alwaysWrite &&
                        Equals(value, defaultValues[i]))
                    {
                        continue;
                    }

                    var type = fieldDefinition.FieldType;
                    var node = fieldDefinition.Attribute.CustomTypeSerializer != null
                        ? manager.WriteWithTypeSerializer(type, fieldDefinition.Attribute.CustomTypeSerializer,
                                                          value, alwaysWrite, context)
                        : manager.WriteValue(type, value, alwaysWrite, context);

                    mapping[fieldDefinition.Attribute.Tag] = node;
                }

                return(mapping);
            }

            return(SerializeDelegate);
        }
コード例 #11
0
        public SerializationReadBenchmark()
        {
            InitializeSerialization();

            StringDataDefNode = new MappingDataNode();
            StringDataDefNode.Add(new ValueDataNode("string"), new ValueDataNode("ABC"));

            var yamlStream = new YamlStream();

            yamlStream.Load(new StringReader(SeedDataDefinition.Prototype));

            SeedNode = yamlStream.Documents[0].RootNode.ToDataNodeCast <SequenceDataNode>().Cast <MappingDataNode>(0);
        }
コード例 #12
0
        public void PopulateElementDescriptor(MappingDataNode node, ISerializationManager serializationManager)
        {
            MappingDataNode original = (MappingDataNode)serializationManager.WriteValue(ElementDescriptor.GetType(), ElementDescriptor);

            foreach (var key in node.Keys)
            {
                original.Remove(key);
            }

            MappingDataNode newNode = original.Merge(node);

            ElementDescriptor = (ElementDescriptor)serializationManager.Read(ElementDescriptor.GetType(), newNode);
            UpdateElementDescriptor();
        }
コード例 #13
0
        public void SerializeListTest()
        {
            // Arrange
            var data     = _serializableList;
            var serMan   = IoCManager.Resolve <ISerializationManager>();
            var sequence = (SequenceDataNode)serMan.WriteValue(data);
            var mapping  = new MappingDataNode();

            mapping.Add("datalist", sequence);

            // Assert
            var result = NodeToYamlText(mapping);

            Assert.That(result, Is.EqualTo(_serializedListYaml));
        }
コード例 #14
0
        public DeserializationResult Read(ISerializationManager serializationManager,
                                          MappingDataNode node, IDependencyCollection dependencies, bool skipHook, ISerializationContext?context)
        {
            var dict         = new Dictionary <TKey, TValue>();
            var mappedFields = new Dictionary <DeserializationResult, DeserializationResult>();

            foreach (var(key, value) in node.Children)
            {
                var(keyVal, keyResult)     = serializationManager.ReadWithValueOrThrow <TKey>(key, context, skipHook);
                var(valueResult, valueVal) = serializationManager.ReadWithValueCast <TValue>(typeof(TValue), value, context, skipHook);

                dict.Add(keyVal, valueVal !);
                mappedFields.Add(keyResult, valueResult);
            }

            return(new DeserializedDictionary <Dictionary <TKey, TValue>, TKey, TValue>(dict, mappedFields, dictInstance => dictInstance));
        }
コード例 #15
0
        private MappingDataNode InterfaceWrite(
            ISerializationManager serializationManager,
            IDictionary <TKey, TValue> value,
            bool alwaysWrite = false,
            ISerializationContext?context = null)
        {
            var mappingNode = new MappingDataNode();

            foreach (var(key, val) in value)
            {
                mappingNode.Add(
                    serializationManager.WriteValue(key, alwaysWrite, context),
                    serializationManager.WriteValue(typeof(TValue), val, alwaysWrite, context));
            }

            return(mappingNode);
        }
コード例 #16
0
        public void DeserializationTest()
        {
            var dictionary = new Dictionary <int, string>
            {
                [1] = "A",
                [2] = "B",
                [3] = "C"
            };
            var node = new MappingDataNode();

            node.Add("1", new ValueDataNode("A"));
            node.Add("2", new ValueDataNode("B"));
            node.Add("3", new ValueDataNode("C"));

            var deserializedDictionary = Serialization.ReadValue <Dictionary <int, string> >(node);

            Assert.That(deserializedDictionary, Is.EqualTo(dictionary));
        }
コード例 #17
0
        DeserializationResult ITypeReader <Rsi, MappingDataNode> .Read(ISerializationManager serializationManager,
                                                                       MappingDataNode node,
                                                                       IDependencyCollection dependencies,
                                                                       bool skipHook, ISerializationContext?context)
        {
            if (!node.TryGet("sprite", out var pathNode))
            {
                throw new InvalidMappingException("Expected sprite-node");
            }

            if (!node.TryGet("state", out var stateNode) || stateNode is not ValueDataNode valueDataNode)
            {
                throw new InvalidMappingException("Expected state-node as a valuenode");
            }

            var path = serializationManager.ReadValueOrThrow <ResourcePath>(pathNode, context, skipHook);

            return(new DeserializedValue <Rsi>(new Rsi(path, valueDataNode.Value)));
        }
コード例 #18
0
ファイル: DMFParser.cs プロジェクト: wixoaGit/OpenDream
        public MappingDataNode Attributes()
        {
            var node = new MappingDataNode();

            while (TryGetAttribute(out var key, out var value))
            {
                if (value == "none")
                {
                    continue;
                }

                if (value[0] == '"')
                {
                    value = value.Substring(1, value.Length - 2);
                }
                node.Add(key, value);
            }

            return(node);
        }
コード例 #19
0
        public ValidationNode Validate(ISerializationManager serializationManager, MappingDataNode node,
                                       IDependencyCollection dependencies,
                                       ISerializationContext?context = null)
        {
            if (node.Children.Count != 1)
            {
                return(new ErrorNode(node, "More or less than 1 Mapping for ValueTuple found."));
            }

            var entry = node.Children.First();
            var dict  = new Dictionary <ValidationNode, ValidationNode>
            {
                {
                    serializationManager.ValidateNode(typeof(T1), entry.Key, context),
                    serializationManager.ValidateNode(typeof(T2), entry.Value, context)
                }
            };

            return(new ValidatedMappingNode(dict));
        }
コード例 #20
0
        public ValidationNode Validate(
            ISerializationManager serialization,
            MappingDataNode mapping,
            ISerializationContext?context)
        {
            var validatedMapping = new Dictionary <ValidationNode, ValidationNode>();

            foreach (var(key, val) in mapping.Children)
            {
                if (key is not ValueDataNode valueDataNode)
                {
                    validatedMapping.Add(new ErrorNode(key, "Key not ValueDataNode."), new InconclusiveNode(val));
                    continue;
                }

                var field = BaseFieldDefinitions.FirstOrDefault(f => f.Attribute.Tag == valueDataNode.Value);
                if (field == null)
                {
                    var error = new ErrorNode(
                        key,
                        $"Field \"{valueDataNode.Value}\" not found in \"{Type}\".",
                        false);

                    validatedMapping.Add(error, new InconclusiveNode(val));
                    continue;
                }

                var            keyValidated = serialization.ValidateNode(typeof(string), key, context);
                ValidationNode valValidated = field.Attribute.CustomTypeSerializer != null
                    ? serialization.ValidateNodeWith(field.FieldType,
                                                     field.Attribute.CustomTypeSerializer, val, context)
                    : serialization.ValidateNode(field.FieldType, val, context);

                validatedMapping.Add(keyValidated, valValidated);
            }

            return(new ValidatedMappingNode(validatedMapping));
        }
コード例 #21
0
        private SerializeDelegateSignature EmitSerializeDelegate()
        {
            MappingDataNode SerializeDelegate(
                object obj,
                ISerializationManager manager,
                ISerializationContext?context,
                bool alwaysWrite,
                object?[] defaultValues)
            {
                var mapping = new MappingDataNode();

                for (var i = BaseFieldDefinitions.Length - 1; i >= 0; i--)
                {
                    var fieldDefinition = BaseFieldDefinitions[i];

                    if (fieldDefinition.Attribute.ReadOnly)
                    {
                        continue;
                    }

                    if (fieldDefinition.Attribute.ServerOnly &&
                        !IoCManager.Resolve <INetManager>().IsServer)
                    {
                        continue;
                    }

                    var value = FieldAccessors[i](ref obj);

                    if (value == null)
                    {
                        continue;
                    }

                    if (!fieldDefinition.Attribute.Required &&
                        !alwaysWrite &&
                        Equals(value, defaultValues[i]))
                    {
                        continue;
                    }

                    var type = fieldDefinition.FieldType;

                    DataNode node;
                    if (fieldDefinition.Attribute.CustomTypeSerializer != null)
                    {
                        var foundInterface = false;
                        foreach (var @interface in fieldDefinition.Attribute.CustomTypeSerializer.GetInterfaces())
                        {
                            if (@interface.GetGenericTypeDefinition() != typeof(ITypeWriter <>))
                            {
                                continue;
                            }
                            if (@interface.GenericTypeArguments[0] == type)
                            {
                                foundInterface = true;
                            }
                        }

                        if (!foundInterface)
                        {
                            throw new InvalidOperationException(
                                      $"Could not find implementation of ITypeWriter for type {type} on customtypeserializer {fieldDefinition.Attribute.CustomTypeSerializer}");
                        }

                        node = manager.WriteWithTypeSerializer(type, fieldDefinition.Attribute.CustomTypeSerializer,
                                                               value, alwaysWrite, context);
                    }
                    else
                    {
                        node = manager.WriteValue(type, value, alwaysWrite, context);
                    }

                    mapping[fieldDefinition.Attribute.Tag] = node;
                }

                return(mapping);
            }

            return(SerializeDelegate);
        }
コード例 #22
0
 ValidationNode ITypeValidator <Dictionary <TKey, TValue>, MappingDataNode> .Validate(
     ISerializationManager serializationManager,
     MappingDataNode node, IDependencyCollection dependencies, ISerializationContext?context)
 {
     return(Validate(serializationManager, node, context));
 }
コード例 #23
0
        public DeserializationResult Read(ISerializationManager serializationManager, MappingDataNode node,
                                          IDependencyCollection dependencies,
                                          bool skipHook,
                                          ISerializationContext?context = null)
        {
            if (node.Children.Count != 1)
            {
                throw new InvalidMappingException("Less than or more than 1 mappings provided to ValueTupleSerializer");
            }

            var entry = node.Children.First();
            var v1    = serializationManager.ReadValueOrThrow <T1>(entry.Key, context, skipHook);
            var v2    = serializationManager.ReadValueOrThrow <T2>(entry.Value, context, skipHook);

            return(new DeserializedValue <ValueTuple <T1, T2> >(new ValueTuple <T1, T2>(v1, v2)));
        }
コード例 #24
0
        public void ParityTest()
        {
            var mapping = new MappingDataNode();

            mapping.Add(GetOnlyPropertyName, new ValueDataNode("5"));
            mapping.Add(GetOnlyPropertyFieldTargetedName, new ValueDataNode("10"));
            mapping.Add(GetAndSetPropertyName, new ValueDataNode("15"));
            mapping.Add(FieldName, new ValueDataNode("20"));
            mapping.Add(GetOnlyPropertyWithOtherAttributeFieldTargetedName, new ValueDataNode("25"));
            mapping.Add(GetOnlyPropertyFieldTargetedAndOtherAttributeName, new ValueDataNode("30"));

            var definition = Serialization.ReadValue <PropertyAndFieldDefinitionTestDefinition>(mapping);

            Assert.NotNull(definition);

            // Get only property with backing field, property targeted
            Assert.That(definition !.GetOnlyProperty, Is.EqualTo(5));

            var backingField = definition.GetType().GetBackingField(GetOnlyPropertyName);

            Assert.NotNull(backingField);

            var backingFieldValue = backingField !.GetValue(definition);

            Assert.That(backingFieldValue, Is.EqualTo(5));

            // Get only property with backing field, field targeted
            Assert.That(definition.GetOnlyPropertyFieldTargeted, Is.EqualTo(10));

            // Get and set property with backing field, property targeted
            Assert.That(definition.GetAndSetProperty, Is.EqualTo(15));

            // Field
            Assert.That(definition.Field, Is.EqualTo(20));

            // Get only property with backing field, property targeted with another attribute field targeted
            Assert.That(definition.GetOnlyPropertyWithOtherAttributeFieldTargeted, Is.EqualTo(25));

            var property = definition.GetType().GetProperty(GetOnlyPropertyWithOtherAttributeFieldTargetedName);

            Assert.NotNull(property);

            var propertyInfo = new SpecificPropertyInfo(property !);

            Assert.NotNull(propertyInfo.GetAttribute <DataFieldAttribute>());
            Assert.NotNull(propertyInfo.GetBackingField() !.GetAttribute <AlwaysPushInheritanceAttribute>());

            // We check for the property info properly finding field targeted attributes as
            // well, otherwise we run the risk of the data field being targeted to the
            // property but an additional attribute like AlwaysPushInheritance being targeted
            // to the field, as was the case in EntityPrototype.
            // And I don't want to debug that ever again.
            Assert.NotNull(propertyInfo.DeclaringType);

            var dataDefinition = ((SerializationManager)Serialization).GetDefinition(propertyInfo.DeclaringType !);

            Assert.NotNull(dataDefinition);

            var alwaysPushDataField = propertyInfo.GetAttribute <DataFieldAttribute>();
            var propertyDefinition  =
                dataDefinition !.BaseFieldDefinitions.Single(e => e.Attribute.Equals(alwaysPushDataField));
            var inheritanceBehaviour = propertyDefinition.InheritanceBehavior;

            Assert.That(inheritanceBehaviour, Is.EqualTo(InheritanceBehavior.Always));

            // Get only property with backing field, field targeted with another attribute property targeted
            Assert.That(definition.GetOnlyPropertyFieldTargetedAndOtherAttribute, Is.EqualTo(30));

            property = definition.GetType().GetProperty(GetOnlyPropertyFieldTargetedAndOtherAttributeName);
            Assert.NotNull(property);

            propertyInfo = new SpecificPropertyInfo(property !);

            // Data field is targeted to the backing field
            Assert.NotNull(propertyInfo.GetBackingField() !.GetAttribute <DataFieldAttribute>());
            Assert.Null(propertyInfo.GetAttribute <DataFieldAttribute>());
            Assert.NotNull(propertyInfo.GetAttribute <DataFieldAttribute>(true));

            // NeverPushInheritanceAttribute is targeted to the property
            Assert.NotNull(propertyInfo.GetAttribute <NeverPushInheritanceAttribute>());
            Assert.Null(propertyInfo.GetBackingField() !.GetAttribute <NeverPushInheritanceAttribute>());
            Assert.NotNull(propertyInfo.GetAttribute <NeverPushInheritanceAttribute>(true));

            var neverPushDataField = propertyInfo.GetBackingField() !.GetAttribute <DataFieldAttribute>();

            propertyDefinition =
                dataDefinition !.BaseFieldDefinitions.Single(e => e.Attribute.Equals(neverPushDataField));
            inheritanceBehaviour = propertyDefinition.InheritanceBehavior;
            dataDefinition       = ((SerializationManager)Serialization).GetDefinition(property !.DeclaringType !);
            Assert.NotNull(dataDefinition);
            Assert.That(inheritanceBehaviour, Is.EqualTo(InheritanceBehavior.Never));
        }