Exemplo n.º 1
2
        private BlueprintManager LoadBlueprints()
        {
            var           blueprintManager           = new BlueprintManager();
            XmlSerializer blueprintManagerSerializer = null;

            Object[] blueprintAssets = Resources.LoadAll(this.BlueprintAssetsFolder);

            foreach (var blueprintObjectAsset in blueprintAssets)
            {
                var blueprintAsset = blueprintObjectAsset as TextAsset;

                if (blueprintAsset != null)
                {
                    var blueprintStream = new MemoryStream(blueprintAsset.bytes);

                    // Load blueprints.
                    BlueprintManager subBlueprintManager = null;

                    if (Application.isEditor || this.UseXmlInBuild)
                    {
                        if (blueprintManagerSerializer == null)
                        {
                            blueprintManagerSerializer = new XmlSerializer(typeof(BlueprintManager));
                        }
                        try
                        {
                            subBlueprintManager =
                                (BlueprintManager)blueprintManagerSerializer.Deserialize(blueprintStream);
                        }
                        catch (XmlException e)
                        {
                            Debug.LogError(
                                string.Format(
                                    "Exception deserializing blueprint xml '{0}': {1}", blueprintAsset.name, e.Message));
                        }
                    }
                    else
                    {
                        BinaryDeserializer binaryDeserializer = new BinaryDeserializer(blueprintStream);
                        subBlueprintManager = binaryDeserializer.Deserialize <BlueprintManager>();
                    }

                    if (subBlueprintManager != null)
                    {
                        blueprintManager.AddBlueprints(subBlueprintManager);
                    }
                }
                else
                {
                    Debug.LogError(string.Format("Blueprint asset is no text asset: {0}", blueprintObjectAsset.name));
                }
            }

            // Resolve parents.
            BlueprintUtils.ResolveParents(blueprintManager, blueprintManager);

            return(blueprintManager);
        }
Exemplo n.º 2
0
        public static void SetVector(BinaryDeserializer Deserializer, GfxFloatKeyFrameGroup[] Vector)
        {
            long Position = Deserializer.BaseStream.Position;

            uint Flags = GetFlagsFromElem(Deserializer, Position);

            uint ConstantMask = 1u;
            uint NotExistMask = 1u << Vector.Length;

            for (int Axis = 0; Axis < Vector.Length; Axis++)
            {
                Deserializer.BaseStream.Seek(Position, SeekOrigin.Begin);

                Position += 4;

                bool Constant = (Flags & ConstantMask) != 0;
                bool Exists   = (Flags & NotExistMask) == 0;

                if (Exists)
                {
                    Vector[Axis] = GfxFloatKeyFrameGroup.ReadGroup(Deserializer, Constant);
                }

                ConstantMask <<= 1;
                NotExistMask <<= 1;
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Encodes a BLOB reference.
        /// </summary>
        /// <param name="BlobReference">Binary BLOB reference.</param>
        /// <param name="BlobData">Original BLOB data.</param>
        /// <returns>Encoded BLOB reference.</returns>
        public byte[] EncodeBlobReference(byte[] BlobReference, byte[] BlobData)
        {
            BinaryDeserializer Reader = new BinaryDeserializer(this.collectionName, this.encoding, BlobReference, int.MaxValue);

            if (!Reader.ReadBit())
            {
                return(BlobReference);
            }

            string Key    = Reader.ReadString();
            int    KeyPos = Reader.Position;
            int    c      = BlobData.Length;

            int FullPayloadLen = c - KeyPos;

            BinarySerializer Writer = new BinarySerializer(this.collectionName, this.encoding);

            Writer.WriteBit(true);
            Writer.Write(Key);
            Writer.WriteBits(ObjectSerializer.TYPE_MAX, 6);
            Writer.WriteVariableLengthUInt64((uint)FullPayloadLen);
            Writer.WriteRaw(BlobReference, BlobReference.Length - 4, 4);

            return(Writer.GetSerialization());
        }
Exemplo n.º 4
0
        public static H3D Open(MemoryStream MS)
        {
            //Please note that data should be on Memory when opening because addresses are relocated.
            //Otherwise the original file would be corrupted!
            BinaryDeserializer Deserializer = new BinaryDeserializer(MS, GetSerializationOptions());

            H3DHeader Header = Deserializer.Deserialize <H3DHeader>();

            new H3DRelocator(MS, Header).ToAbsolute();

            H3D Scene = Deserializer.Deserialize <H3D>();

            Scene.BackwardCompatibility = Header.BackwardCompatibility;
            Scene.ForwardCompatibility  = Header.ForwardCompatibility;

            Scene.ConverterVersion = Header.ConverterVersion;

            Scene.Flags = Header.Flags;

            /*Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(Scene, Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonSerializerSettings()
             * {
             *  ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
             * }));*/

            Scene.SourceData.Add(Scene);
            return(Scene);
        }
        public void SimpleParentUserTestDeserializeBase(byte[] Result, SimpleParentUserInfo Value, BaseOptionInfo SerializerOptions)
        {
            //in this example server side has SimpleUserInfo
            //server side has Id, Name, Family
            //and the client side has SimpleUserOldStructureInfo
            //client side has Id, Age, BirthDate ,Name

            //new structure of models
            var newStructureModels = BinarySerializer.GetStructureModels(SerializerOptions);

            //my old deserializer
            var myDeserializer = new BinaryDeserializer();

            myDeserializer.Options = new BinaryGo.Helpers.BaseOptionInfo();

            #region VersionChangedControl
            //generate type
            myDeserializer.Options.GenerateType <SimpleParentUserOldStructureInfo>();
            //add model renamed
            myDeserializer.AddMovedType(myDeserializer.GetStrcutureModelName(typeof(SimpleParentUserInfo)), typeof(SimpleParentUserOldStructureInfo));
            //build new structure to old structure
            myDeserializer.BuildStructure(newStructureModels);
            #endregion

            var result = myDeserializer.Deserialize <SimpleParentUserOldStructureInfo>(Result);
            Assert.True(result.IsEquals(Value));

            //now serialize from client side and deserialize from server side happen
            result.Passport = "AV12345678";
            BinarySerializer binarySerializer = new BinarySerializer(myDeserializer.Options);
            var resultSerialized   = binarySerializer.Serialize(result);
            var resultDeserialized = myDeserializer.Deserialize <SimpleParentUserOldStructureInfo>(resultSerialized);
            Assert.True(resultDeserialized.IsEquals(Value));
        }
Exemplo n.º 6
0
 public BlockHeader(BinaryDeserializer Reader)
 {
     this.BytesUsed        = Reader.ReadUInt16();                // 0: Counts number of bytes used in block, excluding the node header, and the last block link (14 bytes in total).
     this.SizeSubtree      = Reader.ReadUInt32();                // 2: Order statistic tree, counting number of objects rooted at the current node.
     this.LastBlockIndex   = Reader.ReadBlockLink();             // 6: Last block link.
     this.ParentBlockIndex = Reader.ReadBlockLink();             // 10: Parent block link.
 }
Exemplo n.º 7
0
 public static void SkipHeader(BinaryDeserializer Reader)
 {
     Reader.SkipUInt16();
     Reader.SkipUInt32();
     Reader.SkipUInt32();
     Reader.SkipUInt32();
 }
Exemplo n.º 8
0
        private static object Make_YuzuTest__SampleMergeNonPrimitive(BinaryDeserializer d, ReaderClassDef def)
        {
            var result = new global::YuzuTest.SampleMergeNonPrimitive();

            Read_YuzuTest__SampleMergeNonPrimitive(d, def, result);
            return(result);
        }
Exemplo n.º 9
0
        public async Task GetIndexConfirmed_BinaryValueFound_ReturnsValue()
        {
            var input         = UInt160.Parse(RandomInt().ToString("X40"));
            var expectedBytes = new byte[1];
            var expectedSet   = new HashSet <CoinReference>
            {
                new CoinReference
                {
                    PrevHash  = UInt256.Parse(RandomInt().ToString("X64")),
                    PrevIndex = 0
                },
                new CoinReference
                {
                    PrevHash  = UInt256.Parse(RandomInt().ToString("X64")),
                    PrevIndex = 0
                }
            };
            var contextMock = AutoMockContainer.GetMock <IRedisDbContext>();

            contextMock.Setup(m => m.Get(input.BuildIxConfirmedKey())).ReturnsAsync(expectedBytes);
            var deserializerMock = AutoMockContainer.GetMock <IBinaryDeserializer>();

            deserializerMock.Setup(m => m.Deserialize <HashSet <CoinReference> >(expectedBytes, null))
            .Returns(expectedSet);
            var testee = AutoMockContainer.Create <RedisDbBinaryRepository>();

            BinaryDeserializer.Initialize(deserializerMock.Object);
            var result = await testee.GetIndexConfirmed(input);

            result.SetEquals(expectedSet).Should().BeTrue();
        }
Exemplo n.º 10
0
 /// <summary>
 ///   Reads this object from its binary representation.
 /// </summary>
 /// <param name="deserializer">Deserializer to read the object with.</param>
 public void Deserialize(BinaryDeserializer deserializer)
 {
     this.AdditionalComponentTypes =
         deserializer.Deserialize <string[]>().Select <string, Type>(ReflectionUtils.FindType).ToList();
     this.BlueprintId   = deserializer.Deserialize <string>();
     this.Configuration = deserializer.Deserialize <AttributeTable>();
 }
Exemplo n.º 11
0
        public void TestSimpleObject()
        {
            var serializer = new BinarySerializer();
            var obj        = Create();

            serializer.PrepareObjectGraph(obj);
            var result = serializer.SerializeObjectGraph();

            var deserializer = new BinaryDeserializer();
            var deserObj     = (BasicObject)deserializer.DeserializeObjectGraph(result);

            Assert.Equal(obj.TestIntZero, deserObj.TestIntZero);
            Assert.Equal(obj.TestStringContent, deserObj.TestStringContent);
            Assert.Equal(obj.TestStringNull, deserObj.TestStringNull);
            Assert.Equal(obj.TestIntMax, deserObj.TestIntMax);
            Assert.Equal(obj.TestIntMin, deserObj.TestIntMin);
            Assert.Equal(obj.TestDoubleMax, deserObj.TestDoubleMax);
            Assert.Equal(obj.TestDoubleMin, deserObj.TestDoubleMin);
            Assert.Equal(obj.TestDoubleNan, deserObj.TestDoubleNan);
            Assert.Equal(obj.TestDoubleZero, deserObj.TestDoubleZero);
            Assert.Equal(obj.TestBoolFalse, deserObj.TestBoolFalse);
            Assert.Equal(obj.TestBoolTrue, deserObj.TestBoolTrue);
            Assert.Equal(obj.TestLongMin, deserObj.TestLongMin);
            Assert.Equal(obj.TestLongMax, deserObj.TestLongMax);
            Assert.Equal(obj.TestULongMax, deserObj.TestULongMax);
            Assert.Equal(obj.TestUShortMin, deserObj.TestUShortMin);
            Assert.Equal(obj.TestShortMin, deserObj.TestShortMin);
            Assert.Equal(obj.TestFloatMax, deserObj.TestFloatMax);
            Assert.Equal(obj.TestDateTime, deserObj.TestDateTime);
            Assert.Equal(0, deserObj.TestSkipInt);
        }
Exemplo n.º 12
0
 private static void InitializeBinarySerializer(
     IBinarySerializer binarySerializer,
     IBinaryDeserializer binaryDeserializer)
 {
     BinarySerializer.Initialize(binarySerializer);
     BinaryDeserializer.Initialize(binaryDeserializer);
 }
        /// <summary>
        /// Deserializes an object from a binary source.
        /// </summary>
        /// <param name="Reader">Binary deserializer.</param>
        /// <param name="DataType">Optional datatype. If not provided, will be read from the binary source.</param>
        /// <param name="Embedded">If the object is embedded into another.</param>
        /// <returns>Deserialized object.</returns>
        public override object Deserialize(BinaryDeserializer Reader, uint?DataType, bool Embedded)
        {
            if (!DataType.HasValue)
            {
                DataType = Reader.ReadBits(6);
            }

            switch (DataType.Value)
            {
            case ObjectSerializer.TYPE_DATETIME: return((DateTimeOffset)Reader.ReadDateTime());

            case ObjectSerializer.TYPE_DATETIMEOFFSET: return(Reader.ReadDateTimeOffset());

            case ObjectSerializer.TYPE_STRING:
            case ObjectSerializer.TYPE_CI_STRING: return(DateTimeOffset.Parse(Reader.ReadString()));

            case ObjectSerializer.TYPE_MIN: return(DateTimeOffset.MinValue);

            case ObjectSerializer.TYPE_MAX: return(DateTimeOffset.MaxValue);

            case ObjectSerializer.TYPE_NULL: return(null);

            default: throw new Exception("Expected a DateTimeOffset value.");
            }
        }
Exemplo n.º 14
0
        public void RiskyFlySerialization()
        {
            var origin     = new DateTime(2017, 02, 07);
            var atms       = new double[] { 0.3, 0.32, 0.34 };
            var fwds       = new double[] { 100, 102, 110 };
            var maturities = new DateTime[] { new DateTime(2017, 04, 06), new DateTime(2017, 06, 07), new DateTime(2017, 08, 07) };
            var wingDeltas = new[] { 0.1, 0.25 };
            var riskies    = new[] { new[] { 0.025, 0.015 }, new[] { 0.025, 0.015 }, new[] { 0.025, 0.015 } };
            var flies      = new[] { new[] { 0.0025, 0.0015 }, new[] { 0.0025, 0.0015 }, new[] { 0.0025, 0.0015 } };
            var surface    = new RiskyFlySurface(
                origin, atms, maturities, wingDeltas, riskies, flies, fwds, WingQuoteType.Simple,
                AtmVolType.ZeroDeltaStraddle, Interpolator1DType.Linear,
                Interpolator1DType.LinearInVariance);

            Assert.Equal(atms[1], surface.GetVolForDeltaStrike(0.5, maturities[1], fwds[1]));

            var binSer = new BinarySerializer();

            binSer.PrepareObjectGraph(surface);
            var span = binSer.SerializeObjectGraph();

            var binDeser = new BinaryDeserializer();
            var surface2 = (ObjectWithLists)binDeser.DeserializeObjectGraph(span);

            Assert.Equal(atms[1], surface.GetVolForDeltaStrike(0.5, maturities[1], fwds[1]));
        }
Exemplo n.º 15
0
        private void LoadSettings(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog {
                DefaultExt = ".tgc", Filter = "Файлы настроек (*.tgc)|*.tgc|Все файлы (*.*)|*.*"
            };

            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var s = new BinaryDeserializer(ofd.FileName);

            if (!s.Open())
            {
                MessageBox.Show("Не удалось открыть файл"); return;
            }
            if (!_scene.Settings.Serialize(s))
            {
                MessageBox.Show("Не удалось загрузить настройки");
                s.Close();
                return;
            }
            s.Close();
            RefreshSettings();
        }
Exemplo n.º 16
0
        void ICustomSerialization.Deserialize(BinaryDeserializer Deserializer)
        {
            PICACommandReader Reader = new PICACommandReader(Commands);

            while (Reader.HasCommand)
            {
                PICACommand Cmd = Reader.GetCommand();

                uint Param = Cmd.Parameters[0];

                switch (Cmd.Register)
                {
                case PICARegister.GPUREG_TEXENV_UPDATE_BUFFER:
                    TextureEnvironments[1].Stage.UpdateColorBuffer = (Param & 0x100) != 0;
                    TextureEnvironments[2].Stage.UpdateColorBuffer = (Param & 0x200) != 0;
                    TextureEnvironments[3].Stage.UpdateColorBuffer = (Param & 0x400) != 0;
                    TextureEnvironments[4].Stage.UpdateColorBuffer = (Param & 0x800) != 0;

                    TextureEnvironments[1].Stage.UpdateAlphaBuffer = (Param & 0x1000) != 0;
                    TextureEnvironments[2].Stage.UpdateAlphaBuffer = (Param & 0x2000) != 0;
                    TextureEnvironments[3].Stage.UpdateAlphaBuffer = (Param & 0x4000) != 0;
                    TextureEnvironments[4].Stage.UpdateAlphaBuffer = (Param & 0x8000) != 0;
                    break;

                case PICARegister.GPUREG_TEXENV_BUFFER_COLOR: TexEnvBufferColor = new RGBA(Param); break;
                }
            }
        }
Exemplo n.º 17
0
        public static void SetVector(BinaryDeserializer Deserializer, H3DFloatKeyFrameGroup[] Vector)
        {
            uint Flags = Deserializer.Reader.ReadUInt32();

            long Position = Deserializer.BaseStream.Position;

            uint ConstantMask = (uint)H3DAnimVectorFlags.IsXConstant;
            uint NotExistMask = (uint)H3DAnimVectorFlags.IsXInexistent;

            for (int Axis = 0; Axis < Vector.Length; Axis++)
            {
                Deserializer.BaseStream.Seek(Position, SeekOrigin.Begin);

                Position += 4;

                bool Constant = (Flags & ConstantMask) != 0;
                bool Exists   = (Flags & NotExistMask) == 0;

                if (Exists)
                {
                    Vector[Axis] = H3DFloatKeyFrameGroup.ReadGroup(Deserializer, Constant);
                }

                ConstantMask <<= 1;
                NotExistMask <<= 1;
            }
        }
Exemplo n.º 18
0
        public static T ReadObject <T>(Stream stream, object obj = null)
        {
            var ms = new MemoryStream();

            stream.CopyTo(ms);
            ms.Seek(0, SeekOrigin.Begin);
            stream = ms;
            Yuzu.Deserializer.AbstractReaderDeserializer yd = null;
            if (CheckYuzuBinarySignature(stream))
            {
                yd = new BinaryDeserializer {
                    Options = defaultYuzuCommonOptions
                };
            }
            else
            {
                yd = new JsonDeserializer {
                    JsonOptions = defaultYuzuJSONOptions,
                    Options     = defaultYuzuCommonOptions
                };
            }
            var bd = yd as BinaryDeserializer;

            if (obj == null)
            {
                return((bd != null) ? bd.FromReader <T>(new BinaryReader(stream)) : yd.FromStream <T>(stream));
            }
            else
            {
                return((bd != null) ? (T)bd.FromReader(obj, new BinaryReader(stream)) : (T)yd.FromStream(obj, stream));
            }
        }
Exemplo n.º 19
0
        private List <AclTableEntry> ParseTableEntries(ArraySegment <byte> tableSegment)
        {
            List <AclTableEntry> result;

            using (BinaryDeserializer binaryDeserializer = new BinaryDeserializer(tableSegment))
            {
                List <AclTableEntry> list    = FolderSecurity.AclTableEntry.ParseTableEntries <AclTableEntry>(binaryDeserializer.Reader, new Func <BinaryReader, AclTableEntry>(AclTableEntry.Parse));
                HashSet <string>     hashSet = null;
                if (list != null)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        AclTableEntry aclTableEntry = list[i];
                        if (aclTableEntry.MemberEntryId != null && aclTableEntry.MemberEntryId.Length != 0)
                        {
                            if (hashSet == null)
                            {
                                hashSet = new HashSet <string>();
                            }
                            string text = AclHelper.LegacyDnFromEntryId(aclTableEntry.MemberEntryId);
                            if (!hashSet.Add(text.ToLower()))
                            {
                                return(null);
                            }
                        }
                        if (aclTableEntry.MemberId != 0L && aclTableEntry.MemberId != -1L)
                        {
                            aclTableEntry.SetMemberId(AclModifyTable.GetIdForSecurityIdentifier(aclTableEntry.SecurityIdentifier, null, this.coreFolder.AclTableIdMap));
                        }
                    }
                }
                result = list;
            }
            return(result);
        }
Exemplo n.º 20
0
        private async Task LoadObject()
        {
            byte[]             Key    = (byte[])this.e.CurrentObjectId;
            BinaryDeserializer Reader = new BinaryDeserializer(this.file.CollectionName, this.file.Encoding, Key);

            this.recordHandler.SkipKey(Reader, true);
            this.currentObjectId = this.recordHandler.ObjectId;

            try
            {
                if (this.currentSerializer == null)
                {
                    this.currentSerializer = this.provider.GetObjectSerializer(typeof(T));
                }

                this.current = (T)await this.file.ObjectFile.LoadObject(this.currentObjectId, this.currentSerializer);

                this.currentTypeCompatible = true;
            }
            catch (Exception)
            {
                this.current = default(T);
                this.currentTypeCompatible = false;
            }

            this.hasCurrent = true;
        }
Exemplo n.º 21
0
        void ICustomSerialization.Deserialize(BinaryDeserializer Deserializer)
        {
            PICACommandReader Reader = new PICACommandReader(Commands);

            while (Reader.HasCommand)
            {
                PICACommand Cmd = Reader.GetCommand();

                uint Param = Cmd.Parameters[0];

                switch (Cmd.Register)
                {
                case PICARegister.GPUREG_TEXENV0_SOURCE:
                case PICARegister.GPUREG_TEXENV1_SOURCE:
                case PICARegister.GPUREG_TEXENV2_SOURCE:
                case PICARegister.GPUREG_TEXENV3_SOURCE:
                case PICARegister.GPUREG_TEXENV4_SOURCE:
                case PICARegister.GPUREG_TEXENV5_SOURCE:
                    Stage.Source = new PICATexEnvSource(Param);
                    break;

                case PICARegister.GPUREG_TEXENV0_OPERAND:
                case PICARegister.GPUREG_TEXENV1_OPERAND:
                case PICARegister.GPUREG_TEXENV2_OPERAND:
                case PICARegister.GPUREG_TEXENV3_OPERAND:
                case PICARegister.GPUREG_TEXENV4_OPERAND:
                case PICARegister.GPUREG_TEXENV5_OPERAND:
                    Stage.Operand = new PICATexEnvOperand(Param);
                    break;

                case PICARegister.GPUREG_TEXENV0_COMBINER:
                case PICARegister.GPUREG_TEXENV1_COMBINER:
                case PICARegister.GPUREG_TEXENV2_COMBINER:
                case PICARegister.GPUREG_TEXENV3_COMBINER:
                case PICARegister.GPUREG_TEXENV4_COMBINER:
                case PICARegister.GPUREG_TEXENV5_COMBINER:
                    Stage.Combiner = new PICATexEnvCombiner(Param);
                    break;

                case PICARegister.GPUREG_TEXENV0_COLOR:
                case PICARegister.GPUREG_TEXENV1_COLOR:
                case PICARegister.GPUREG_TEXENV2_COLOR:
                case PICARegister.GPUREG_TEXENV3_COLOR:
                case PICARegister.GPUREG_TEXENV4_COLOR:
                case PICARegister.GPUREG_TEXENV5_COLOR:
                    Stage.Color = new RGBA(Param);
                    break;

                case PICARegister.GPUREG_TEXENV0_SCALE:
                case PICARegister.GPUREG_TEXENV1_SCALE:
                case PICARegister.GPUREG_TEXENV2_SCALE:
                case PICARegister.GPUREG_TEXENV3_SCALE:
                case PICARegister.GPUREG_TEXENV4_SCALE:
                case PICARegister.GPUREG_TEXENV5_SCALE:
                    Stage.Scale = new PICATexEnvScale(Param);
                    break;
                }
            }
        }
Exemplo n.º 22
0
        void ICustomSerialization.Deserialize(BinaryDeserializer Deserializer)
        {
            uint[] Addresses = new uint[3];

            uint ConstantMask = (uint)H3DAnimQuatTransformFlags.IsScaleConstant;
            uint NotExistMask = (uint)H3DAnimQuatTransformFlags.IsScaleInexistent;

            Addresses[0] = Deserializer.Reader.ReadUInt32();
            Addresses[1] = Deserializer.Reader.ReadUInt32();
            Addresses[2] = Deserializer.Reader.ReadUInt32();

            for (int ElemIndex = 0; ElemIndex < 3; ElemIndex++)
            {
                bool Constant = ((uint)Flags & ConstantMask) != 0;
                bool Exists   = ((uint)Flags & NotExistMask) == 0;

                if (Exists)
                {
                    Deserializer.BaseStream.Seek(Addresses[ElemIndex], SeekOrigin.Begin);

                    uint ElemFlags = 0;
                    uint Address   = Addresses[ElemIndex];
                    uint Count     = 1;

                    if (!Constant)
                    {
                        /*
                         * gdkchan Note:
                         * Those values have been verified and Start Frame will always be zero on observed BCHs.
                         * This may or may not change on future versions (probably not), so we can safely ignore it.
                         */
                        float StartFrame = Deserializer.Reader.ReadSingle();
                        float EndFrame   = Deserializer.Reader.ReadSingle();

                        ElemFlags = Deserializer.Reader.ReadUInt32();
                        Address   = Deserializer.Reader.ReadUInt32();
                        Count     = Deserializer.Reader.ReadUInt32();
                    }

                    Deserializer.BaseStream.Seek(Address, SeekOrigin.Begin);

                    for (int Index = 0; Index < Count; Index++)
                    {
                        switch (ElemIndex)
                        {
                        case 0: Scales.Add(Deserializer.Reader.ReadVector3());       break;

                        case 1: Rotations.Add(Deserializer.Reader.ReadQuaternion()); break;

                        case 2: Translations.Add(Deserializer.Reader.ReadVector3()); break;
                        }
                    }
                }

                ConstantMask >>= 1;
                NotExistMask >>= 1;
            }
        }
Exemplo n.º 23
0
        void ICustomSerialization.Deserialize(BinaryDeserializer Deserializer)
        {
            Deserializer.BaseStream.Seek(-0xc, SeekOrigin.Current);

            uint Flags = Deserializer.Reader.ReadUInt32();

            Deserializer.BaseStream.Seek(8, SeekOrigin.Current);

            uint[] Addresses = new uint[3];

            uint ConstantMask = (uint)GfxAnimQuatTransformFlags.IsScaleConstant;
            uint NotExistMask = (uint)GfxAnimQuatTransformFlags.IsScaleInexistent;

            Addresses[1] = Deserializer.ReadPointer();
            Addresses[2] = Deserializer.ReadPointer();
            Addresses[0] = Deserializer.ReadPointer();

            for (int ElemIndex = 0; ElemIndex < 3; ElemIndex++)
            {
                bool Constant = (Flags & ConstantMask) != 0;
                bool Exists   = (Flags & NotExistMask) == 0;

                if (Exists)
                {
                    Deserializer.BaseStream.Seek(Addresses[ElemIndex], SeekOrigin.Begin);

                    float StartFrame  = Deserializer.Reader.ReadSingle();
                    float EndFrame    = Deserializer.Reader.ReadSingle();
                    uint  CurveRelPtr = Deserializer.Reader.ReadUInt32();
                    bool  IsConstant  = Deserializer.Reader.ReadUInt32() != 0;

                    int Count = IsConstant ? 1 : (int)(EndFrame - StartFrame);

                    for (int Index = 0; Index < Count; Index++)
                    {
                        switch (ElemIndex)
                        {
                        case 0:
                            Scales.Add(Deserializer.Reader.ReadVector3());
                            break;

                        case 1:
                            Rotations.Add(Deserializer.Reader.ReadQuaternion());
                            break;

                        case 2:
                            Translations.Add(Deserializer.Reader.ReadVector3());
                            break;
                        }

                        uint SegmentFlags = Deserializer.Reader.ReadUInt32();
                    }
                }

                ConstantMask >>= 1;
                NotExistMask >>= 1;
            }
        }
Exemplo n.º 24
0
        void ICustomSerialization.Deserialize(BinaryDeserializer Deserializer)
        {
            if (Deserializer.FileVersion < 0x20)
            {
                /*
                 * Older version have a pointer within the curve data,
                 * instead of storing it directly. So we read it below...
                 */
                Deserializer.BaseStream.Seek(Deserializer.Reader.ReadUInt32(), SeekOrigin.Begin);

                //We don't need this since it's already stored on Curve
                float StartFrame = Deserializer.Reader.ReadSingle();
                float EndFrame   = Deserializer.Reader.ReadSingle();

                InterpolationType = (H3DInterpolationType)Deserializer.Reader.ReadByte();
                Quantization      = (KeyFrameQuantization)Deserializer.Reader.ReadByte();

                Count = Deserializer.Reader.ReadUInt16();

                InvDuration = Deserializer.Reader.ReadSingle();
                ValueScale  = Deserializer.Reader.ReadSingle();
                ValueOffset = Deserializer.Reader.ReadSingle();
                FrameScale  = Deserializer.Reader.ReadSingle();
            }

            Deserializer.BaseStream.Seek(Deserializer.Reader.ReadUInt32(), SeekOrigin.Begin);

            for (int Index = 0; Index < Count; Index++)
            {
                KeyFrame KF;

                switch (Quantization)
                {
                case KeyFrameQuantization.Hermite128:       KF = Deserializer.Reader.ReadHermite128();       break;

                case KeyFrameQuantization.Hermite64:        KF = Deserializer.Reader.ReadHermite64();        break;

                case KeyFrameQuantization.Hermite48:        KF = Deserializer.Reader.ReadHermite48();        break;

                case KeyFrameQuantization.UnifiedHermite96: KF = Deserializer.Reader.ReadUnifiedHermite96(); break;

                case KeyFrameQuantization.UnifiedHermite48: KF = Deserializer.Reader.ReadUnifiedHermite48(); break;

                case KeyFrameQuantization.UnifiedHermite32: KF = Deserializer.Reader.ReadUnifiedHermite32(); break;

                case KeyFrameQuantization.StepLinear64:     KF = Deserializer.Reader.ReadStepLinear64();     break;

                case KeyFrameQuantization.StepLinear32:     KF = Deserializer.Reader.ReadStepLinear32();     break;

                default: throw new InvalidOperationException($"Invalid Segment quantization {Quantization}!");
                }

                KF.Frame = KF.Frame * FrameScale;
                KF.Value = KF.Value * ValueScale + ValueOffset;

                KeyFrames.Add(KF);
            }
        }
Exemplo n.º 25
0
        public void TestBinaryReadObject()
        {
            var bd = new BinaryDeserializer();

            binaryStream.Position = 0;
            var p = bd.FromStream(binaryStream);

            Assert.AreEqual(person.Name, ((SamplePerson)p).Name);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Deserializes an object from a binary source.
        /// </summary>
        /// <param name="Reader">Binary deserializer.</param>
        /// <param name="DataType">Optional datatype. If not provided, will be read from the binary source.</param>
        /// <param name="Embedded">If the object is embedded into another.</param>
        /// <returns>Deserialized object.</returns>
        public override object Deserialize(BinaryDeserializer Reader, uint?DataType, bool Embedded)
        {
            if (!DataType.HasValue)
            {
                DataType = Reader.ReadBits(6);
            }

            return(ReadArray <T>(this.provider, Reader, DataType.Value));
        }
Exemplo n.º 27
0
        /// <summary>
        ///   Reads this object from its binary representation.
        /// </summary>
        /// <param name="deserializer">Deserializer to read the object with.</param>
        public void Deserialize(BinaryDeserializer deserializer)
        {
            Dictionary <object, object> attributeTable = deserializer.Deserialize <Dictionary <object, object> >();

            foreach (KeyValuePair <object, object> keyValuePair in attributeTable)
            {
                this.attributes[keyValuePair.Key] = keyValuePair.Value;
            }
        }
Exemplo n.º 28
0
        public ILoadEntityDatabasePipeline CreateDefaultLoadPipeline(IDependencyContainer container)
        {
            var mappingRegistry        = new MappingRegistry(container.Resolve <EverythingTypeMapper>());
            var typeCreator            = container.Resolve <ITypeCreator>();
            var primitiveTypeMappings  = container.ResolveAll <IBinaryPrimitiveHandler>();
            var everythingDeserializer = new BinaryDeserializer(mappingRegistry, typeCreator, primitiveTypeMappings);

            return(CreateLoadPipeline(container, everythingDeserializer, DefaultEntityDatabaseFile));
        }
Exemplo n.º 29
0
        public static DATA FromBytes <DATA>(byte[] Source) where DATA : class, IData, new()
        {
            GameObject  Load          = Resource.LoadPrefabInstance("Group");
            DataWrapper LoadComponent = Load.AddComponent <DataWrapper>();

            BinaryDeserializer.LoadComponentContentsFromBytes(LoadComponent, null, Source);

            return(LoadComponent.Data as DATA);
        }
Exemplo n.º 30
0
        public void TestBinaryRead()
        {
            var          bd = new BinaryDeserializer();
            SamplePerson p  = new SamplePerson();

            binaryStream.Position = 0;
            bd.FromStream(p, binaryStream);
            Assert.AreEqual(person.Name, p.Name);
        }
Exemplo n.º 31
0
        public void TestJsonToBinaryUnknown()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();
            var js = new JsonSerializer();
            js.JsonOptions.FieldSeparator = "";
            js.JsonOptions.Indent = "";
            js.JsonOptions.SaveRootClass = true;
            var jd = new JsonDeserializer();

            var data1 = "{\"class\":\"NewType\",\"X\":\"abc\"}";
            var result1 = js.ToString(bd.FromBytes(bs.ToBytes(jd.FromString(data1))));
            Assert.AreEqual(data1, result1);
        }
Exemplo n.º 32
0
        public void TestAllowReadingFromAncestor()
        {
            var bs = new BinarySerializer();
            var v1 = new Sample2 { X = 83, Y = "83" };
            var result1 = bs.ToBytes(v1);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(Sample2)) + " 02 00 " + XS("X", RoughType.Int, "Y", RoughType.String) +
                " 01 00 53 00 00 00 00 00", XS(result1));

            var w1 = new Sample2Allow();
            var bd = new BinaryDeserializer();
            bd.FromBytes(w1, result1);
            Assert.AreEqual(v1.X, w1.X);
        }
Exemplo n.º 33
0
        public void TestBinaryToJsonUnknown()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();
            var js = new JsonSerializer();
            js.JsonOptions.SaveRootClass = true;
            var jd = new JsonDeserializer();

            var n = "NewType".ToCharArray().Select(ch => (byte)ch).ToList();
            var data1 =
                new byte[] { 0x20, 0x01, 0x00, (byte)n.Count }.Concat(n).
                Concat(new byte[] { 0x01, 0x00, 0x01, (byte)'X', (byte)RoughType.String, 0x01, 0x00,
                    0x03, (byte)'a', (byte)'b', (byte)'c', 0, 0
                }).ToArray();
            var result1 = bs.ToBytes(jd.FromString(js.ToString(bd.FromBytes(data1))));
            CollectionAssert.AreEqual(data1, result1);
        }
Exemplo n.º 34
0
        public void TestAbstract()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();

            SampleAbstract v1 = new SampleConcrete { XX = 81 };
            var result1 = bs.ToBytes(v1);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleConcrete)) + " 01 00 " + XS("XX", RoughType.Int) +
                " 01 00 51 00 00 00 00 00", XS(result1));

            var w1 = bd.FromBytes<SampleAbstract>(result1);
            Assert.AreEqual((v1 as SampleConcrete).XX, (w1 as SampleConcrete).XX);
            var w1g = (SampleConcrete)(new BinaryDeserializerGen().FromBytes(result1));
            Assert.AreEqual((v1 as SampleConcrete).XX, w1g.XX);

            var v2 = new List<SampleAbstract>();
            v2.Add(new SampleConcrete { XX = 51 });

            var w2 = bd.FromBytes<List<SampleAbstract>>(bs.ToBytes(v2));
            Assert.AreEqual(v2.Count, w2.Count);
            Assert.AreEqual((v2[0] as SampleConcrete).XX, (w2[0] as SampleConcrete).XX);
        }
Exemplo n.º 35
0
        public void TestCollection()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();

            var v0 = new SampleWithCollection();
            v0.A.Add(new SampleInterfaced { X = 9 });
            v0.B.Add(7);
            v0.B.Add(6);
            var result0 = bs.ToBytes(v0);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleWithCollection)) + " 02 00 " +
                XS("A", RoughType.Sequence) + " " + XS(RoughType.Record) + " " +
                XS("B", RoughType.Sequence) + " " + XS(RoughType.Int) +
                " 01 00 01 00 00 00 02 00 " + XS(typeof(SampleInterfaced)) +
                " 01 00 " + XS("X", RoughType.Int) +
                " 01 00 09 00 00 00 00 00" +
                " 02 00 02 00 00 00 07 00 00 00 06 00 00 00 00 00",
                XS(result0));

            var w0 = new SampleWithCollection();
            bd.FromBytes(w0, result0);
            Assert.AreEqual(1, w0.A.Count);
            Assert.IsInstanceOfType(w0.A.First(), typeof(SampleInterfaced));
            Assert.AreEqual(9, w0.A.First().X);
            CollectionAssert.AreEqual(new int[] { 7, 6 }, w0.B.ToList());

            var w1 = (SampleWithCollection)((new BinaryDeserializerGen()).FromBytes(result0));
            Assert.AreEqual(1, w1.A.Count);
            Assert.IsInstanceOfType(w1.A.First(), typeof(SampleInterfaced));
            Assert.AreEqual(9, w1.A.First().X);
            CollectionAssert.AreEqual(new int[] { 7, 6 }, w1.B.ToList());

            var v2 = new SampleConcreteCollection { 2, 5, 4 };
            var result1 = bs.ToBytes(v2);
            Assert.AreEqual("21 05 03 00 00 00 02 00 00 00 05 00 00 00 04 00 00 00", XS(result1));
            SampleConcreteCollection w2 = new SampleConcreteCollection();
            bd.FromBytes(w2, result1);
            CollectionAssert.AreEqual(v2.ToList(), w2.ToList());
        }
Exemplo n.º 36
0
        public void TestFloat()
        {
            var bs = new BinarySerializer();
            bs.Options.TagMode = TagMode.Names;

            var v = new SampleFloat { F = 1e-20f, D = -3.1415e100d };

            var result1 = bs.ToBytes(v);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleFloat)) + " 02 00 " +
                XS("F", RoughType.Float, "D", RoughType.Double) +
                " 01 00 08 E5 3C 1E 02 00 CA DC 09 3E BE B9 CC D4 00 00",
                XS(result1));

            var w = new SampleFloat();
            var bd = new BinaryDeserializer();
            bd.Options.TagMode = TagMode.Names;
            bd.FromBytes(w, result1);
            Assert.AreEqual(v.F, w.F);
            Assert.AreEqual(v.D, w.D);
        }
Exemplo n.º 37
0
        public void TestStruct()
        {
            var v = new SampleRect {
                A = new SamplePoint { X = 33, Y = 44 },
                B = new SamplePoint { X = 55, Y = 66 },
            };
            var bs = new BinarySerializer();
            var result = bs.ToBytes(v);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleRect)) + " 02 00 " +
                XS("A", RoughType.Record, "B", RoughType.Record) +
            " 01 00 02 00 " + XS(typeof(SamplePoint)) + " 02 00 " +
            XS("X", RoughType.Int, "Y", RoughType.Int) +
            " 21 00 00 00 2C 00 00 00 " +
            "02 00 02 00 37 00 00 00 42 00 00 00 00 00",
            XS(result));

            var bd = new BinaryDeserializer();
            var w = new SampleRect();
            bd.FromBytes(w, result);
            CheckSampleRect(v, w);

            var bdg = new BinaryDeserializerGen();
            w = (SampleRect)bdg.FromBytes(result);
            CheckSampleRect(v, w);

            var p = (SamplePoint)bdg.FromBytes(new SamplePoint(), SX("20 02 00 22 00 00 00 2D 00 00 00"));
            Assert.AreEqual(34, p.X);
            Assert.AreEqual(45, p.Y);
        }
Exemplo n.º 38
0
        public void Load(string path)
        {
            FileInfo file = new FileInfo(path);

            if (!file.Exists)
            {
                this.editorSettings.RecentProjects.Remove(path);
                this.SaveEditorSettings();

                throw new FileNotFoundException(string.Format("Project file not found: {0}", path), path);
            }

            // Load project.
            FileStream fileStream = new FileStream(path, FileMode.Open);
            ProjectSettings newProjectSettings = (ProjectSettings)this.projectSettingsSerializer.Deserialize(fileStream);
            if (newProjectSettings == null)
            {
                throw new SerializationException(
                    string.Format("Couldn't deserialize project settings from '{0}'.", path));
            }

            fileStream.Close();

            // Convert file paths.
            newProjectSettings.ProjectAssemblies =
                newProjectSettings.ProjectAssembliesSerialized.Select(
                    assemblyPath =>
                    ReflectionUtils.FindAssembly(string.Format("{0}\\{1}", Path.GetDirectoryName(path), assemblyPath)))
                                  .ToList();

            newProjectSettings.LanguageFiles =
                newProjectSettings.LanguageFilesSerialized.Select(
                    languageFilePath =>
                    new LanguageFile
                        {
                            Path =
                                new FileInfo(string.Format("{0}\\{1}", Path.GetDirectoryName(path), languageFilePath))
                        .FullName
                        }).ToList();

            for (int i = 0; i < newProjectSettings.LanguageFiles.Count; i++)
            {
                newProjectSettings.LanguageFiles[i].LanguageTag = newProjectSettings.LanguageNamesSerialized[i];
            }

            // Load blueprint files.
            foreach (var blueprintFile in newProjectSettings.BlueprintFiles)
            {
                var blueprintFileName = this.ReadBlueprintsAsBinary
                                            ? Path.ChangeExtension(blueprintFile.Path, "bytes")
                                            : blueprintFile.Path;

                var absoluteBlueprintFilePath = string.Format(
                    "{0}\\{1}", Path.GetDirectoryName(path), blueprintFileName);

                var fileInfo = new FileInfo(absoluteBlueprintFilePath);

                if (!fileInfo.Exists)
                {
                    throw new FileNotFoundException(string.Format("Blueprint file not found: {0}.", blueprintFileName));
                }

                using (var blueprintFileStream = fileInfo.OpenRead())
                {
                    try
                    {
                        BlueprintManager newBlueprintManager;

                        if (this.ReadBlueprintsAsBinary)
                        {
                            var binaryDeserializer = new BinaryDeserializer(blueprintFileStream);
                            newBlueprintManager = binaryDeserializer.Deserialize<BlueprintManager>();
                        }
                        else
                        {
                            newBlueprintManager =
                                (BlueprintManager)this.blueprintManagerSerializer.Deserialize(blueprintFileStream);
                        }

                        if (newBlueprintManager == null)
                        {
                            throw new SerializationException(
                                string.Format("Couldn't deserialize blueprint manager from '{0}'.", path));
                        }

                        blueprintFile.BlueprintManager = newBlueprintManager;
                    }
                    catch (Exception e)
                    {
                        throw new SerializationException(
                            string.Format(
                                "Couldn't deserialize blueprint manager from '{0}': {1}.",
                                path,
                                e.GetBaseException().Message),
                            e);
                    }
                }
            }

            // Set new project.
            this.SetProject(newProjectSettings, path);

            // Save to recent projects.
            this.editorSettings.AddRecentProject(path);
            this.SaveEditorSettings();
        }
Exemplo n.º 39
0
        public void TestTopLevelList()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();

            var v0 = new List<string> { "a", "b", "c" };
            var result0 = bs.ToBytes(v0);
            Assert.AreEqual("21 10 03 00 00 00 " + XS("a", "b", "c"), XS(result0));

            var w0 = new List<string>();
            bd.FromBytes(w0, result0);
            CollectionAssert.AreEqual(v0, w0);
            bd.FromBytes(w0, new byte[] { 0x21, 0x10, 0, 0, 0, 0 });
            CollectionAssert.AreEqual(v0, w0);
            bd.FromBytes(w0, result0);
            CollectionAssert.AreEqual(new List<string> { "a", "b", "c", "a", "b", "c" }, w0);
        }
Exemplo n.º 40
0
 /// <summary>
 ///   Reads this object from its binary representation.
 /// </summary>
 /// <param name="deserializer">Deserializer to read the object with.</param>
 public void Deserialize(BinaryDeserializer deserializer)
 {
     this.AttributeTableSerialized = deserializer.Deserialize<AttributeTable>();
     this.ComponentTypesSerialized = deserializer.Deserialize<string[]>();
     this.ParentId = deserializer.Deserialize<string>();
 }
Exemplo n.º 41
0
        public void TestUnknownStorage()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();
            bd.Options.AllowUnknownFields = true;

            var data =
                "20 01 00 " + XS(typeof(SampleUnknown)) + " 03 00 " +
                XS("A", RoughType.String, "X", RoughType.Int, "Z", RoughType.Bool) +
                " 01 00 " + XS("qq") + " 02 00 02 01 00 00 03 00 01 00 00";
            var w = new SampleUnknown();
            bd.FromBytes(w, SX(data));
            Assert.AreEqual(258, w.X);
            Assert.AreEqual(2, w.Storage.Fields.Count);
            Assert.AreEqual("A", w.Storage.Fields[0].Name);
            Assert.AreEqual("qq", w.Storage.Fields[0].Value);
            Assert.AreEqual("Z", w.Storage.Fields[1].Name);
            Assert.AreEqual(true, w.Storage.Fields[1].Value);

            Assert.AreEqual(data, XS(bs.ToBytes(w)));

            bd.FromBytes(w, SX("20 01 00 00 00"));
            Assert.AreEqual(0, w.Storage.Fields.Count);

            Assert.AreEqual("20 01 00 00 00", XS(bs.ToBytes(new SampleUnknown())));

            bd.ClearClassIds();
            bs.ClearClassIds();
            bd.FromBytes(w, SX(
                "20 01 00 " + XS(typeof(SampleUnknown)) + " 02 00 " +
                XS("A", RoughType.String, "Z", RoughType.Bool) +
                " 01 00 " + XS("tt") + " 02 00 01 00 00"));
            Assert.AreEqual(2, w.Storage.Fields.Count);
            Assert.AreEqual("A", w.Storage.Fields[0].Name);
            Assert.AreEqual("tt", w.Storage.Fields[0].Value);
            Assert.AreEqual("Z", w.Storage.Fields[1].Name);
            Assert.AreEqual(true, w.Storage.Fields[1].Value);
            Assert.AreEqual(258, w.X);

            w.X = 0;
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleUnknown)) + " 03 00 " +
                XS("A", RoughType.String, "X", RoughType.Int, "Z", RoughType.Bool) +
                " 01 00 " + XS("tt") + " 03 00 01 00 00",
                XS(bs.ToBytes(w)));

            bs.ClearClassIds();
            bs.ToBytes(new SampleUnknown());
            XAssert.Throws<YuzuException>(() => bs.ToBytes(w), "SampleUnknown");

            bs.ClearClassIds();
            bd.ClearClassIds();
            var data2 =
                "20 01 00 " + XS(typeof(SampleUnknown)) + " 02 00 " +
                XS("A", RoughType.Record, "X", RoughType.Int) +
                " 01 00 02 00 " + XS("NewType") + " 01 00 " + XS("Fld", RoughType.SByte) +
                " 01 00 FE 00 00 02 00 14 00 00 00 00 00";
            var w2 = bd.FromBytes<SampleUnknown>(SX(data2));
            Assert.AreEqual(1, w2.Storage.Fields.Count);
            Assert.AreEqual("A", w2.Storage.Fields[0].Name);
            var u2 = (YuzuUnknown)w2.Storage.Fields[0].Value;
            Assert.AreEqual("NewType", u2.ClassTag);
            Assert.AreEqual(1, u2.Fields.Count);
            Assert.AreEqual((sbyte)-2, u2.Fields["Fld"]);
            Assert.AreEqual(20, w2.X);

            Assert.AreEqual("\n" + data2, "\n" + XS(bs.ToBytes(w2)));
        }
Exemplo n.º 42
0
        public void TestNewFields()
        {
            var bd = new BinaryDeserializer();
            bd.Options.TagMode = TagMode.Aliases;
            bd.Options.AllowUnknownFields = true;

            var w = new SampleTree();
            bd.FromBytes(w, SX(
                "20 01 00 " + XS(typeof(SampleTree)) + " 03 00 " +
                XS("a", RoughType.Int, "a1", RoughType.Sequence) + " 10 " +
                XS("b", RoughType.Sequence) +
                " 20 01 00 09 00 00 00 02 00 00 00 00 00 03 00 FF FF FF FF 00 00"));
            Assert.AreEqual(9, w.Value);
            Assert.AreEqual(null, w.Children);

            bd.ClearClassIds();

            bd.FromBytes(w, SX(
                "20 01 00 " + XS(typeof(SampleTree)) + " 04 00 " +
                XS("a", RoughType.Int, "a1", RoughType.Byte) + " " +
                XS("b", RoughType.Sequence) + " 20 " + XS("x", RoughType.Record) +
                " 01 00 0A 00 00 00 02 00 00 04 00 00 00 00 00"));
            Assert.AreEqual(10, w.Value);

            bd.FromBytes(w, SX(
                "20 01 00 01 00 0B 00 00 00 00 00"));
            Assert.AreEqual(11, w.Value);
        }
Exemplo n.º 43
0
        public void TestNested()
        {
            var bs = new BinarySerializer();
            bs.Options.TagMode = TagMode.Names;

            var v = new Sample3 {
                S1 = new Sample1 { X = 345, Y = "test" },
                F = 222,
                S2 = new Sample2 { X = -346, Y = "test1" },
            };

            var result = bs.ToBytes(v);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(Sample3)) + " 03 00 " +
                XS("S1", RoughType.Record, "F", RoughType.Int, "S2", RoughType.Record) +
                " 01 00 02 00 " + XS(typeof(Sample1)) +
                " 02 00 " + XS("X", RoughType.Int, "Y", RoughType.String) +
                " 01 00 59 01 00 00 02 00 " + XS("test") + " 00 00 " +
                "02 00 DE 00 00 00 " +
                "03 00 03 00 " + XS(typeof(Sample2)) +
                " 02 00 " + XS("X", RoughType.Int, "Y", RoughType.String) +
                " 01 00 A6 FE FF FF 02 00 " + XS("test1") + " 00 00 00 00",
                XS(result));

            var bd = new BinaryDeserializer();
            bd.Options.TagMode = TagMode.Names;
            var w = new Sample3();
            bd.FromBytes(w, result);
            Assert.AreEqual(v.S1.X, w.S1.X);
            Assert.AreEqual(v.S1.Y, w.S1.Y);
            Assert.AreEqual(v.F, w.F);
            Assert.AreEqual(v.S2.X, w.S2.X);
            Assert.AreEqual(v.S2.Y, w.S2.Y);
        }
Exemplo n.º 44
0
        public void TestArray()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();
            var bdg = new BinaryDeserializerGen();

            var v0 = new SampleArray { A = new string[] { "a", "b", "c" } };
            var result0 = bs.ToBytes(v0);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleArray)) + " 01 00 " + XS("A", RoughType.Sequence) +
                " 10 01 00 03 00 00 00 " + XS("a", "b", "c") + " 00 00",
                XS(result0));
            var w0 = new SampleArray();
            bd.FromBytes(w0, result0);
            CollectionAssert.AreEqual(v0.A, w0.A);
            var w0g = (SampleArray)bdg.FromBytes(result0);
            CollectionAssert.AreEqual(v0.A, w0g.A);

            var v2 = new SampleArray();
            var result2 = bs.ToBytes(v2);
            Assert.AreEqual("20 01 00 01 00 FF FF FF FF 00 00", XS(result2));
            var w2 = new SampleArray();
            bd.FromBytes(w2, result2);
            CollectionAssert.AreEqual(v2.A, w2.A);
            var w2g = (SampleArray)bdg.FromBytes(result2);
            CollectionAssert.AreEqual(v2.A, w2g.A);
        }
Exemplo n.º 45
0
        public void TestMemberOfInterface()
        {
            var bs = new BinarySerializer();

            var v1 = new List<ISampleMember>();
            var result1 = bs.ToBytes(v1);
            Assert.AreEqual("21 20 00 00 00 00", XS(result1));

            var bd = new BinaryDeserializer();
            var w1 = new List<ISampleMember>();
            bd.FromBytes(w1, result1);
            Assert.AreEqual(0, w1.Count);

            v1.Add(new SampleMemberI());
            var result2 = bs.ToBytes(v1);
            Assert.AreEqual(
                "21 20 01 00 00 00 01 00 " +
                XS(typeof(SampleMemberI)) + " 01 00 " + XS("X", RoughType.Int) + " 00 00",
                XS(result2));
            bd.FromBytes(w1, result2);
            Assert.AreEqual(71, w1[0].X);

            Assert.AreEqual("21 20 00 00 00 00", XS(bs.ToBytes(new List<SampleMemberAbstract>())));

            var v3 = new List<SampleMemberAbstract> { new SampleMemberConcrete() };
            var result3 = bs.ToBytes(v3);
            Assert.AreEqual(
                "21 20 01 00 00 00 02 00 " +
                XS(typeof(SampleMemberConcrete)) + " 01 00 " + XS("X", RoughType.Int) + " 00 00",
                XS(result3));
            var w3 = new List<SampleMemberAbstract>();
            bd.FromBytes(w3, result3);
            Assert.AreEqual(72, w3[0].X);
        }
Exemplo n.º 46
0
        public void TestLong()
        {
            var bs = new BinarySerializer();
            var v1 = new SampleLong { S = -1L << 33, U = 1UL << 33 };

            var result = bs.ToBytes(v1);
            Assert.AreEqual(
                XS(RoughType.Record) + " 01 00 " + XS(typeof(SampleLong)) + " 02 00 " +
                XS("S", RoughType.Long, "U", RoughType.ULong) +
                " 01 00 00 00 00 00 FE FF FF FF 02 00 00 00 00 00 02 00 00 00 00 00", XS(result));

            var v2 = new SampleLong();
            var bd = new BinaryDeserializer();
            bd.FromBytes(v2, result);
            Assert.AreEqual(v1.S, v2.S);
            Assert.AreEqual(v1.U, v2.U);

            v1.S = long.MinValue;
            v1.U = ulong.MaxValue;
            bd.FromBytes(v2, bs.ToBytes(v1));
            Assert.AreEqual(v1.S, v2.S);
            Assert.AreEqual(v1.U, v2.U);
        }
Exemplo n.º 47
0
        public void TestList()
        {
            var bs = new BinarySerializer();
            bs.Options.TagMode = TagMode.Names;
            var bd = new BinaryDeserializer();
            bd.Options.TagMode = TagMode.Names;

            var v0 = new SampleList { E = new List<string> { "a", "b", "c" } };
            var result0 = bs.ToBytes(v0);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleList)) + " 01 00 " +
                XS("E", RoughType.Sequence) + " " + XS(RoughType.String) +
                " 01 00 03 00 00 00 " + XS("a", "b", "c") + " 00 00",
                XS(result0));
            var w0 = new SampleList();
            bd.FromBytes(w0, result0);
            CollectionAssert.AreEqual(v0.E, w0.E);

            var v1 = new SampleTree { Value = 11, Children = new List<SampleTree>() };
            var result1 = bs.ToBytes(v1);
            Assert.AreEqual(
                "20 02 00 " + XS(typeof(SampleTree)) + " 02 00 " +
                XS("Value", RoughType.Int, "Children", RoughType.Sequence) + " " + XS(RoughType.Record) +
                " 01 00 0B 00 00 00 02 00 00 00 00 00 00 00",
                XS(result1));
            Assert.AreEqual("20 02 00 01 00 0B 00 00 00 02 00 00 00 00 00 00 00", XS(bs.ToBytes(v1)));
            var w1 = new SampleTree();
            bd.FromBytes(w1, result1);
            Assert.AreEqual(0, w1.Children.Count);

            var v2 = new SampleTree {
                Value = 11,
                Children = new List<SampleTree> {
                    new SampleTree {
                        Value = 12,
                        Children = new List<SampleTree>(),
                    },
                    new SampleTree {
                        Value = 13,
                    }
                }
            };
            var result2 = bs.ToBytes(v2);
            Assert.AreEqual(
                "20 02 00 01 00 0B 00 00 00 02 00 02 00 00 00 " +
                "02 00 01 00 0C 00 00 00 02 00 00 00 00 00 00 00 " +
                "02 00 01 00 0D 00 00 00 02 00 FF FF FF FF 00 00 00 00",
                XS(result2));
            SampleTree w2 = new SampleTree();
            bd.FromBytes(w2, result2);
            Assert.AreEqual(v2.Value, w2.Value);
            Assert.AreEqual(v2.Children.Count, w2.Children.Count);
            Assert.AreEqual(v2.Children[0].Value, w2.Children[0].Value);
            Assert.AreEqual(v2.Children[1].Children, w2.Children[1].Children);

            Assert.AreEqual(
                "20 03 00 " + XS(typeof(SampleEmptyList)) + " 01 00 " +
                XS("E", RoughType.Sequence) + " " + XS(RoughType.String) + " 00 00",
                XS(bs.ToBytes(new SampleEmptyList())));
            Assert.AreEqual(
                "20 03 00 01 00 FF FF FF FF 00 00",
                XS(bs.ToBytes(new SampleEmptyList { E = null })));
        }
Exemplo n.º 48
0
        public void TestClassNames()
        {
            var bs = new BinarySerializer();
            bs.Options.TagMode = TagMode.Names;
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleBase)) + " 01 00 " + XS("FBase", RoughType.Int) +
                " 01 00 00 00 00 00 00 00",
                XS(bs.ToBytes(new SampleBase())));
            Assert.AreEqual(
                "20 02 00 " + XS(typeof(SampleDerivedA)) + " 02 00 " +
                XS("FBase", RoughType.Int, "FA", RoughType.Int) +
                " 01 00 00 00 00 00 02 00 00 00 00 00 00 00",
                XS(bs.ToBytes(new SampleDerivedA())));

            var bd = new BinaryDeserializer();
            bd.Options.TagMode = TagMode.Names;
            var v = bd.FromBytes(SX(
                "20 01 00 " + XS(typeof(SampleDerivedB)) + " 02 00 " +
                XS("FBase", RoughType.Int, "FB", RoughType.Int) +
                " 01 00 03 00 00 00 02 00 07 00 00 00 00 00"));
            Assert.IsInstanceOfType(v, typeof(SampleDerivedB));
            var b = (SampleDerivedB)v;
            Assert.AreEqual(3, b.FBase);
            Assert.AreEqual(7, b.FB);
        }
Exemplo n.º 49
0
        public void TestBool()
        {
            var bs = new BinarySerializer();

            var v = new SampleBool { B = true };

            var result1 = bs.ToBytes(v);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleBool)) +
                " 01 00 " + XS("B", RoughType.Bool) + " 01 00 01 00 00",
                XS(result1));

            var bd = new BinaryDeserializer();
            var w = new SampleBool();
            bd.FromBytes(w, result1);
            Assert.AreEqual(true, w.B);
        }
Exemplo n.º 50
0
        public void TestEscape()
        {
            var bs = new BinarySerializer();

            var s = "\"/{\u0001}\n\t\"\"";
            var v = new Sample1 { Y = s };
            var result = bs.ToBytes(v);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(Sample1)) + " 02 00 " +
                XS("X", RoughType.Int, "Y", RoughType.String) +
                " 01 00 00 00 00 00 02 00 " + XS(s) + " 00 00",
                XS(result));

            var w = new Sample1();
            var bd = new BinaryDeserializer();
            bd.FromBytes(w, result);
            Assert.AreEqual(s, w.Y);

            v.Y = "привет";
            var result2 = bs.ToBytes(v);
            Assert.AreEqual(
                "20 01 00 01 00 00 00 00 00 02 00 0C " +
                XS(Encoding.UTF8.GetBytes("привет")) + " 00 00",
                XS(result2));
            bd.FromBytes(w, result2);
            Assert.AreEqual(v.Y, w.Y);

            var ms = new MemoryStream(result2.Length);
            ms.Write(result2, 0, result2.Length);
            ms.Position = 0;
            bd.FromReader(w, new UnsafeBinaryReader(ms));
            Assert.AreEqual(v.Y, w.Y);
        }
Exemplo n.º 51
0
        public void TestUnknown()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();
            var data1 = SX(
                "20 01 00 " + XS("NewType1") + " 02 00 " + XS("a", RoughType.Int, "b", RoughType.String) +
                " 01 00 07 07 00 00 00 00");
            var w1 = (YuzuUnknown)bd.FromBytes<object>(data1);
            Assert.AreEqual("NewType1", w1.ClassTag);
            Assert.AreEqual(1, w1.Fields.Count);
            Assert.AreEqual(7*256 + 7, w1.Fields["a"]);
            CollectionAssert.AreEqual(data1, bs.ToBytes(w1));

            var data2 = SX("20 01 00 02 00 " + XS("qwe") + " 00 00");
            var w2 = (YuzuUnknown)bd.FromBytes(data2);
            Assert.AreEqual("NewType1", w2.ClassTag);
            Assert.AreEqual(1, w2.Fields.Count);
            Assert.AreEqual("qwe", w2.Fields["b"]);
            CollectionAssert.AreEqual(data2, bs.ToBytes(w2));

            var data3 = SX(
                "20 02 00 " + XS(typeof(SampleBool)) + " 02 00 " + XS("B", RoughType.Bool, "a", RoughType.Record) +
                " 01 00 01 02 00 03 00 " + XS("NewType2") + " 00 00 00 00 00 00");
            bd.Options.AllowUnknownFields = true;
            var w3 = bd.FromBytes<SampleBool>(data3);
            Assert.AreEqual(true, w3.B);
        }
Exemplo n.º 52
0
        public void TestDictionary()
        {
            var bs = new BinarySerializer();
            bs.Options.TagMode = TagMode.Names;
            var bd = new BinaryDeserializer();
            bd.Options.TagMode = TagMode.Names;
            var bdg = new BinaryDeserializer();
            bdg.Options.TagMode = TagMode.Names;

            var v0 = new SampleDict {
                Value = 3, Children = new Dictionary<string, SampleDict> {
                { "a", new SampleDict { Value = 5, Children = new Dictionary<string, SampleDict>() } },
                { "b", new SampleDict { Value = 7 } },
            }
            };
            var result0 = bs.ToBytes(v0);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleDict)) + " 02 00 " +
                XS("Value", RoughType.Int, "Children", RoughType.Mapping) + " 10 20" +
                " 01 00 03 00 00 00 02 00 02 00 00 00 " + XS("a") +
                " 01 00 01 00 05 00 00 00 02 00 00 00 00 00 00 00 " +
                XS("b") + " 01 00 01 00 07 00 00 00 02 00 FF FF FF FF 00 00 00 00",
                XS(result0));

            var w0 = new SampleDict();
            bd.FromBytes(w0, result0);
            Assert.AreEqual(v0.Value, w0.Value);
            Assert.AreEqual(v0.Children.Count, w0.Children.Count);
            Assert.AreEqual(v0.Children["a"].Value, w0.Children["a"].Value);

            var w1 = (SampleDict)bdg.FromBytes(result0);
            Assert.AreEqual(v0.Value, w1.Value);
            Assert.AreEqual(v0.Children.Count, w1.Children.Count);
            Assert.AreEqual(v0.Children["a"].Value, w1.Children["a"].Value);
        }
Exemplo n.º 53
0
        public void TestTopLevelListOfNonPrimitiveTypes()
        {
            var bs = new BinarySerializer();
            bs.Options.TagMode = TagMode.Names;
            var bd = new BinaryDeserializer();
            bd.Options.TagMode = TagMode.Names;

            var v1 = new List<SampleDerivedB> { new SampleDerivedB { FB = 10 }, new SampleDerivedB { FB = 20 } };

            var result1 = bs.ToBytes(v1);
            Assert.AreEqual(
                "21 20 02 00 00 00 01 00 " + XS(typeof(SampleDerivedB)) + " 02 00 " +
                XS("FBase", RoughType.Int, "FB", RoughType.Int) +
                " 01 00 00 00 00 00 02 00 0A 00 00 00 00 00 " +
                "01 00" +
                " 01 00 00 00 00 00 02 00 14 00 00 00 00 00",
                XS(result1));
            var w1 = (List<object>)bd.FromBytes(result1);
            for (int i = 0; i < v1.Count; i++) {
                Assert.AreEqual(v1[i].FB, (w1[i] as SampleDerivedB).FB);
            }
        }
Exemplo n.º 54
0
        public void TestDelegate()
        {
            var bs = new BinarySerializer();

            var v1 = new SampleSelfDelegate { x = 77 };
            v1.OnSomething = v1.Handler1;
            var result = bs.ToBytes(v1);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleSelfDelegate)) + " 02 00 " +
                XS("OnSomething", RoughType.Record, "x", RoughType.Int) +
                " 01 00 " + XS("Handler1") + " 02 00 4D 00 00 00 00 00",
                XS(result));

            var w1 = new SampleSelfDelegate();
            var bd = new BinaryDeserializer();
            bd.FromBytes(w1, result);
            Assert.AreEqual(v1.x, w1.x);
            w1.OnSomething(10);
            Assert.AreEqual(87, w1.x);

            result[69]++; // Replace("Handler1", "Handler2")
            (new BinaryDeserializer()).FromBytes(w1, result);
            w1.OnSomething(10);
            Assert.AreEqual(770, w1.x);
        }
 /// <summary>
 ///   Reads this object from its binary representation.
 /// </summary>
 /// <param name="deserializer">Deserializer to read the object with.</param>
 public void Deserialize(BinaryDeserializer deserializer)
 {
     this.AdditionalComponentTypes =
         deserializer.Deserialize<string[]>().Select<string, Type>(ReflectionUtils.FindType).ToList();
     this.BlueprintId = deserializer.Deserialize<string>();
     this.Configuration = deserializer.Deserialize<AttributeTable>();
 }
Exemplo n.º 56
0
        public void TestDefault()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();
            var bdg = new BinaryDeserializerGen();

            var v1 = new Sample1 { X = 6, Y = "ttt" };
            var result1 = bs.ToBytes(v1);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(Sample1)) + " 02 00 " +
                XS("X", RoughType.Int, "Y", RoughType.String) +
                " 01 00 06 00 00 00 00 00", XS(result1));
            var w1 = (Sample1)bd.FromBytes(result1);
            Assert.AreEqual(6, w1.X);
            Assert.AreEqual("zzz", w1.Y);
            var w1g = (Sample1)bdg.FromBytes(result1);
            Assert.AreEqual(6, w1g.X);
            Assert.AreEqual("zzz", w1g.Y);

            var v2 = new Sample2 { X = 5, Y = "5" };
            var result2 = bs.ToBytes(v2);
            Assert.AreEqual(
                "20 02 00 " + XS(typeof(Sample2)) + " 02 00 " +
                XS("X", RoughType.Int, "Y", RoughType.String) +
                " 01 00 05 00 00 00 00 00", XS(result2));
            Assert.IsInstanceOfType(bd.FromBytes(result2), typeof(Sample2));

            var v3 = new SampleDefault();
            var result3 = bs.ToBytes(new SampleDefault());
            Assert.AreEqual(
                "20 03 00 " + XS(typeof(SampleDefault)) + " 03 00 " +
                XS("A", RoughType.Int, "B", RoughType.String, "P", RoughType.Record) + " 00 00",
                XS(result3));
            Assert.IsInstanceOfType(bd.FromBytes(result3), typeof(SampleDefault));
            v3.B = "z";
            var result3m = bs.ToBytes(v3);
            Assert.AreEqual("20 03 00 02 00 " + XS("z") + " 00 00", XS(result3m));
            var w3 = new SampleDefault();
            bd.FromBytes(w3, result3m);
            Assert.AreEqual(3, w3.A);
            Assert.AreEqual("z", w3.B);
            Assert.AreEqual(new SamplePoint { X = 7, Y = 2 }, w3.P);

            var result4 = SX(
                "20 01 00 " + XS(typeof(SampleDefault)) + " 02 00 " +
                XS("A", RoughType.Int, "P", RoughType.Record) + " 01 00 05 00 00 00 " +
                "02 00 02 00 " + XS(typeof(SamplePoint)) + " 02 00 " +
                XS("X", RoughType.Int, "Y", RoughType.Int) + " 04 00 00 00 06 00 00 00 " +
                "00 00"
            );
            bdg.ClearClassIds();
            var w4 = bdg.FromBytes<SampleDefault>(result4);
            Assert.AreEqual(5, w4.A);
            Assert.AreEqual("default", w4.B);
            Assert.AreEqual(new SamplePoint { X = 4, Y = 6 }, w4.P);
        }
Exemplo n.º 57
0
        public void TestTopLevelDict()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();

            var v0 = new Dictionary<string, int> { { "a", 1 }, { "b", 2 } };
            var result0 = bs.ToBytes(v0);
            Assert.AreEqual(
                "22 10 05 02 00 00 00 " + XS("a") + " 01 00 00 00 " + XS("b") + " 02 00 00 00",
                XS(result0));

            var w0 = new Dictionary<string, int>();
            bd.FromBytes(w0, result0);
            CollectionAssert.AreEqual(v0, w0);
            bd.FromBytes(w0, new byte[] { 0x22, 0x10, 05, 0, 0, 0, 0 });
            CollectionAssert.AreEqual(v0, w0);
            bd.FromBytes(w0, SX("22 10 05 01 00 00 00 " + XS("c") + " 03 00 00 00"));
            CollectionAssert.AreEqual(
                new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } }, w0);
        }
Exemplo n.º 58
0
        public void TestDate()
        {
            var bs = new BinarySerializer();
            var bd = new BinaryDeserializer();

            var v1 = new SampleDate { D = new DateTime(2011, 3, 25), T = TimeSpan.FromMinutes(5) };
            var result1 = bs.ToBytes(v1);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleDate)) + " 02 00 " +
                XS("D", RoughType.DateTime, "T", RoughType.TimeSpan) +
                " 01 00 00 00 F5 B7 96 B8 CD 08 02 00 00 5E D0 B2 00 00 00 00 00 00",
                XS(result1));

            var w1 = new SampleDate();
            bd.FromBytes(w1, result1);
            Assert.AreEqual(v1.D, w1.D);
            Assert.AreEqual(v1.T, w1.T);

            var v2 = new DateTime(2011, 3, 25, 1, 2, 3, DateTimeKind.Utc);
            var result2 = bs.ToBytes(v2);
            var w2 = bd.FromBytes<DateTime>(result2);
            Assert.AreEqual(v2, w2);
            Assert.AreEqual(v2.Kind, w2.Kind);

            var v3 = new DateTime(2011, 3, 25, 1, 2, 3, DateTimeKind.Local);
            var result3 = bs.ToBytes(v3);
            var w3 = bd.FromBytes<DateTime>(result3);
            Assert.AreEqual(v3, w3);
            Assert.AreEqual(v3.Kind, w3.Kind);
        }
Exemplo n.º 59
0
        public void TestErrors()
        {
            var bd = new BinaryDeserializer();
            bd.Options.AllowEmptyTypes = true;
            var bdg = new BinaryDeserializerGenerator();

            XAssert.Throws<YuzuException>(() => bdg.Generate<ISample>(), "ISample");
            XAssert.Throws<YuzuException>(() => bdg.Generate<SampleAbstract>(), "SampleAbstract");
            XAssert.Throws<YuzuException>(() => bd.FromBytes<int>(new byte[] { 0xFF }), "255");

            XAssert.Throws<YuzuException>(() => bd.FromBytes(new byte[] { 0xFF }), "255");
            XAssert.Throws<YuzuException>(() => bd.FromBytes<int>(new byte[] { 0xFF }), "255");
            XAssert.Throws<YuzuException>(() => bd.FromBytes<int>(new byte[] { 07 }), "Int32");

            XAssert.Throws<YuzuException>(() => bd.FromBytes(new byte[] { (byte)RoughType.Any }), "pure");

            XAssert.Throws<YuzuException>(() => bd.FromBytes<Sample1>(SX(
                "20 01 00 " + XS("notype") + " 00 00 00 00"
            )), "YuzuUnknown");

            var w = new Sample1();
            XAssert.Throws<YuzuException>(() => bd.FromBytes(w, SX(
                "20 02 00 " + XS(typeof(Empty)) + " 00 00 00 00"
            )), "Sample1");

            var w2 = new Sample2Allow();
            XAssert.Throws<YuzuException>(() => bd.FromBytes(w2, SX(
                "20 02 00 00 00"
            )), "Sample2Allow");

            XAssert.Throws<YuzuException>(() => bd.FromBytes(w, SX("20 05 00")), "5");

            XAssert.Throws<YuzuException>(() => bd.FromBytes(w, SX(
                "20 03 00 " + XS(typeof(Sample1)) + " 00 00 00 00"
            )), " X ");

            XAssert.Throws<YuzuException>(() => bd.FromBytes(w, SX(
                "20 03 00 " + XS(typeof(Empty)) + " 00 01 " + XS("New", RoughType.Int) + " 00 00"
            )), "New");

            XAssert.Throws<YuzuException>(() => bd.FromBytes(w, SX(
                "20 03 00 " + XS(typeof(Sample1)) + " 00 01 " + XS("X", RoughType.String) + " 00 00"
            )), "Int32");
        }
Exemplo n.º 60
0
        public void TestInterface()
        {
            var bs = new BinarySerializer();
            var v1 = new SampleInterfaceField { I = new SampleInterfaced { X = 34 } };
            var result1 = bs.ToBytes(v1);
            Assert.AreEqual(
                "20 01 00 " + XS(typeof(SampleInterfaceField)) + " 01 00 " + XS("I", RoughType.Record) +
                " 01 00 02 00 " + XS(typeof(SampleInterfaced)) + " 01 00 " + XS("X", RoughType.Int) +
                " 01 00 22 00 00 00 00 00 00 00",
                XS(result1));

            var w1 = new SampleInterfaceField();
            var bd = new BinaryDeserializer();
            bd.FromBytes(w1, result1);
            Assert.IsInstanceOfType(w1.I, typeof(SampleInterfaced));
            Assert.AreEqual(34, w1.I.X);

            var w1g = new SampleInterfaceField();
            var bdg = new BinaryDeserializerGen();
            bdg.FromBytes(w1g, result1);
            Assert.IsInstanceOfType(w1g.I, typeof(SampleInterfaced));
            Assert.AreEqual(34, w1g.I.X);

            var w1n = (SampleInterfaceField)bd.FromBytes(new byte[] { 0x20, 01, 00, 01, 00, 00, 00, 00, 00 });
            Assert.AreEqual(null, w1n.I);
            var w1ng = (SampleInterfaceField)bdg.FromBytes(new byte[] { 0x20, 01, 00, 01, 00, 00, 00, 00, 00 });
            Assert.AreEqual(null, w1ng.I);

            var v2 = new List<ISample> { null, new SampleInterfaced { X = 37 } };
            var result2 = bs.ToBytes(v2);
            Assert.AreEqual("21 20 02 00 00 00 00 00 02 00 01 00 25 00 00 00 00 00", XS(result2));

            var w2 = new List<ISample>();
            bd.FromBytes(w2, result2);
            Assert.AreEqual(2, w2.Count);
            Assert.IsNull(w2[0]);
            Assert.AreEqual(37, w2[1].X);

            ISampleField v3 = new SampleInterfacedField { X = 41 };
            var result3 = bs.ToBytes(v3);
            Assert.AreEqual(
                "20 03 00 " + XS(typeof(SampleInterfacedField)) + " 01 00 " + XS("X", RoughType.Int) +
                " 01 00 29 00 00 00 00 00", XS(result3));
            var w3 = (ISampleField)bd.FromBytes(result3);
            Assert.AreEqual(41, w3.X);
        }