Implements serialization feature of MsgPack.
Inheritance: IDisposable
Exemplo n.º 1
0
        protected override void PackToCore(MsgPack.Packer packer, Delegate objectTree)
        {
            if (objectTree is CallbackDelegate)
            {
                var funcRef = objectTree.Method.DeclaringType?.GetFields(BindingFlags.NonPublic |
                                                                         BindingFlags.Instance |
                                                                         BindingFlags.Public |
                                                                         BindingFlags.Static).FirstOrDefault(a => a.FieldType == typeof(RemoteFunctionReference));

                if (funcRef == null)
                {
                    throw new ArgumentException("The CallbackDelegate does not contain a RemoteFunctionReference capture.");
                }

                RemoteFunctionReference fr = (RemoteFunctionReference)funcRef.GetValue(objectTree.Target);

                packer.PackExtendedTypeValue(10, fr.Duplicate());
            }
            else
            {
                var    funcRefDetails = FunctionReference.Create(objectTree);
                string refType        = InternalManager.CanonicalizeRef(funcRefDetails.Identifier);

                packer.PackExtendedTypeValue(10, Encoding.UTF8.GetBytes(refType));
            }
        }
Exemplo n.º 2
0
		public void PackToMessage( Packer pk, PackingOptions options )
		{
			pk.PackArrayHeader( 5 );
			pk.PackString( uri );
			pk.PackString( title );
			pk.Pack( width );
			pk.Pack( height );
			pk.Pack( size );
		}
Exemplo n.º 3
0
        public void PackToMessage(Packer packer, PackingOptions options)
        {
            packer.PackMapHeader(2);
            packer.Pack("__type");
            packer.Pack("MetaField");

            packer.Pack("fieldId");
            packer.Pack(FieldId);
        }
 public void PackToMessage(Packer packer, PackingOptions options)
 {
     packer.PackMapHeader(3);
     packer.PackString("graphName");
     packer.Pack(this.graphName);
     packer.PackString("graphObjName");
     packer.Pack(this.graphObjName);
     packer.PackString("killSession");
     packer.Pack(this.killSession);
 }
Exemplo n.º 5
0
        protected override void PackToCore(MsgPack.Packer packer, IO.Ably.Message objectTree)
        {
            var nonNullFields = new bool[]
            {
                objectTree.ClientId.IsNotEmpty(),
                objectTree.ConnectionId.IsNotEmpty(),
                objectTree.Data != null,
                objectTree.Encoding.IsNotEmpty(),
                objectTree.Id.IsNotEmpty(),
                objectTree.Name.IsNotEmpty(),
                objectTree.Timestamp != null,
            }.Count(x => x);

            packer.PackMapHeader(nonNullFields);
            if (objectTree.ClientId.IsNotEmpty())
            {
                this._serializer0.PackTo(packer, "clientId");
                this._serializer0.PackTo(packer, objectTree.ClientId);
            }
            if (objectTree.ConnectionId.IsNotEmpty())
            {
                this._serializer0.PackTo(packer, "connectionId");
                this._serializer0.PackTo(packer, objectTree.ConnectionId);
            }
            if (objectTree.Data != null)
            {
                this._serializer0.PackTo(packer, "data");
                this._serializer1.PackTo(packer, objectTree.Data);
            }
            if (objectTree.Encoding.IsNotEmpty())
            {
                this._serializer0.PackTo(packer, "encoding");
                this._serializer0.PackTo(packer, objectTree.Encoding);
            }
            if (objectTree.Id.IsNotEmpty())
            {
                this._serializer0.PackTo(packer, "id");
                this._serializer0.PackTo(packer, objectTree.Id);
            }
            if (objectTree.Name.IsNotEmpty())
            {
                this._serializer0.PackTo(packer, "name");
                this._serializer0.PackTo(packer, objectTree.Name);
            }
            if (objectTree.Timestamp != null)
            {
                this._serializer0.PackTo(packer, "timestamp");
                this._serializer2.PackTo(packer, objectTree.Timestamp);
            }
        }
Exemplo n.º 6
0
        public static bool MsgPackLuaTable(ref LuaTable luatable, ref Packer pker)
        {

            if (luatable == null)
            {
                pker = null;
                return false;
            }
            else
            {
                pker.PackMapHeader(luatable.Count);
            }
            foreach (var item in luatable)
            {
                //object key = item.Key;
                bool kFlag = luatable.IsKeyString(item.Key);
                if (kFlag)
                {
                    pker.PackRawHeader(item.Key.Length);
                    pker.PackRawBody(System.Text.Encoding.UTF8.GetBytes(item.Key));
                }
                else
                {
                    pker.Pack(double.Parse(item.Key.ToString()));
                }

                var valueType = item.Value.GetType();
                if (valueType == typeof(String))
                {

                    pker.PackRawHeader(item.Value.ToString().Length);
                    pker.PackRawBody(System.Text.Encoding.UTF8.GetBytes(item.Value.ToString()));
                }
                else if (valueType == typeof(LuaTable))
                {
                    LuaTable luaTbl = item.Value as LuaTable;
                    MsgPackLuaTable(ref luaTbl, ref pker);
                }
                else if (valueType == typeof(bool))
                {
                    pker.Pack(bool.Parse(item.Value.ToString()));
                }
                else
                {
                    pker.Pack(double.Parse(item.Value.ToString()));
                }
            }
            return true;
        }
		public void PackToMessage( Packer packer, PackingOptions options )
		{
			// Pack fields are here:
			// First, record total fields size.
			packer.PackArrayHeader( 2 );
			packer.Pack( this.Id );
			packer.PackString( this.Name );

			// ...Instead, you can pack as map as follows:
			// packer.PackMapHeader( 2 );
			// packer.Pack( "Id" );
			// packer.Pack( this.Id );
			// packer.Pack( "Name" );
			// packer.Pack( this.Name );
		}
Exemplo n.º 8
0
        protected override void PackToCore(MsgPack.Packer packer, Delegate objectTree)
        {
            if (objectTree is CallbackDelegate)
            {
                throw new InvalidOperationException("Resending callback delegates is currently not supported.");
            }

            var funcRefDetails = FunctionReference.Create(objectTree);

            var resourceNameBytes = Encoding.UTF8.GetBytes(funcRefDetails.Resource);
            var delegateData      = new byte[8 + resourceNameBytes.Length];

            Array.Copy(BitConverter.GetBytes(funcRefDetails.Identifier).Reverse().ToArray(), 0, delegateData, 0, 4);
            Array.Copy(BitConverter.GetBytes(funcRefDetails.Instance).Reverse().ToArray(), 0, delegateData, 4, 4);
            Array.Copy(resourceNameBytes, 0, delegateData, 8, resourceNameBytes.Length);

            packer.PackExtendedTypeValue(1, delegateData);
        }
        public void PackToMessage(Packer packer, PackingOptions options)
        {
            packer.PackMapHeader(this.inSession ? 4 : 6)
                  .PackString("channel")
                  .Pack(Channel.MsgPack)
                  .PackString("inSession")
                  .Pack(this.inSession)
                  .PackString("isolate")
                  .Pack(this.isolate)
                  .PackString("transaction")
                  .Pack(this.transaction);

            if (!this.inSession)
            {
                packer.PackString("graphName")
                      .PackString(this.graphName)
                      .PackString("graphObjName")
                      .PackString(this.graphObjName);
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// Use msgpack to compress the data
 /// </summary>
 /// <param name="packer">
 /// The msgpack packer
 /// </param>
 /// <param name="options">
 /// msgpack packing options
 /// </param>
 public void PackToMessage(Packer packer, PackingOptions options)
 {
     packer.PackArrayHeader(this.Values.Count);
     foreach (object obj in this.Values)
     {
         if (obj.GetType() == typeof(string))
         {
             string temp = (string)obj;
             packer.PackString(temp, Encoding.GetEncoding("UTF-8"));
         }
         else if (obj.GetType() == typeof(Single))
         {
             float temp = (Single)obj;
             packer.Pack<float>(temp);
         }
         else if (obj.GetType() == typeof(int))
         {
             int temp = (Int32)obj;
             packer.Pack(temp);
         }
     }
 }
 /// <summary>
 /// Use msgpack to compress the data
 /// </summary>
 /// <param name="packer">
 /// The msgpack packer
 /// </param>
 /// <param name="options">
 /// msgpack packing options
 /// </param>
 public void PackToMessage(Packer packer, PackingOptions options)
 {
     packer.PackArrayHeader(this.Values.Count);
     foreach (MessagePackObject obj in this.Values)
     {
         if (obj.IsTypeOf(typeof(string)) == true)
         {
             string temp = obj.AsStringUtf8();
             packer.PackString(temp);
         }
         else if (obj.IsTypeOf(typeof(Single)) == true)
         {
             float temp = obj.AsSingle();
             packer.Pack<float>(temp);
         }
         else if (obj.IsTypeOf(typeof(int)) == true)
         {
             int temp = obj.AsInt32();
             packer.Pack(temp);
         }
     }
 }
Exemplo n.º 12
0
 protected abstract byte[] GetResult(Packer packer);
Exemplo n.º 13
0
 public void PackToMessage(Packer packer, PackingOptions options)
 {
     // 0xC3
     packer.Pack(true);
 }
Exemplo n.º 14
0
        public void TestDeepNestedArray()
        {
            using (var stream = new MemoryStream())
            {
                var packer = Packer.Create(stream);
                packer.Pack(
                    new[]
                {
                    new MessagePackObject(
                        new[]
                    {
                        new MessagePackObject(
                            new [] { new MessagePackObject("1-1-1"), new MessagePackObject("1-1-2"), new MessagePackObject("1-1-3") }
                            ),
                        new MessagePackObject(
                            new [] { new MessagePackObject("1-2-1"), new MessagePackObject("1-2-2"), new MessagePackObject("1-2-3") }
                            ),
                        new MessagePackObject(
                            new [] { new MessagePackObject("1-3-1"), new MessagePackObject("1-3-2"), new MessagePackObject("1-3-3") }
                            ),
                    }
                        ),
                    new MessagePackObject(
                        new[]
                    {
                        new MessagePackObject(
                            new [] { new MessagePackObject("2-1-1"), new MessagePackObject("2-1-2"), new MessagePackObject("2-1-3") }
                            ),
                        new MessagePackObject(
                            new [] { new MessagePackObject("2-2-1"), new MessagePackObject("2-2-2"), new MessagePackObject("2-2-3") }
                            ),
                        new MessagePackObject(
                            new [] { new MessagePackObject("2-3-1"), new MessagePackObject("2-3-2"), new MessagePackObject("2-3-3") }
                            ),
                    }
                        ),
                    new MessagePackObject(
                        new[]
                    {
                        new MessagePackObject(
                            new [] { new MessagePackObject("3-1-1"), new MessagePackObject("3-1-2"), new MessagePackObject("3-1-3") }
                            ),
                        new MessagePackObject(
                            new [] { new MessagePackObject("3-2-1"), new MessagePackObject("3-2-2"), new MessagePackObject("3-2-3") }
                            ),
                        new MessagePackObject(
                            new [] { new MessagePackObject("3-3-1"), new MessagePackObject("3-3-2"), new MessagePackObject("3-3-3") }
                            ),
                    }
                        ),
                }
                    );
                stream.Position = 0;
                var unpacker = Unpacker.Create(stream);
                Assert.That(unpacker.Read());
                using (Unpacker subtreeReader1 = unpacker.ReadSubtree())
                {
                    Assert.That(subtreeReader1.IsArrayHeader);
                    Assert.That(subtreeReader1.ItemsCount, Is.EqualTo(3));

                    for (int i = 1; subtreeReader1.Read(); i++)
                    {
                        using (Unpacker subtreeReader2 = subtreeReader1.ReadSubtree())
                        {
                            Assert.That(subtreeReader2.IsArrayHeader);
                            Assert.That(subtreeReader2.ItemsCount, Is.EqualTo(3));
                            for (int j = 1; subtreeReader2.Read(); j++)
                            {
                                using (Unpacker subtreeReader3 = subtreeReader2.ReadSubtree())
                                {
                                    Assert.That(subtreeReader3.IsArrayHeader);
                                    Assert.That(subtreeReader3.ItemsCount, Is.EqualTo(3));
                                    for (int k = 1; subtreeReader3.Read(); k++)
                                    {
                                        Assert.That(subtreeReader3.LastReadData.AsString(), Is.EqualTo(i + "-" + j + "-" + k));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        ///     Packs the candidate to a MessagePack objects
        ///     This method should not be called directly, use serialize instead.
        /// </summary>
        /// <param name="packer">The packer</param>
        /// <param name="options">The packer options</param>
        public void PackToMessage(Packer packer, PackingOptions options)
        {
            // pack the header for the amount of items in the map
            packer.PackMapHeader(MapCount);

            packer.Pack("DCS");
            packer.Pack(Dcs);

            packer.Pack("DAC");
            packer.Pack(Dac);

            packer.Pack("DAD");
            packer.Pack(Dad);

            packer.Pack("DBD");
            packer.Pack(Dbd.ToString(DateFormat, CultureInfo.InvariantCulture));

            packer.Pack("DBB");
            packer.Pack(Dbb.ToString(DateFormat, CultureInfo.InvariantCulture));

            packer.Pack("DBC");
            packer.Pack((int) Dbc);

            packer.Pack("DAY");
            packer.Pack(Day.AnsiFormat());

            packer.Pack("DAU");
            packer.Pack(Dau.AnsiFormat);

            packer.Pack("DAG");
            packer.Pack(Dag);

            packer.Pack("DAI");
            packer.Pack(Dai);

            packer.Pack("DAJ");
            packer.Pack(Daj);

            packer.Pack("DAK");
            packer.Pack(Dak.AnsiFormat);

            packer.Pack("DCG");
            packer.Pack(Dcg);

            // pack image
            packer.Pack("ZAA");
            var imageConverter = new ImageConverter();
            packer.Pack((byte[]) imageConverter.ConvertTo(Image, typeof (byte[])));

            // pack fingerprint
            packer.Pack("ZAB");

            if (Fingerprint.Image != null) {
                var afis = new AfisEngine();
                var p = new Person(Fingerprint);
                afis.Extract(p);
            }
            if (Fingerprint.AsIsoTemplate != null) packer.Pack(Fingerprint.AsIsoTemplate);
        }
Exemplo n.º 16
0
 /// <summary>
 ///		Packs specified collection with the default context.
 /// </summary>
 /// <typeparam name="T">The type of items of the collection.</typeparam>
 /// <param name="source">The <see cref="Packer"/>.</param>
 /// <param name="collection">The collection to be serialized.</param>
 /// <returns><paramref name="source"/>.</returns>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="source"/> is <c>null</c>.
 /// </exception>
 /// <exception cref="System.Runtime.Serialization.SerializationException">
 ///		Cannot serialize <paramref name="collection"/>.
 /// </exception>
 public static Packer PackArray <T>(this Packer source, IEnumerable <T> collection)
 {
     PackCollectionCore(source, collection, SerializationContext.Default);
     return(source);
 }
Exemplo n.º 17
0
 protected override Packer CreatePacker(MemoryStream stream)
 {
     Assert.That(stream.Position, Is.EqualTo(0));
     return(Packer.Create(new byte[64 * 1024]));
 }
 /// <summary>
 /// Serializes the target object
 /// </summary>
 /// <param name="packer"></param>
 /// <param name="objectTree"></param>
 protected override void PackToCore(MsgPack.Packer packer, T objectTree)
 {
     _pack(packer, objectTree);
 }
Exemplo n.º 19
0
        public void TestArray()
        {
            var emptyList = new List <int>();
            {
                var output = new MemoryStream();
                Packer.Create(output).PackCollection(emptyList);
                Assert.AreEqual(0, Unpacking.UnpackArrayLength(new MemoryStream(output.ToArray())));
                Assert.AreEqual(0, Unpacking.UnpackArrayLength(output.ToArray()).Value);
            }

            var random = new Random();

            for (int i = 0; i < 100; i++)
            {
                var l   = new List <int>();
                int len = ( int )random.Next() % 1000 + 1;
                for (int j = 0; j < len; j++)
                {
                    l.Add(j);
                }
                var output = new MemoryStream();
                Packer.Create(output).PackCollection(l);

                Stream streamInput = new MemoryStream(output.ToArray());
                Assert.AreEqual(len, Unpacking.UnpackArrayLength(streamInput));
                for (int j = 0; j < len; j++)
                {
                    Assert.AreEqual(l[j], Unpacking.UnpackInt32(streamInput));
                }

                byte[] byteArrayInput = output.ToArray();
                var    arrayLength    = Unpacking.UnpackArrayLength(byteArrayInput);
                Assert.AreEqual(len, arrayLength.Value);
                int offset = arrayLength.ReadCount;
                for (int j = 0; j < len; j++)
                {
                    var uar = Unpacking.UnpackInt32(byteArrayInput, offset);
                    Assert.AreNotEqual(0, uar.ReadCount);
                    Assert.AreEqual(l[j], uar.Value);
                    offset += uar.ReadCount;
                }
            }

            for (int i = 0; i < 100; i++)
            {
                var l   = new List <String>();
                int len = ( int )random.Next() % 1000 + 1;
                for (int j = 0; j < len; j++)
                {
                    l.Add(j.ToString());
                }
                var output = new MemoryStream();
                Packer.Create(output).PackCollection(l);

                Stream streamInput = new MemoryStream(output.ToArray());
                Assert.AreEqual(len, Unpacking.UnpackArrayLength(streamInput));
                for (int j = 0; j < len; j++)
                {
                    Assert.AreEqual(l[j], Unpacking.UnpackString(streamInput));
                }

                byte[] byteArrayInput = output.ToArray();
                var    arrayLength    = Unpacking.UnpackArrayLength(byteArrayInput);
                Assert.AreEqual(len, arrayLength.Value);
                int offset = arrayLength.ReadCount;
                for (int j = 0; j < len; j++)
                {
                    var usr = Unpacking.UnpackString(byteArrayInput, offset);
                    Assert.AreEqual(l[j], usr.Value);
                    offset += usr.ReadCount;
                }
            }
        }
Exemplo n.º 20
0
 /// <summary>
 ///		Packs specified dictionary with the specified context.
 /// </summary>
 /// <typeparam name="TKey">The type of keys of the dictionary.</typeparam>
 /// <typeparam name="TValue">The type of values of the dictionary.</typeparam>
 /// <param name="source">The <see cref="Packer"/>.</param>
 /// <param name="dictionary">The dictionary to be serialized.</param>
 /// <param name="context">The <see cref="SerializationContext"/> holds shared serializers.</param>
 /// <returns><paramref name="source"/>.</returns>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="source"/> is <c>null</c>.
 ///		Or <paramref name="context"/> is <c>null</c>.
 /// </exception>
 /// <exception cref="System.Runtime.Serialization.SerializationException">
 ///		Cannot serialize <paramref name="dictionary"/>.
 /// </exception>
 public static Packer PackDictionary <TKey, TValue>(this Packer source, IDictionary <TKey, TValue> dictionary, SerializationContext context)
 {
     PackDictionaryCore(source, dictionary, context);
     return(source);
 }
Exemplo n.º 21
0
 private static void PackCollectionCore <T>(Packer source, IEnumerable <T> collection, SerializationContext context)
 {
     PackCollectionCore(source, collection, context.GetSerializer <T>());
 }
Exemplo n.º 22
0
 /// <summary>
 ///		Packs specified collection with the specified context.
 /// </summary>
 /// <typeparam name="T">The type of items of the collection.</typeparam>
 /// <param name="source">The <see cref="Packer"/>.</param>
 /// <param name="collection">The collection to be serialized.</param>
 /// <param name="context">The <see cref="SerializationContext"/> holds shared serializers.</param>
 /// <returns><paramref name="source"/>.</returns>
 /// <exception cref="ArgumentNullException">
 ///		<paramref name="source"/> is <c>null</c>.
 ///		Or <paramref name="context"/> is <c>null</c>.
 /// </exception>
 /// <exception cref="System.Runtime.Serialization.SerializationException">
 ///		Cannot serialize <paramref name="collection"/>.
 /// </exception>
 public static Packer PackCollection <T>(this Packer source, IEnumerable <T> collection, SerializationContext context)
 {
     PackCollectionCore(source, collection, context);
     return(source);
 }
Exemplo n.º 23
0
 protected override Packer CreatePacker(MemoryStream stream, PackerCompatibilityOptions compatibilityOptions)
 {
     Assert.That(stream.Position, Is.EqualTo(0));
     return(Packer.Create(new byte[64 * 1024], true, compatibilityOptions));
 }
Exemplo n.º 24
0
        public void PackToMessage(Packer packer, PackingOptions options)
        {
            packer.Pack((byte)RequestType);

            PackToMessageCore(packer);
        }
Exemplo n.º 25
0
			public void PackToMessage( Packer packer, PackingOptions options )
			{
				// 0xC3
				packer.Pack( true );
			}
Exemplo n.º 26
0
 private static ByteArrayPacker CreatePacker(byte[] buffer, int startOffset, Func <byte[], int, byte[]> allocator)
 {
     return(Packer.Create(buffer, startOffset, allocator, PackerCompatibilityOptions.None));
 }
Exemplo n.º 27
0
        public void TestHeteroArray()
        {
            var heteroList = new List <MessagePackObject>()
            {
                true,
                false,
                MessagePackObject.Nil,
                0,
                "",
                123456,
                -123456,
                new String('a', 40000),
                new String('a', 80000),
                new MessagePackObject(
                    new MessagePackObjectDictionary()
                {
                    { "1", "foo" },
                    { 2, MessagePackObject.Nil },
                    { 3333333, -1 }
                }
                    ),
                new MessagePackObject(new MessagePackObject[] { 1, 2, 3 })
            };

            var output = new MemoryStream();

            Packer.Create(output).PackCollection(heteroList);
            MessagePackObject obj = UnpackOne(output);
            bool isSuccess        = false;

            try
            {
                var list = obj.AsList();
                Assert.AreEqual(heteroList[0], list[0]);
                Assert.AreEqual(heteroList[1], list[1]);
                Assert.AreEqual(heteroList[2], list[2]);
                Assert.AreEqual(heteroList[3], list[3]);
                Assert.AreEqual(heteroList[4], list[4]);
                Assert.AreEqual(heteroList[5], list[5]);
                Assert.AreEqual(heteroList[6], list[6]);
                Assert.AreEqual(heteroList[7], list[7]);
                Assert.AreEqual(heteroList[8], list[8]);
                Assert.AreEqual(
                    heteroList[9].AsDictionary()["1"],
                    list[9].AsDictionary()["1"]
                    );
                Assert.IsTrue(list[9].AsDictionary()[2].IsNil);
                Assert.AreEqual(
                    heteroList[9].AsDictionary()[3333333],
                    list[9].AsDictionary()[3333333]
                    );
                Assert.AreEqual(heteroList[10].AsList()[0], list[10].AsList()[0]);
                Assert.AreEqual(heteroList[10].AsList()[1], list[10].AsList()[1]);
                Assert.AreEqual(heteroList[10].AsList()[2], list[10].AsList()[2]);
                isSuccess = true;
            }
            finally
            {
                if (!isSuccess)
                {
                    Console.WriteLine(Dump(obj));
                }
            }
        }
Exemplo n.º 28
0
 private static ByteArrayPacker CreatePacker(byte[] buffer, int startOffset, bool allowsBufferExtension)
 {
     return(Packer.Create(buffer, startOffset, allowsBufferExtension, PackerCompatibilityOptions.None));
 }
 public void PackToMessage(Packer packer, PackingOptions options)
 {
     packer.Pack(count);
     packer.PackString(data);
 }
Exemplo n.º 30
0
 protected override byte[] GetResult(Packer packer)
 {
     return((( ByteArrayPacker )packer).GetResultBytes().ToArray());
 }
Exemplo n.º 31
0
        public void TestMap()
        {
            var emptyMap = new Dictionary <int, int>();
            {
                var output = new MemoryStream();
                Packer.Create(output).PackDictionary(emptyMap);
                Assert.AreEqual(0, Unpacking.UnpackDictionaryCount(new MemoryStream(output.ToArray())));
                Assert.AreEqual(0, Unpacking.UnpackDictionaryCount(output.ToArray()).Value);
            }

            var random = new Random();

            for (int i = 0; i < 100; i++)
            {
                var m   = new Dictionary <int, int>();
                int len = ( int )random.Next() % 1000 + 1;
                for (int j = 0; j < len; j++)
                {
                    m[j] = j;
                }
                var output = new MemoryStream();
                Packer.Create(output).PackDictionary(m);

                Stream streamInput = new MemoryStream(output.ToArray());
                Assert.AreEqual(len, Unpacking.UnpackDictionaryCount(streamInput));
                for (int j = 0; j < len; j++)
                {
                    int value;
                    Assert.IsTrue(m.TryGetValue(Unpacking.UnpackInt32(streamInput), out value));
                    Assert.AreEqual(value, Unpacking.UnpackInt32(streamInput));
                }

                byte[] byteArrayInput = output.ToArray();
                var    arrayLength    = Unpacking.UnpackDictionaryCount(byteArrayInput);
                Assert.AreEqual(len, arrayLength.Value);
                int offset = arrayLength.ReadCount;
                for (int j = 0; j < len; j++)
                {
                    var keyUar = Unpacking.UnpackInt32(byteArrayInput, offset);
                    Assert.AreNotEqual(0, keyUar.ReadCount);
                    int value;
                    Assert.IsTrue(m.TryGetValue(keyUar.Value, out value));
                    var valueUar = Unpacking.UnpackInt32(byteArrayInput, offset + keyUar.ReadCount);
                    Assert.AreEqual(value, valueUar.Value);
                    offset += keyUar.ReadCount + valueUar.ReadCount;
                }
            }

            for (int i = 0; i < 100; i++)
            {
                var m   = new Dictionary <string, int>();
                int len = ( int )random.Next() % 1000 + 1;
                for (int j = 0; j < len; j++)
                {
                    m[j.ToString()] = j;
                }
                var output = new MemoryStream();
                Packer.Create(output).PackDictionary(m);

                Stream streamInput = new MemoryStream(output.ToArray());
                Assert.AreEqual(len, Unpacking.UnpackDictionaryCount(streamInput));
                for (int j = 0; j < len; j++)
                {
                    int value;
                    Assert.IsTrue(m.TryGetValue(Unpacking.UnpackString(streamInput), out value));
                    Assert.AreEqual(value, Unpacking.UnpackInt32(streamInput));
                }

                byte[] byteArrayInput = output.ToArray();
                var    arrayLength    = Unpacking.UnpackDictionaryCount(byteArrayInput);
                Assert.AreEqual(len, arrayLength.Value);
                int offset = arrayLength.ReadCount;
                for (int j = 0; j < len; j++)
                {
                    var usr = Unpacking.UnpackString(byteArrayInput, offset);
                    Assert.AreNotEqual(0, usr.ReadCount);
                    int value;
                    Assert.IsTrue(m.TryGetValue(usr.Value, out value));
                    var uar = Unpacking.UnpackInt32(byteArrayInput, offset + usr.ReadCount);
                    Assert.AreEqual(value, uar.Value);
                    offset += usr.ReadCount + uar.ReadCount;
                }
            }
        }
Exemplo n.º 32
0
 protected abstract void PackToMessageCore(Packer packer);
Exemplo n.º 33
0
 protected override Packer CreatePacker(MemoryStream stream)
 {
     return(Packer.Create(stream));
 }
Exemplo n.º 34
0
 protected override Packer CreatePacker(MemoryStream stream, PackerCompatibilityOptions compatibilityOptions)
 {
     return(Packer.Create(stream, compatibilityOptions));
 }
Exemplo n.º 35
0
 protected override void PackToMessageCore(Packer packer)
 {
     packer.PackArrayHeader(1);
     packer.Pack(_str);
 }
Exemplo n.º 36
0
 protected override byte[] GetResult(Packer packer)
 {
     return((( MemoryStream )(( MessagePackStreamPacker )packer).Destination).ToArray());
 }
Exemplo n.º 37
0
        /// <summary>
        /// </summary>
        /// <param name="packer">
        /// </param>
        /// <param name="options">
        /// </param>
        public void PackToMessage(Packer packer, PackingOptions options)
        {
            // Serialize type name of the data object
            packer.Pack(this.typeName);

            // Serialize the data object itself as a byte array
            packer.Pack(this.dataObject.GetData());
        }
        void Pack(Packer packer, object o)
        {
            if (o == null) {
                packer.PackNull();
                return;
            }

            if (o is int)
                packer.Pack ((int)o);
            else if (o is uint)
                packer.Pack ((uint)o);
            else if (o is float)
                packer.Pack ((float)o);
            else if (o is double)
                packer.Pack ((double)o);
            else if (o is long)
                packer.Pack ((long)o);
            else if (o is ulong)
                packer.Pack ((ulong)o);
            else if (o is bool)
                packer.Pack ((bool)o);
            else if (o is byte)
                packer.Pack ((byte)o);
            else if (o is sbyte)
                packer.Pack ((sbyte)o);
            else if (o is short)
                packer.Pack ((short)o);
            else if (o is ushort)
                packer.Pack ((ushort)o);
            else if (o is string)
                packer.PackString((string)o, Encoding.ASCII);
            else if (o is Dictionary<string, object>)
            {
                packer.PackMapHeader((o as Dictionary<string, object>).Count);

                foreach (var pair in (o as Dictionary<string, object>))
                {
                    Pack(packer, pair.Key);
                    Pack(packer, pair.Value);
                }

            }
            else if (o is string[])
            {
                packer.PackArrayHeader((o as string[]).Length);

                foreach (var obj in (o as string[]))
                    packer.Pack(obj as string);
            }
            else
                throw new Exception("Cant handle type: " + o.GetType().Name);;
        }