public IDictionary Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }

            var formatter   = formatterResolver.GetFormatterWithVerify <object>();
            var startOffset = offset;

            var count = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);

            offset += readSize;

            var dict = new Dictionary <object, object>(count);

            for (int i = 0; i < count; i++)
            {
                var key = formatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                offset += readSize;
                var value = formatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                offset += readSize;
                dict.Add(key, value);
            }

            readSize = offset - startOffset;
            return(dict);
        }
        private SwimMember DeserializeMember(byte[] bytes, int offset, out int readSize)
        {
            readSize = 0;

            var host = DeserializeHost(bytes, offset + readSize, out var r);

            readSize += r;

            var metaCount = MessagePackBinary.ReadMapHeader(bytes, offset + readSize, out r);

            readSize += r;
            var meta = new Dictionary <string, string>();

            for (var i = 0; i < metaCount; i++)
            {
                var key = MessagePackBinary.ReadString(bytes, offset + readSize, out r);
                readSize += r;
                var value = MessagePackBinary.ReadString(bytes, offset + readSize, out r);
                readSize += r;

                meta.Add(key, value);
            }

            var state = (SwimMemberState)MessagePackBinary.ReadByte(bytes, offset + readSize, out r);

            readSize += r;
            var incarnation = MessagePackBinary.ReadInt32(bytes, offset + readSize, out r);

            readSize += r;

            return(new SwimMember(host, new SwimMeta(meta), state, incarnation));
        }
        public void Standard()
        {
            var o = new SimpleIntKeyData()
            {
                Prop1 = 100,
                Prop2 = ByteEnum.C,
                Prop3 = "abcde",
                Prop4 = new SimlpeStringKeyData
                {
                    Prop1 = 99999,
                    Prop2 = ByteEnum.E,
                    Prop3 = 3
                },
                Prop5 = new SimpleStructIntKeyData
                {
                    X            = 100,
                    Y            = 300,
                    BytesSpecial = new byte[] { 9, 99, 122 }
                },
                Prop6 = new SimpleStructStringKeyData
                {
                    X = 9999,
                    Y = new[] { 1, 10, 100 }
                },
                BytesSpecial = new byte[] { 1, 4, 6 }
            };


            var bytes = MessagePackSerializer.Serialize(o);
            var ms    = new MemoryStream(bytes);

            MessagePackBinary.ReadArrayHeader(ms).Is(7);
            MessagePackBinary.ReadInt32(ms).Is(100);
            MessagePackBinary.ReadByte(ms).Is((byte)ByteEnum.C);
            MessagePackBinary.ReadString(ms).Is("abcde");

            MessagePackBinary.ReadMapHeader(ms).Is(3);
            MessagePackBinary.ReadString(ms).Is("Prop1");
            MessagePackBinary.ReadInt32(ms).Is(99999);
            MessagePackBinary.ReadString(ms).Is("Prop2");
            MessagePackBinary.ReadByte(ms).Is((byte)ByteEnum.E);
            MessagePackBinary.ReadString(ms).Is("Prop3");
            MessagePackBinary.ReadInt32(ms).Is(3);

            MessagePackBinary.ReadArrayHeader(ms).Is(3);
            MessagePackBinary.ReadInt32(ms).Is(100);
            MessagePackBinary.ReadInt32(ms).Is(300);
            MessagePackBinary.ReadBytes(ms).Is(new byte[] { 9, 99, 122 });

            MessagePackBinary.ReadMapHeader(ms).Is(2);
            MessagePackBinary.ReadString(ms).Is("key-X");
            MessagePackBinary.ReadInt32(ms).Is(9999);
            MessagePackBinary.ReadString(ms).Is("key-Y");
            MessagePackBinary.ReadArrayHeader(ms).Is(3);
            MessagePackBinary.ReadInt32(ms).Is(1);
            MessagePackBinary.ReadInt32(ms).Is(10);
            MessagePackBinary.ReadInt32(ms).Is(100);

            MessagePackBinary.ReadBytes(ms).Is(new byte[] { 1, 4, 6 });
        }
예제 #4
0
        public T Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }

            var formatter   = formatterResolver.GetFormatterWithVerify <object>();
            var startOffset = offset;

            var count = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);

            offset += readSize;

            var dict = CollectionHelpers <T, IEqualityComparer> .CreateHashCollection(count, MessagePackSecurity.Active.GetEqualityComparer());

            using (MessagePackSecurity.DepthStep())
            {
                for (int i = 0; i < count; i++)
                {
                    var key = formatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    var value = formatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dict.Add(key, value);
                }
            }

            readSize = offset - startOffset;
            return(dict);
        }
예제 #5
0
    public static Dictionary <string, object> Deserialize(byte[] bytes, int offset, out int readSize)
    {
        if (MessagePackBinary.IsNil(bytes, offset))
        {
            readSize = 1;
            return(default(Dictionary <string, object>));
        }
        else
        {
            var startOffset = offset;

            var len = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);
            offset += readSize;

            var dict = new Dictionary <string, object>(len);
            for (int i = 0; i < len; i++)
            {
                var key = MessagePackBinary.ReadString(bytes, offset, out readSize);
                offset += readSize;

                var value = DeserializeObject(bytes, offset, out readSize);
                offset += readSize;

                dict.Add(key, value);
            }
            readSize = offset - startOffset;

            return(dict);
        }
    }
예제 #6
0
        public override Product Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            int     startOffset = offset;
            int     size        = 0;
            Product p           = new Product();

            var initialSize = offset;

            if (bytes[offset] == 0xc0)
            {
                readSize = 1;
                return(null);
            }

            int headSize = 0;

            _       = MessagePackBinary.ReadMapHeader(bytes, offset, out headSize);
            offset += headSize;
            // element name
            var instance = new Product();
            int expectedFieldsDeserialized = 8;

            offset += DeserializeProperties(bytes, offset, formatterResolver, expectedFieldsDeserialized, instance);

            readSize = offset - initialSize;

            return(instance);
        }
예제 #7
0
    public int GetMapLength()
    {
        int value = MessagePackBinary.ReadMapHeader(_bytes, _offset, out int length);

        _offset += length;
        return(value);
    }
예제 #8
0
        public TDictionary Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(default(TDictionary));
            }
            else
            {
                var startOffset    = offset;
                var keyFormatter   = formatterResolver.GetFormatterWithVerify <TKey>();
                var valueFormatter = formatterResolver.GetFormatterWithVerify <TValue>();

                var len = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);
                offset += readSize;

                var dict = Create(len);
                for (int i = 0; i < len; i++)
                {
                    var key = keyFormatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;

                    var value = valueFormatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;

                    Add(dict, i, key, value);
                }
                readSize = offset - startOffset;

                return(Complete(dict));
            }
        }
예제 #9
0
        public int ReadMapHeader()
        {
            int value = MessagePackBinary.ReadMapHeader(Buffer, Position, out int readSize);

            Position += readSize;

            return(value);
        }
예제 #10
0
        public static int ReadMapHeader(ref ReadOnlyMemory <byte> data)
        {
            var arr = GetArray(data);
            var val = MessagePackBinary.ReadMapHeader(arr.Array, arr.Offset, out var readSize);

            data = data.Slice(readSize);
            return(val);
        }
예제 #11
0
        IEnumerable <string> IteratePropertyNames(byte[] bin)
        {
            var offset   = 0;
            int readSize = 0;
            var mapCount = MessagePackBinary.ReadMapHeader(bin, 0, out readSize);

            offset += readSize;
            for (int i = 0; i < mapCount; i++)
            {
                yield return(MessagePackBinary.ReadString(bin, offset, out readSize));

                offset += readSize;
                offset += MessagePackBinary.ReadNext(bin, offset);
            }
        }
예제 #12
0
        public static long ReadMapLength(byte[] input, ref int offset, string field)
        {
            Exception msgPackException = null;

            try
            {
                var readMap = MessagePackBinary.ReadMapHeader(input, offset, out var readSize);
                offset += readSize;
                return(readMap);
            }
            catch (Exception e)
            {
                msgPackException = e;
            }

            throw new InvalidDataException($"Reading map length for '{field}' failed.", msgPackException);
        }
예제 #13
0
        public T Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(default(T));
            }

            int startOffset       = offset;
            var serializationInfo = new SerializationInfo(typeof(T), new FormatterConverter());

            var len = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);

            offset += readSize;

            for (int i = 0; i < len; i++)
            {
                var key = MessagePackBinary.ReadString(bytes, offset, out readSize);
                offset += readSize;
                var val = ObjectFormatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                offset += readSize;

                serializationInfo.AddValue(key, val);
            }

            ISerializable   obj             = null;
            ConstructorInfo constructorInfo = typeof(T).GetConstructor(
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                new[] { typeof(SerializationInfo), typeof(StreamingContext) },
                null);

            if (constructorInfo != null)
            {
                object[] args = { serializationInfo, new StreamingContext() };
                obj = constructorInfo.Invoke(args).AsInstanceOf <ISerializable>();
            }

            readSize = offset - startOffset;
            return((T)obj);
        }
        public JsonRpcRequest?Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }

            var startOffset = offset;
            int singleReadSize;

            if (MessagePackBinary.ReadArrayHeader(bytes, offset, out singleReadSize) != 4)
            {
                throw new InvalidOperationException("Invalid JsonRpcMessage format.");
            }

            offset += singleReadSize;

            var version = MessagePackBinary.ReadString(bytes, offset, out singleReadSize);

            offset += singleReadSize;

            var id = TypelessFormatter.Instance.Deserialize(bytes, offset, formatterResolver, out singleReadSize);

            offset += singleReadSize;

            var method = MessagePackBinary.ReadString(bytes, offset, out singleReadSize);

            offset += singleReadSize;

            object?arguments;

            switch (MessagePackBinary.GetMessagePackType(bytes, offset))
            {
            case MessagePackType.Nil:
            {
                arguments = null;
                offset++;
                break;
            }

            case MessagePackType.Array:
            {
                var length = MessagePackBinary.ReadArrayHeader(bytes, offset, out singleReadSize);
                offset += singleReadSize;

                var array = new object[length];
                for (var i = 0; i < length; i++)
                {
                    array[i] = TypelessFormatter.Instance.Deserialize(bytes, offset, formatterResolver, out singleReadSize);
                    offset  += singleReadSize;
                }

                arguments = array;
                break;
            }

            case MessagePackType.Map:
            {
                var length = MessagePackBinary.ReadMapHeader(bytes, offset, out singleReadSize);
                offset += singleReadSize;

                var map = new Dictionary <string, object>(length);
                for (var i = 0; i < length; i++)
                {
                    var key = MessagePackBinary.ReadString(bytes, offset, out singleReadSize);
                    offset += singleReadSize;
                    var value = TypelessFormatter.Instance.Deserialize(bytes, offset, formatterResolver, out singleReadSize);
                    offset += singleReadSize;
                    map.Add(key, value);
                }

                arguments = map;
                break;
            }

            default:
                throw new InvalidOperationException(string.Format("Invalid code : {0}", bytes[offset]));
            }

            readSize = offset - startOffset;
            return(new JsonRpcRequest()
            {
                Version = version,
                Id = id,
                Method = method,
                Arguments = arguments,
            });
        }
예제 #15
0
        public Product Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            int     startOffset = offset;
            int     size        = 0;
            Product p           = new Product();

            _       = MessagePackBinary.ReadMapHeader(bytes, offset, out size);
            offset += size;

            string fieldName = MessagePackBinary.ReadString(bytes, offset, out size);

            offset += size;

            p.Id    = MessagePackBinary.ReadInt64(bytes, offset, out size);
            offset += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;

            p.Name  = MessagePackBinary.ReadString(bytes, offset, out size);
            offset += size;

            fieldName     = MessagePackBinary.ReadString(bytes, offset, out size);
            offset       += size;
            p.Description = MessagePackBinary.ReadString(bytes, offset, out size);
            offset       += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            p.Seller  = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            formatterResolver.GetFormatter <Category>().Deserialize(bytes, offset, formatterResolver, out size);
            offset += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            p.Rating  = formatterResolver.GetFormatter <Rate>().Deserialize(bytes, offset, formatterResolver, out size);
            offset   += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            if (bytes[offset] != 0xc0)
            {
                string  price = MessagePackBinary.ReadString(bytes, offset, out size);
                decimal priceResult;
                if (Decimal.TryParse(price, out priceResult))
                {
                    p.Price = priceResult;
                }
                ;
            }
            else
            {
                MessagePackBinary.ReadNil(bytes, offset, out size);
            }
            offset += size;

            fieldName  = MessagePackBinary.ReadString(bytes, offset, out size);
            offset    += size;
            p.Currency = MessagePackBinary.ReadString(bytes, offset, out size);
            offset    += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            p.Created = MessagePackBinary.ReadDateTime(bytes, offset, out size);
            offset   += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            if (bytes[offset] != 0xc0)
            {
                p.Updated = MessagePackBinary.ReadDateTime(bytes, offset, out size);
            }
            else
            {
                MessagePackBinary.ReadNil(bytes, offset, out size);
            }
            offset += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            p.Labels  = formatterResolver.GetFormatter <ICollection <string> >().Deserialize(bytes, offset, formatterResolver, out size);
            offset   += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            Uri uriStr = formatterResolver.GetFormatter <Uri>().Deserialize(bytes, offset, formatterResolver, out size);

            p.Location = uriStr;
            offset    += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;
            p.Image   = MessagePackBinary.ReadBytes(bytes, offset, out size);
            offset   += size;

            fieldName = MessagePackBinary.ReadString(bytes, offset, out size);
            offset   += size;

            p.Details = formatterResolver.GetFormatter <Dictionary <string, string> >().Deserialize(bytes, offset, formatterResolver, out size);
            offset   += size;

            readSize = offset - startOffset;
            return(p);
        }
예제 #16
0
        public object Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            var type = MessagePackBinary.GetMessagePackType(bytes, offset);

            switch (type)
            {
            case MessagePackType.Integer:
                var code = bytes[offset];
                if (MessagePackCode.MinNegativeFixInt <= code && code <= MessagePackCode.MaxNegativeFixInt)
                {
                    return(MessagePackBinary.ReadSByte(bytes, offset, out readSize));
                }
                else if (MessagePackCode.MinFixInt <= code && code <= MessagePackCode.MaxFixInt)
                {
                    return(MessagePackBinary.ReadByte(bytes, offset, out readSize));
                }
                else if (code == MessagePackCode.Int8)
                {
                    return(MessagePackBinary.ReadSByte(bytes, offset, out readSize));
                }
                else if (code == MessagePackCode.Int16)
                {
                    return(MessagePackBinary.ReadInt16(bytes, offset, out readSize));
                }
                else if (code == MessagePackCode.Int32)
                {
                    return(MessagePackBinary.ReadInt32(bytes, offset, out readSize));
                }
                else if (code == MessagePackCode.Int64)
                {
                    return(MessagePackBinary.ReadInt64(bytes, offset, out readSize));
                }
                else if (code == MessagePackCode.UInt8)
                {
                    return(MessagePackBinary.ReadByte(bytes, offset, out readSize));
                }
                else if (code == MessagePackCode.UInt16)
                {
                    return(MessagePackBinary.ReadUInt16(bytes, offset, out readSize));
                }
                else if (code == MessagePackCode.UInt32)
                {
                    return(MessagePackBinary.ReadUInt32(bytes, offset, out readSize));
                }
                else if (code == MessagePackCode.UInt64)
                {
                    return(MessagePackBinary.ReadUInt64(bytes, offset, out readSize));
                }
                throw new InvalidOperationException("Invalid primitive bytes.");

            case MessagePackType.Boolean:
                return(MessagePackBinary.ReadBoolean(bytes, offset, out readSize));

            case MessagePackType.Float:
                if (MessagePackCode.Float32 == bytes[offset])
                {
                    return(MessagePackBinary.ReadSingle(bytes, offset, out readSize));
                }
                else
                {
                    return(MessagePackBinary.ReadDouble(bytes, offset, out readSize));
                }

            case MessagePackType.String:
                return(MessagePackBinary.ReadString(bytes, offset, out readSize));

            case MessagePackType.Binary:
                return(MessagePackBinary.ReadBytes(bytes, offset, out readSize));

            case MessagePackType.Extension:
                var ext = MessagePackBinary.ReadExtensionFormatHeader(bytes, offset, out readSize);
                if (ext.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime)
                {
                    return(MessagePackBinary.ReadDateTime(bytes, offset, out readSize));
                }
                throw new InvalidOperationException("Invalid primitive bytes.");

            case MessagePackType.Array:
            {
                var length      = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize);
                var startOffset = offset;
                offset += readSize;

                var objectFormatter = formatterResolver.GetFormatter <object>();
                var array           = new object[length];
                for (int i = 0; i < length; i++)
                {
                    array[i] = objectFormatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset  += readSize;
                }

                readSize = offset - startOffset;
                return(array);
            }

            case MessagePackType.Map:
            {
                var length      = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);
                var startOffset = offset;
                offset += readSize;

                var objectFormatter = formatterResolver.GetFormatter <object>();
                var hash            = new Dictionary <object, object>(length);
                for (int i = 0; i < length; i++)
                {
                    var key = objectFormatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;

                    var value = objectFormatter.Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;

                    hash.Add(key, value);
                }

                readSize = offset - startOffset;
                return(hash);
            }

            case MessagePackType.Nil:
                readSize = 1;
                return(null);

            default:
                throw new InvalidOperationException("Invalid primitive bytes.");
            }
        }
예제 #17
0
        /// <inheritdoc />
        public HttpRequestMessage Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }

            int startOffset = offset;

            int count = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize);

            offset += readSize;
            if (count != 5)
            {
                throw new InvalidOperationException("Request format invalid.");
            }

            // RequestPart.Version:
            string versionStr = MessagePackBinary.ReadString(bytes, offset, out readSize);

            offset += readSize;
            if (!Version.TryParse(versionStr, out Version version))
            {
                throw new InvalidOperationException($"Request version '{versionStr}' in invalid format!");
            }

            // RequestPart.UriScheme:
            string uriStr = MessagePackBinary.ReadString(bytes, offset, out readSize);

            offset += readSize;
            if (!Uri.TryCreate(uriStr, UriKind.Absolute, out Uri uri))
            {
                throw new InvalidOperationException($"Request Uri '{uri}' could not be parsed");
            }

            // RequestPart.Method:
            HttpMethod method = HttpMethodFormatter.Instance.Deserialize(bytes, offset, formatterResolver, out readSize);

            offset += readSize;

            // Create request so we can add headers and content
            HttpRequestMessage request = new HttpRequestMessage(method, uri)
            {
                Version = version
            };

            // RequestPart.Headers:
            int headersCount = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);

            offset += readSize;

            if (headersCount > 0)
            {
                while (headersCount-- > 0)
                {
                    string key = MessagePackBinary.ReadString(bytes, offset, out readSize);
                    offset += readSize;

                    int valuesCount = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize);
                    offset += readSize;

                    // Note, we can't have an empty array, and if we tried adding one it would be ignored anyway
                    // therefore it's safe to just start looping and call add for each entry.
                    while (valuesCount-- > 0)
                    {
                        string headerValue = MessagePackBinary.ReadString(bytes, offset, out readSize);
                        offset += readSize;

                        request.Headers.TryAddWithoutValidation(key, headerValue);
                    }
                }
            }

            // RequestPart.Content:
#pragma warning disable DF0023 // Marks undisposed objects assinged to a property, originated from a method invocation.
            request.Content = HttpContentFormatter.Deserialize(bytes, offset, out readSize);
#pragma warning restore DF0023 // Marks undisposed objects assinged to a property, originated from a method invocation.

            offset += readSize;

            readSize = offset - startOffset;

            return(request);
        }
        public void Read()
        {
            void Check1 <T, T2>(T data, T2 result, Func <Stream, T2> streamRead)
            {
                const int CheckOffset = 10;

                byte[] bytes = null;
                var    len   = MessagePack.Resolvers.StandardResolver.Instance.GetFormatter <T>().Serialize(ref bytes, CheckOffset, data, MessagePack.Resolvers.StandardResolver.Instance);

                MessagePackBinary.FastResize(ref bytes, CheckOffset + len);


                var ms = new MemoryStream(bytes);

                ms.Position = CheckOffset;

                streamRead(ms).Is(result);
            }

            void Check2 <T>(T data, Func <Stream, T> streamRead)
            {
                const int CheckOffset = 10;

                byte[] bytes = null;
                var    len   = MessagePack.Resolvers.StandardResolver.Instance.GetFormatter <T>().Serialize(ref bytes, CheckOffset, data, MessagePack.Resolvers.StandardResolver.Instance);

                MessagePackBinary.FastResize(ref bytes, CheckOffset + len);


                var ms = new MemoryStream(bytes);

                ms.Position = CheckOffset;

                streamRead(ms).Is(data);
            }

            Check1(new[] { 1, 10, 100, 1000, 10000, short.MaxValue, int.MaxValue }, 7, x => MessagePackBinary.ReadArrayHeader(x));
            Check1(new[] { 1, 10, 100, 1000, 10000, short.MaxValue, int.MaxValue }, (uint)7, x => MessagePackBinary.ReadArrayHeaderRaw(x));
            Check1(Nil.Default, true, x => MessagePackBinary.IsNil((x)));
            Check2(true, x => MessagePackBinary.ReadBoolean(x));
            Check2((byte)100, x => MessagePackBinary.ReadByte(x));
            Check2(new byte[] { 1, 10, 100, 245 }, x => MessagePackBinary.ReadBytes(x));
            Check2('あ', x => MessagePackBinary.ReadChar(x));
            Check2(DateTime.UtcNow, x => MessagePackBinary.ReadDateTime(x));
            Check2(132, x => MessagePackBinary.ReadInt16(x));
            Check2(423, x => MessagePackBinary.ReadInt32(x));
            Check2(64332, x => MessagePackBinary.ReadInt64(x));
            Check2(Nil.Default, x => MessagePackBinary.ReadNil(x));
            Check2(11, x => MessagePackBinary.ReadSByte(x));
            Check2(10.31231f, x => MessagePackBinary.ReadSingle(x));
            Check2("foobar", x => MessagePackBinary.ReadString(x));
            Check2(124, x => MessagePackBinary.ReadUInt16(x));
            Check2((uint)432, x => MessagePackBinary.ReadUInt32(x));
            Check2((ulong)432, x => MessagePackBinary.ReadUInt64(x));


            Check1(new Dictionary <int, int>()
            {
                { 1, 2 }
            }, 1, x => MessagePackBinary.ReadMapHeader(x));
            Check1(new Dictionary <int, int>()
            {
                { 1, 2 }
            }, (uint)1, x => MessagePackBinary.ReadMapHeaderRaw(x));

            {
                var block  = new object[] { 1, new[] { 1, 10, 100 }, 100 };
                var bytes  = MessagePackSerializer.Serialize(block);
                var stream = new MemoryStream(bytes);
                MessagePackBinary.ReadNext(stream);      // array(first)
                MessagePackBinary.ReadNext(stream);      // int
                MessagePackBinary.ReadNextBlock(stream); // skip array
                MessagePackBinary.ReadInt32(stream).Is(100);
            }
            {
                var block = new object[] { 1, new Dictionary <int, int> {
                                               { 1, 10 }, { 111, 200 }
                                           }, 100 };
                var bytes  = MessagePackSerializer.Serialize(block);
                var stream = new MemoryStream(bytes);
                MessagePackBinary.ReadNext(stream);
                MessagePackBinary.ReadNext(stream);
                MessagePackBinary.ReadNextBlock(stream);
                MessagePackBinary.ReadInt32(stream).Is(100);
            }
        }
예제 #19
0
        /// <summary>
        /// Deserializes the content into the specified response.
        /// </summary>
        /// <param name="bytes">The bytes.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="readSize">Size of the read.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">Content format invalid.</exception>
        public static HttpContent Deserialize(byte[] bytes, int offset, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }

            int startOffset = offset;

            int count = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize);

            offset += readSize;
            if (count != 3)
            {
                throw new InvalidOperationException("Content format invalid.");
            }

            // Type
            byte typeByte = MessagePackBinary.ReadByte(bytes, offset, out readSize);

            offset += readSize;

            // Headers
            Dictionary <string, string[]> headers = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);

            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize++;
            }
            else
            {
                int headersCount = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);
                offset += readSize;

                if (headersCount > 0)
                {
                    while (headersCount-- > 0)
                    {
                        string key = MessagePackBinary.ReadString(bytes, offset, out readSize);
                        offset += readSize;


                        int valuesCount = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize);
                        offset += readSize;

                        string[] values = new string[valuesCount];

                        // Note, we can't have an empty array, and if we tried adding one it would be ignored anyway
                        // therefore it's safe to just start looping and call add for each entry.
                        for (int i = 0; i < valuesCount; i++)
                        {
                            string headerValue = MessagePackBinary.ReadString(bytes, offset, out readSize);
                            offset += readSize;

                            values[i] = headerValue;
                        }

                        headers[key] = values;
                    }
                }
            }

            // Get data
            byte[]      data = MessagePackBinary.ReadBytes(bytes, offset, out readSize);
            HttpContent content;

            switch (typeByte)
            {
            // StreamContent
            case 1:
#pragma warning disable DF0000 // Marks undisposed anonymous objects from object creations.
                content = new StreamContent(new MemoryStream(data));
#pragma warning restore DF0000 // Marks undisposed anonymous objects from object creations.
                break;

            /*
             *  TODO
             * case 2:
             *  // See https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/FormUrlEncodedContent.cs
             *  string encoded = Encoding.UTF8.GetString(data).Replace("+", "%20");
             *  List<KeyValuePair<string, string>> nvc = new List<KeyValuePair<string, string>>();
             *  int start = 0;
             *  do
             *  {
             *
             *  } while ()
             *
             *
             *  break;
             */

            case 3:
                // See https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/StringContent.cs
                // Get encoding from headers if possible
                Encoding encoding;
                string   charSet;
                if (headers.TryGetValue("content-type", out string[] ctValues) &&
예제 #20
0
        /// <inheritdoc />
        public HttpResponseMessage Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }

            int startOffset = offset;

            int count = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize);

            offset += readSize;
            if (count != 5)
            {
                throw new InvalidOperationException("Response format invalid.");
            }

            // Version
            string versionStr = MessagePackBinary.ReadString(bytes, offset, out readSize);

            offset += readSize;
            if (!Version.TryParse(versionStr, out Version version))
            {
                throw new InvalidOperationException($"Response version '{versionStr}' in invalid format!");
            }

            // Status Code
            HttpStatusCode statusCode = (HttpStatusCode)MessagePackBinary.ReadUInt16(bytes, offset, out readSize);

            offset += readSize;

            // ReasonPhrase
            string reasonPhrase = MessagePackBinary.ReadString(bytes, offset, out readSize);

            offset += readSize;

            // Create response so we can start updating it's headers
            HttpResponseMessage response = new HttpResponseMessage(statusCode)
            {
                Version      = version,
                ReasonPhrase = reasonPhrase
            };

            // Headers
            int headersCount = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);

            offset += readSize;

            if (headersCount > 0)
            {
                while (headersCount-- > 0)
                {
                    string key = MessagePackBinary.ReadString(bytes, offset, out readSize);
                    offset += readSize;

                    int valuesCount = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize);
                    offset += readSize;

                    // Note, we can't have an empty array, and if we tried adding one it would be ignored anyway
                    // therefore it's safe to just start looping and call add for each entry.
                    while (valuesCount-- > 0)
                    {
                        string headerValue = MessagePackBinary.ReadString(bytes, offset, out readSize);
                        offset += readSize;

                        response.Headers.TryAddWithoutValidation(key, headerValue);
                    }
                }
            }

            // Content
#pragma warning disable DF0023 // Marks undisposed objects assinged to a property, originated from a method invocation.
            response.Content = HttpContentFormatter.Deserialize(bytes, offset, out readSize);
#pragma warning restore DF0023 // Marks undisposed objects assinged to a property, originated from a method invocation.

            readSize = offset - startOffset;
            return(response);
        }
예제 #21
0
        public static object ReadObject(byte[] input, ref int offset)
        {
            var type = MessagePackBinary.GetMessagePackType(input, offset);
            int size;

            switch (type)
            {
            case MessagePackType.Integer:
                var intValue = MessagePackBinary.ReadInt64(input, offset, out size);
                offset += size;
                return(intValue);

            case MessagePackType.Nil:
                MessagePackBinary.ReadNil(input, offset, out size);
                offset += size;
                return(null);

            case MessagePackType.Boolean:
                var boolValue = MessagePackBinary.ReadBoolean(input, offset, out size);
                offset += size;
                return(boolValue);

            case MessagePackType.Float:
                var doubleValue = MessagePackBinary.ReadDouble(input, offset, out size);
                offset += size;
                return(doubleValue);

            case MessagePackType.String:
                var textValue = MessagePackBinary.ReadString(input, offset, out size);
                offset += size;
                return(textValue);

            case MessagePackType.Binary:
                var binaryValue = MessagePackBinary.ReadBytes(input, offset, out size);
                offset += size;
                return(binaryValue);

            case MessagePackType.Array:
                var argumentCount = ReadArrayLength(input, ref offset, "arguments");
                var array         = new object[argumentCount];
                for (int i = 0; i < argumentCount; i++)
                {
                    array[i] = ReadObject(input, ref offset);
                }
                return(array);

            case MessagePackType.Map:
                var propertyCount = MessagePackBinary.ReadMapHeader(input, offset, out size);
                offset += size;
                var map = new Dictionary <string, object>();
                for (int i = 0; i < propertyCount; i++)
                {
                    textValue = MessagePackBinary.ReadString(input, offset, out size);
                    offset   += size;
                    var value = ReadObject(input, ref offset);
                    map[textValue] = value;
                }
                return(map);

            case MessagePackType.Extension:
            case MessagePackType.Unknown:
            default:
                return(null);
            }
        }
        public DataDictionary Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }
            var startOffset = offset;
            var len         = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);

            offset += readSize;
            var dic = new DataDictionary();

            for (int i = 0; i < len; i++)
            {
                var key = MessagePackBinary.ReadString(bytes, offset, out readSize);
                offset += readSize;
                switch (key)
                {
                case Event.KnownDataKeys.EnvironmentInfo: {
                    var value = formatterResolver.GetFormatter <EnvironmentInfo>().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.Error: {
                    var value = formatterResolver.GetFormatter <Error>().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.Level: {
                    var value = MessagePackBinary.ReadString(bytes, offset, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.ManualStackingInfo: {
                    var value = formatterResolver.GetFormatter <ManualStackingInfo>().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.RequestInfo: {
                    var value = formatterResolver.GetFormatter <RequestInfo>().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.SimpleError: {
                    var value = formatterResolver.GetFormatter <SimpleError>().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.SubmissionMethod: {
                    var value = MessagePackBinary.ReadString(bytes, offset, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.TraceLog: {
                    var value = formatterResolver.GetFormatter <List <string> >().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.UserDescription: {
                    var value = formatterResolver.GetFormatter <UserDescription>().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.UserInfo: {
                    var value = formatterResolver.GetFormatter <UserInfo>().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

                case Event.KnownDataKeys.Version: {
                    var value = MessagePackBinary.ReadString(bytes, offset, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }

#if NETSTANDARD
                case "ProcessArchitecture": {
                    var value = MessagePackBinary.ReadInt32(bytes, offset, out readSize);
                    offset += readSize;
                    dic.Add(key, (System.Runtime.InteropServices.Architecture)value);
                    break;
                }
#endif
                default: {
                    var value = formatterResolver.GetFormatter <object>().Deserialize(bytes, offset, formatterResolver, out readSize);
                    offset += readSize;
                    dic.Add(key, value);
                    break;
                }
                }
            }
            readSize = offset - startOffset;
            return(dic);
        }
예제 #23
0
        public unsafe Dup Deserialize(byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            if (MessagePackBinary.IsNil(bytes, offset))
            {
                readSize = 1;
                return(null);
            }

            var startOffset = offset;

            var len = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);

            offset += readSize;


            int aBCDEFGH     = 0;
            int aBCDEFGHIJKL = 0;
            int aBCDEFGHIJKO = 0;

            // ---isStringKey

            ulong key;
            ArraySegment <byte> arraySegment;
            byte *p;
            int   rest;

            fixed(byte *buffer = &bytes[0])
            {
                for (int i = 0; i < len; i++)
                {
                    arraySegment = MessagePackBinary.ReadStringSegment(bytes, offset, out readSize);
                    offset      += readSize;

                    p    = buffer + arraySegment.Offset;
                    rest = arraySegment.Count;

                    if (rest == 0)
                    {
                        goto LOOP_END;
                    }

                    key = AutomataKeyGen.GetKey(ref p, ref rest);
                    if (rest == 0)
                    {
                        if (key == 5208208757389214273L)
                        {
                            aBCDEFGH = MessagePackBinary.ReadInt32(bytes, offset, out readSize);
                            goto LOOP_END;
                        }

                        goto READ_NEXT;
                    }

                    if (key == 5208208757389214273L)
                    {
                        key = AutomataKeyGen.GetKey(ref p, ref rest);
                        if (rest == 0)
                        {
                            if (key == 1280002633L)
                            {
                                aBCDEFGHIJKL = MessagePackBinary.ReadInt32(bytes, offset, out readSize);
                                goto LOOP_END;
                            }

                            if (key == 1330334281L)
                            {
                                aBCDEFGHIJKO = MessagePackBinary.ReadInt32(bytes, offset, out readSize);
                                goto LOOP_END;
                            }
                        }
                    }

READ_NEXT:
                    readSize = MessagePackBinary.ReadNextBlock(bytes, offset);

LOOP_END:
                    offset += readSize;
                    continue;
                }
            }

            // --- end

            return(new Dup
            {
                ABCDEFGH = aBCDEFGH,
                ABCDEFGHIJKL = aBCDEFGHIJKL,
                ABCDEFGHIJKO = aBCDEFGHIJKO
            });
        }
        internal static object Deserialize(ObjectSerializationInfo metaInfo, ObjectSerializationInfo.EmittableMember[] readMembers, int[] constructorParameterIndexes, AutomataDictionary mapMemberDictionary, byte[] bytes, int offset, IFormatterResolver formatterResolver, out int readSize)
        {
            var startOffset = offset;

            object[] parameters = null;

            var headerType = MessagePackBinary.GetMessagePackType(bytes, offset);

            if (headerType == MessagePackType.Nil)
            {
                readSize = 1;
                return(null);
            }
            else if (headerType == MessagePackType.Array)
            {
                var arraySize = MessagePackBinary.ReadArrayHeader(bytes, offset, out readSize);
                offset += readSize;

                // ReadValues
                parameters = new object[arraySize];
                for (int i = 0; i < arraySize; i++)
                {
                    var info = readMembers[i];
                    if (info != null)
                    {
                        parameters[i] = MessagePackSerializer.NonGeneric.Deserialize(info.Type, bytes, offset, formatterResolver, out readSize);
                        offset       += readSize;
                    }
                    else
                    {
                        offset += MessagePackBinary.ReadNextBlock(bytes, offset);
                    }
                }
            }
            else if (headerType == MessagePackType.Map)
            {
                var mapSize = MessagePackBinary.ReadMapHeader(bytes, offset, out readSize);
                offset += readSize;

                // ReadValues
                parameters = new object[mapSize];
                for (int i = 0; i < mapSize; i++)
                {
                    var rawPropName = MessagePackBinary.ReadStringSegment(bytes, offset, out readSize);
                    offset += readSize;

                    int index;
                    if (mapMemberDictionary.TryGetValue(rawPropName.Array, rawPropName.Offset, rawPropName.Count, out index))
                    {
                        var info = readMembers[index];
                        parameters[index] = MessagePackSerializer.NonGeneric.Deserialize(info.Type, bytes, offset, formatterResolver, out readSize);
                        offset           += readSize;
                    }
                    else
                    {
                        offset += MessagePackBinary.ReadNextBlock(bytes, offset);
                    }
                }
            }
            else
            {
                throw new InvalidOperationException("Invalid MessagePackType:" + MessagePackCode.ToFormatName(bytes[offset]));
            }

            // CreateObject
            object result = null;

            if (constructorParameterIndexes.Length == 0)
            {
                result = Activator.CreateInstance(metaInfo.Type);
            }
            else
            {
                var args = new object[constructorParameterIndexes.Length];
                for (int i = 0; i < constructorParameterIndexes.Length; i++)
                {
                    args[i] = parameters[constructorParameterIndexes[i]];
                }

                result = Activator.CreateInstance(metaInfo.Type, args);
            }

            // SetMembers
            for (int i = 0; i < readMembers.Length; i++)
            {
                var info = readMembers[i];
                if (info != null)
                {
                    info.ReflectionStoreValue(result, parameters[i]);
                }
            }

            readSize = offset - startOffset;
            return(result);
        }