Esempio n. 1
0
        /// <summary>
        /// Writes a property container the specified buffer.
        /// </summary>
        /// <param name="writer">The buffer to write the object to.</param>
        /// <param name="value">The container to write.</param>
        /// <param name="parameters">The parameters to use when writing.</param>
        /// <typeparam name="T">The type to serialize.</typeparam>
        public static void ToJson <T>(JsonWriter writer, T value, JsonSerializationParameters parameters = default)
        {
            var container = new PropertyWrapper <T>(value);

            var serializedReferences = default(SerializedReferences);
            var state = parameters.State ?? (parameters.RequiresThreadSafety ? new JsonSerializationState() : GetSharedState());

            if (!parameters.DisableSerializedReferences)
            {
                serializedReferences = state.GetSerializedReferences();
                var serializedReferenceVisitor = state.GetSerializedReferenceVisitor();
                serializedReferenceVisitor.SetSerializedReference(serializedReferences);
                PropertyContainer.Accept(serializedReferenceVisitor, ref container);
            }

            var visitor = state.GetJsonPropertyWriter();

            visitor.SetWriter(writer);
            visitor.SetSerializedType(parameters.SerializedType);
            visitor.SetDisableRootAdapters(parameters.DisableRootAdapters);
            visitor.SetGlobalAdapters(GetGlobalAdapters());
            visitor.SetUserDefinedAdapters(parameters.UserDefinedAdapters);
            visitor.SetGlobalMigrations(GetGlobalMigrations());
            visitor.SetUserDefinedMigration(parameters.UserDefinedMigrations);
            visitor.SetSerializedReferences(serializedReferences);

            using (visitor.Lock()) PropertyContainer.Accept(visitor, ref container);
        }
Esempio n. 2
0
            public void PropertyVisitor_VisitingAUserDefinedContainerUsingAUserDefinedVisitorWithOpenGenerics_DoesNotThrow()
            {
                var container = (object)new Container
                {
                    Int32List = new List <int>
                    {
                        1, 3, 6, 9
                    },
                    NestedList = new List <Nested>
                    {
                        new Nested()
                    },
                    InterfaceList = new List <IData>
                    {
                        new UserDataA(),
                        new UserDataB()
                    },
                    Float32ListList = new List <List <float> >
                    {
                        new List <float> {
                            1, 2, 3
                        },
                        new List <float> {
                            4, 5, 6
                        }
                    }
                };

                PropertyContainer.Accept(new UserDefinedVisitorWithOpenGeneric(), container);
            }
        void SetTarget()
        {
            try
            {
                var value = Provider.GetContent();
                if (null == value)
                {
                    Debug.LogError($"{TypeUtility.GetTypeDisplayName(Provider.GetType())}: Releasing content named '{Provider.Name}' because it returned null value.");
                    m_RequestQuit = true;
                    return;
                }

                // Removing from the hierarchy here because Unity will try to bind the elements to a serializedObject and
                // we want to use our own bindings. This will be fixed in UIToolkit directly.
                m_ContentRoot.RemoveFromHierarchy();
                m_ContentNotReadyRoot.RemoveFromHierarchy();

                var visitor = new SetTargetVisitor {
                    Content = this, Inspector = m_ContentRoot
                };
                PropertyContainer.Accept(visitor, ref value);
                Root.contentContainer.Add(m_ContentRoot);
            }
            catch (Exception ex)
            {
                Debug.LogError($"{TypeUtility.GetTypeDisplayName(Provider.GetType())}: Releasing content named '{Provider.Name}' because it threw an exception.");
                m_RequestQuit = true;
                Debug.LogException(ex);
            }
        }
Esempio n. 4
0
        public void PropertyVisitor_ClassWithMultidimensionalArray_WhenArrayIsNull()
        {
            var container = new ClassWithMultidimensionalArray();

            PropertyContainer.Accept(new EmptyVisitor(), container);
            PropertyContainer.Accept(new EmptyLowLevelVisitor(), container);
        }
Esempio n. 5
0
            /// <summary>
            /// Invoked by property.Accept and provides the strongly typed value.
            /// </summary>
            void IPropertyVisitor.Visit <TContainer, TValue>(Property <TContainer, TValue> property, ref TContainer container)
            {
                var value = property.GetValue(ref container);

                // Re-entry will invoke the strongly typed visit callback for this container.
                PropertyContainer.Accept(this, value);
            }
        public static IInspector GetAttributeInspector <TValue>(InspectorVisitor.InspectorContext inspectorContext,
                                                                IProperty property, ref TValue value, PropertyPath path)
        {
            if (RuntimeTypeInfoCache <TValue> .CanBeNull && EqualityComparer <TValue> .Default.Equals(value, default))
            {
                return(null);
            }

            if (!RuntimeTypeInfoCache <TValue> .IsContainerType)
            {
                var inspector = InspectorRegistry.GetAttributeInspector <TValue>(property);
                if (null != inspector)
                {
                    inspector.Context = new InspectorContext <TValue>(
                        inspectorContext.Root,
                        path,
                        property,
                        property.GetAttributes()
                        );
                }

                return(inspector);
            }

            using (var scoped = ScopedVisitor <CustomInspectorVisitor <TValue> > .Make())
            {
                var visitor = scoped.Visitor;
                visitor.Target       = InspectorTarget.AttributeInspector;
                visitor.PropertyPath = path;
                visitor.Root         = inspectorContext.Root;
                visitor.Property     = property;
                PropertyContainer.Accept(visitor, ref value);
                return(visitor.Inspector);
            }
        }
        public void PropertyVisitor_WhenChainingAdapters_RespectVisitation(int count, params VisitStatus[] statuses)
        {
            var container = new Container();

            var expectedHasDefault = true;

            foreach (var status in statuses)
            {
                if (status == VisitStatus.Stop)
                {
                    expectedHasDefault = false;
                    break;
                }

                if (status == VisitStatus.Handled)
                {
                    break;
                }
            }

            var visitor = new TestVisitor(expectedHasDefault ? "0" : "");

            foreach (var status in statuses)
            {
                visitor.AddAdapter(new ChainedAdapter(visitor, status));
            }

            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(), Is.EqualTo(new string('0', count)));
        }
Esempio n. 8
0
                protected override void VisitProperty <TContainer, TValue>(Property <TContainer, TValue> property, ref TContainer container, ref TValue value)
                {
                    Debug.Log($"Name=[{property.Name}] TContainer=[{typeof(TContainer)}] TValue=[{typeof(TValue)}]");

                    UserDefinedOpenGeneric <TContainer, TValue>();

                    PropertyContainer.Accept(this, ref value);
                }
        public void PropertyVisitor_WithoutAdapters_CallsDefaultBehaviour()
        {
            var container = new Container();
            var visitor   = new TestVisitor("No adapters were reached");

            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(), Is.EqualTo("No adapters were reached"));
        }
Esempio n. 10
0
                protected override void VisitList <TContainer, TList, TElement>(Property <TContainer, TList> property, ref TContainer container, ref TList value)
                {
                    Debug.Log($"Name=[{property.Name}] TContainer=[{typeof(TContainer)}] TList=[{typeof(TList)}] TElement=[{typeof(TElement)}]");

                    UserDefinedOpenGeneric <TContainer, TList>();

                    PropertyContainer.Accept(this, ref value);
                }
Esempio n. 11
0
                protected override void VisitProperty <TContainer, TValue>(Property <TContainer, TValue> property, ref TContainer container, ref TValue value)
                {
                    Debug.Log($"Name=[{property.Name}] TContainer=[{typeof(TContainer)}] TValue=[{typeof(TValue)}]");

                    new UserDefinedFeature().Execute <TContainer, TValue>(value);

                    PropertyContainer.Accept(this, ref value);
                }
        public void PropertyVisitor_WithContravariantAdapters_CallsMostTyped()
        {
            var container = new ContainerWithInterface();
            var visitor   = new TestVisitor("");

            visitor.AddAdapter(new ContravariantAdapter(visitor));

            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(), Is.EqualTo("ABA"));
        }
        public void PropertyVisitor_WithWrappingAdapter_CallsAdapterAndDefault()
        {
            var container = new Container();
            var visitor   = new TestVisitor("Failure is inevitable");

            visitor.AddAdapter(new WrappingAdapter(visitor));

            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(),
                        Is.EqualTo("This sentence: \"Failure is inevitable\" is simply not true"));
        }
        public void PropertyVisitor_WithExcludeAdapter_StopsVisitationWhenRequired()
        {
            var container = new ExcludeContainer();
            var visitor   = new TestVisitor("X");

            visitor.AddAdapter(new ExcludeAdapter(visitor));

            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(), Does.Not.Contain("int"));
            Assert.That(visitor.ToString(), Does.Contain("float"));
        }
        public void PropertyVisitor_WithMixedAdapters_CanIterate()
        {
            var container = new MixedContainer();
            var visitor   = new TestVisitor("");

            visitor.AddAdapter(new MixedContravariantAdapter(visitor));
            visitor.AddAdapter(new MixedAdapter(visitor));

            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(), Is.EqualTo("AA"));
        }
        public void PropertyVisitor_WithInertAdapter_ContinuesAsExpected()
        {
            var container = new Container();
            var visitor   = new TestVisitor("");

            visitor.AddAdapter(new MixedContravariantAdapter(visitor));
            visitor.AddAdapter(new MixedAdapter(visitor));
            visitor.AddAdapter(new MultiAdapter(visitor));

            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(), Is.EqualTo("IVisit<Container, int>"));
        }
Esempio n. 17
0
            public void VisitAdapter_AdapterWithCovariance_VisitsAllDerivedTypes()
            {
                var container = new Container
                {
                    Base = new ConcreteA(),
                    A    = new ConcreteA(),
                    B    = new ConcreteB(),
                    C    = new ConcreteC(),
                };

                PropertyContainer.Accept(new TestVisitor().WithAdapter <TestAdapter>(), ref container);
            }
        public void ClassWithSomeResolvedGenerics_HasPropertyBagGenerated()
        {
            Assert.That(PropertyBagStore.GetPropertyBag(typeof(ClassWithGenericParameterAndGenericBase <int>)), Is.InstanceOf(typeof(ContainerPropertyBag <ClassWithGenericParameterAndGenericBase <int> >)));

            var container = new ClassWithGenericParameterAndGenericBase <int>
            {
                Value0 = 1,
                Value1 = 4.2f
            };

            PropertyContainer.Accept(new DebugVisitor(), ref container);
        }
        public void PropertyVisitor_WithMultiAdapter_CallsMostTypedAdapter()
        {
            var container = new Container();
            var visitor   = new TestVisitor("Failure");

            visitor.AddAdapter(new MultiAdapter(visitor));

            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(), Is.EqualTo("IVisit<Container, int>"));
            visitor.Reset();
            PropertyContainer.Accept(visitor, ref container);
            Assert.That(visitor.ToString(), Is.EqualTo("IVisit<Container, int>"));
        }
        public void PathVisitor_VisitNestedContainer_ReturnVisitErrorCodeOk()
        {
            var container = new StructWithNestedStruct
            {
                Container = new StructWithPrimitives()
            };

            var visitor = new TestPathVisitor(new PropertyPath($"{nameof(StructWithNestedStruct.Container)}.{nameof(StructWithPrimitives.Float64Value)}"));

            PropertyContainer.Accept(visitor, ref container);

            Assert.That(visitor.ErrorCode, Is.EqualTo(VisitErrorCode.Ok));
        }
        public void PropertyContainer_VisitAtPath_VisitsCorrectPath(string path, string expected)
        {
            var visitor   = new AssertNameAtPath();
            var container = new ClassWithPolymorphicFields
            {
                ObjectValue    = new ClassDerivedB(),
                AbstractValue  = new ClassDerivedA(),
                InterfaceValue = new ClassDerivedA1()
            };

            PropertyContainer.Accept(visitor, ref container, new PropertyPath(path));
            visitor.Matches(expected);
            visitor.Reset();
        }
Esempio n. 22
0
        public void PropertyVisitor_ClassWithMultidimensionalArray_WhenArrayIsNotNull()
        {
            var container = new ClassWithMultidimensionalArray
            {
                Int32MultidimensionalArray = new [, ]
                {
                    { 1, 2 },
                    { 3, 4 }
                }
            };

            PropertyContainer.Accept(new EmptyVisitor(), container);
            PropertyContainer.Accept(new EmptyLowLevelVisitor(), container);
        }
        public void ClassWithGenericBaseClass_HasPropertyBagGenerated()
        {
            Assert.That(PropertyBagStore.GetPropertyBag(typeof(Baz)), Is.InstanceOf(typeof(ContainerPropertyBag <Baz>)));

            var container = new Baz
            {
                Root           = 1,
                Value          = "Hello",
                Value0         = 1.23f,
                Value1         = 42,
                Value0Property = 1.4f
            };

            PropertyContainer.Accept(new DebugVisitor(), ref container);
        }
        public void PathVisitor_VisitArrayElement_ReturnVisitErrorCodeOk()
        {
            var container = new ClassWithLists
            {
                Int32List = new List <int> {
                    1, 2, 3
                }
            };

            var visitor = new TestPathVisitor(new PropertyPath($"{nameof(ClassWithLists.Int32List)}[1]"));

            PropertyContainer.Accept(visitor, ref container);

            Assert.That(visitor.ErrorCode, Is.EqualTo(VisitErrorCode.Ok));
        }
Esempio n. 25
0
            public void PropertyVisitor_VisitingAStructWithPrimitiveProperties_DoesNotAllocate()
            {
                var container = new StructWithPrimitiveProperties();
                var visitor   = new CountVisitor();

                GCAllocTest.Method(() =>
                {
                    visitor.Count = 0;
                    PropertyContainer.Accept(visitor, ref container);
                })
                .ExpectedCount(0)
                .Warmup()
                .Run();

                Assert.That(visitor.Count, Is.EqualTo(2));
            }
        public void PropertyVisitor_WhenCallingMultipleAdapters_RespectVisitation(bool withAdapters)
        {
            for (var count = 0; count < 10; ++count)
            {
                var container = new Container();
                var visitor   = new TestVisitor("1");

                visitor.AddAdapter(new MultiContinueAdapter(visitor, count, withAdapters));
                visitor.AddAdapter(new MessageAdapter(visitor, "0"));

                PropertyContainer.Accept(visitor, ref container);

                var result = withAdapters ? new string('0', count) : new string('1', count);
                Assert.That(visitor.ToString(), Is.EqualTo(result));
            }
        }
Esempio n. 27
0
            public void PropertyVisitor_VisitingAClassWithCollectionProperties_DoesNotAllocate()
            {
                var container = new ClassWithCollectionProperties
                {
                    Float32List = new List <float> {
                        1, 2, 3
                    }
                };
                var visitor = new CountVisitor();

                GCAllocTest.Method(() =>
                {
                    visitor.Count = 0;
                    PropertyContainer.Accept(visitor, ref container);
                })
                .ExpectedCount(2)
                .Warmup()
                .Run();

                Assert.That(visitor.Count, Is.EqualTo(4));
            }
Esempio n. 28
0
        public void PropertyVisitor_NullCollectionType_VisitCollectionIsInvoked()
        {
            var withVisitCollection    = new VisitorWithVisitCollection();
            var withoutVisitCollection = new VisitorWithoutVisitCollection();

            var container = new ClassWithLists()
            {
                Int32List           = new List <int>(),
                ClassContainerList  = null,
                StructContainerList = null,
                Int32ListList       = null
            };

            PropertyContainer.Accept(withVisitCollection, container);
            PropertyContainer.Accept(withoutVisitCollection, container);

            Assert.That(withVisitCollection.VisitCollectionCount, Is.EqualTo(4));
            Assert.That(withVisitCollection.VisitPropertyCount, Is.EqualTo(0));

            Assert.That(withoutVisitCollection.VisitCollectionCount, Is.EqualTo(0));
            Assert.That(withoutVisitCollection.VisitPropertyCount, Is.EqualTo(4));
        }
Esempio n. 29
0
        /// <summary>
        /// Serializes the given object to the given stream as binary.
        /// </summary>
        /// <param name="stream">The stream to write the object to.</param>
        /// <param name="value">The object to serialize.</param>
        /// <param name="parameters">Parameters to use when writing.</param>
        /// <typeparam name="T">The type to serialize.</typeparam>
        public static void ToBinary <T>(UnsafeAppendBuffer *stream, T value, BinarySerializationParameters parameters = default)
        {
            var container = new PropertyWrapper <T>(value);

            var state   = parameters.State ?? (parameters.RequiresThreadSafety ? new BinarySerializationState() : GetSharedState());
            var visitor = state.GetBinaryPropertyWriter();

            visitor.SetStream(stream);
            visitor.SetSerializedType(parameters.SerializedType);
            visitor.SetDisableRootAdapters(parameters.DisableRootAdapters);
            visitor.SetGlobalAdapters(GetGlobalAdapters());
            visitor.SetUserDefinedAdapters(parameters.UserDefinedAdapters);

            visitor.SetSerializedReferences(parameters.DisableSerializedReferences ? default : state.GetSerializedReferences());

            using (visitor.Lock()) PropertyContainer.Accept(visitor, ref container);

            if (!parameters.DisableSerializedReferences)
            {
                state.GetSerializedReferences().Clear();
            }
        }
Esempio n. 30
0
        public void Visit_NestedLists_PropertyBagsAreGenerated()
        {
            var container = new List <List <List <int> > >
            {
                new List <List <int> >
                {
                    new List <int> {
                        1, 2, 3
                    },
                    new List <int> {
                        4, 5, 6
                    }
                },
                new List <List <int> >
                {
                    new List <int> {
                        7, 8, 9
                    },
                    new List <int> {
                        10, 11, 12
                    }
                },
                new List <List <int> >
                {
                    new List <int> {
                        13, 14, 15
                    },
                    new List <int> {
                        16, 17, 18
                    }
                }
            };

            var visitor = new Visitor();

            PropertyContainer.Accept(visitor, ref container);

            Assert.That(visitor.Count, Is.EqualTo(27));
        }