Beispiel #1
0
        public void LegacyConverter()
        {
            var con = new Dictionary <Type, IPacketConverter>()
            {
                [typeof(TestTwo)] = new TestTwoConverter(),
                [typeof(TestBox)] = new TestBoxConverter(),
            };
            var obj = new
            {
                a = Enumerable.Range(0, 4).Select(r => new TestTwo {
                    One = r, Two = r * 2
                }),
                b = Enumerable.Range(0, 8).ToDictionary(r => r.ToString(), r => new TestTwo {
                    One = r * 2, Two = r * 4
                }),
                x = Enumerable.Range(0, 2)
                    .Select(t =>
                            Enumerable.Range(0, 4).Select(r =>
                                                          new TestBox {
                    Name = $"{t}:{r}"
                }))
                    .ToList(),
            };
            var buf = PacketConvert.Serialize(obj, con);
            var rea = new PacketReader(buf, con);
            var itr = rea["a"].GetEnumerable <TestTwo>();

            var oc  = new TestTuple();
            var c   = oc.ToDictionary(r => r.Key, r => r.Value);
            var kvp = PacketWriter.Serialize(oc);
            var tc  = kvp.GetBytes();

            var ra = itr.ToList();
            var rb = rea["b"].GetDictionary <string, TestTwo>();
            var rc = PacketConvert.Deserialize <IDictionary <int, string> >(tc);
            var rx = rea["x"].Deserialize <TestBox[][]>();

            var od = new[] { new TestBox {
                                 Name = "one"
                             }, new TestBox {
                                 Name = "Loooooooooooooong name!"
                             }, new TestBox {
                                 Name = "what?"
                             } };
            var td  = PacketConvert.Serialize(od, con);
            var rd  = PacketConvert.Deserialize <IEnumerable <TestBox> >(td, con);
            var rdx = PacketConvert.Deserialize <TestBox[]>(td, con);
            var rdy = PacketConvert.Deserialize <List <TestBox> >(td, con);

            var rax = rea["a"].Deserialize <TestTwo[]>();
            var ray = rea["a"].Deserialize <List <TestTwo> >();

            ThrowIfNotEqual(c, rc);
            ThrowIfNotSequenceEqual(od, rd);
            ThrowIfNotSequenceEqual(od, rdx);
            ThrowIfNotSequenceEqual(od, rdy);
            ThrowIfNotSequenceEqual(obj.a, rax);
            ThrowIfNotSequenceEqual(obj.a, ray);
            return;
        }
Beispiel #2
0
        public void SerializeCollection()
        {
            var a = new byte[] { 1, 3, 5, 7 };
            var b = new sbyte[] { -6, -3, 0, 3, 6, 9 };
            var c = new List <byte> {
                192, 128, 64, 0
            };
            var d = new List <sbyte> {
                -14, -7, 0, 7, 14, 21
            };
            var e = new long[] { 0x123456789ABCDEF, 0xFF512429871224, 0x7513A45272CE5B8 };
            var f = new ulong[] { 0xFEDCBA987654321, 0xFB58412A0C8E5 };

            var obj = new
            {
                a,
                b,
                sub = new { c, d, e, f },
            };

            var buf = PacketConvert.Serialize(obj);
            var val = PacketConvert.Deserialize(buf, obj);

            ThrowIfNotSequenceEqual(a, val.a);
            ThrowIfNotSequenceEqual(b, val.b);
            ThrowIfNotSequenceEqual(c, val.sub.c);
            ThrowIfNotSequenceEqual(d, val.sub.d);
            ThrowIfNotSequenceEqual(e, val.sub.e);
            ThrowIfNotSequenceEqual(f, val.sub.f);
        }
Beispiel #3
0
        public void CollectionWithAddFunction()
        {
            var random = new Random();

            TestAddOnlyList <T> ToAddOnlyList <T>(IEnumerable <T> enumerable)
            {
                var list = new TestAddOnlyList <T>();

                foreach (var i in enumerable)
                {
                    list.Add(i);
                }
                return(list);
            }

            var xa = Enumerable.Range(0, 4).Select(r => random.Next()).ToArray();
            var la = ToAddOnlyList(xa);
            var ta = PacketConvert.Serialize(la);
            var ra = PacketConvert.Deserialize <TestAddOnlyList <int> >(ta);

            ThrowIfNotSequenceEqual(ra, xa);

            var xb = Enumerable.Range(0, 4).Select(r => new { id = random.Next(), text = random.Next().ToString("x") }).ToArray();
            var lb = ToAddOnlyList(xb);
            var tb = PacketConvert.Serialize(lb);
            var rb = PacketConvert.Deserialize(tb, lb);

            ThrowIfNotSequenceEqual(rb, xb);
            return;
        }
Beispiel #4
0
public void Nest()
{
    var a = new List <List <int> > {
        new List <int> {
            1, 2
        }, new List <int> {
            3, 4, 5
        }
    };
    var wtr = PacketWriter.Serialize(a);
    var ta  = wtr.GetBytes();

    var b   = Enumerable.Range(128, 1).Select(r => new { id = r, text = r.ToString() });
    var ano = PacketWriter.Serialize(b);
    var tb  = ano.GetBytes();

    var rea = new PacketReader(ta);
    var ra  = rea.Deserialize <IEnumerable <List <int> > >().ToList();
    var rb  = PacketConvert.Deserialize(tb, new[] { new { id = 0, text = string.Empty } }.ToHashSet());

    var c   = Enumerable.Range(128, 2).ToDictionary(r => r, r => new { id = r, text = r.ToString() });
    var dic = PacketWriter.Serialize(c);
    var tc  = dic.GetBytes();
    var rc  = PacketConvert.Deserialize(tc, new[] { new { id = 0, text = string.Empty } }.ToDictionary(r => r.id));

    Assert.AreEqual(a.Count, ra.Count);

    for (int i = 0; i < ra.Count; i++)
    {
        ThrowIfNotSequenceEqual(a[i], ra[i]);
    }
    ThrowIfNotEqual(b.ToHashSet(), rb);
    ThrowIfNotEqual(c, rc);
    return;
}
Beispiel #5
0
        public void SerializeCollection()
        {
            var a = new byte[] { 1, 3, 5, 7 };
            var b = new sbyte[] { -6, -3, 0, 3, 6, 9 };
            var c = new List <byte> {
                192, 128, 64, 0
            };
            var d = new List <sbyte> {
                -14, -7, 0, 7, 14, 21
            };

            var obj = new
            {
                a,
                b,
                sub = new { c, d },
            };

            var buf = PacketConvert.Serialize(obj);
            var val = PacketConvert.Deserialize(buf, obj);

            ThrowIfNotSequenceEqual(a, val.a);
            ThrowIfNotSequenceEqual(b, val.b);
            ThrowIfNotSequenceEqual(c, val.sub.c);
            ThrowIfNotSequenceEqual(d, val.sub.d);
        }
Beispiel #6
0
public void NestDictionary()
{
    var a = new[] { new { id = 1, text = "alpha" }, new { id = 2, text = "beta" } }.ToDictionary(r => r.id);
    var b = new[] { new { key = "m", value = 1.1 }, new { key = "n", value = 2.2 } }.ToDictionary(r => r.key);
    var wa  = PacketWriter.Serialize(a);
    var wb  = PacketWriter.Serialize(b);
    var wtr = new PacketWriter().SetItem("alpha", wa).SetItem("beta", wb);
    var buf = wtr.GetBytes();
    var rea = new PacketReader(buf);
    var obj = rea.Deserialize(new { alpha = a, beta = b });

    ThrowIfNotEqual(a, obj.alpha);
    ThrowIfNotEqual(b, obj.beta);

    var src = new PacketWriter();
    var dyn = (dynamic)src;

    dyn.x = wa;
    dyn.y = wb;
    var tmp = src.GetBytes();
    var res = PacketConvert.Deserialize(tmp, new { x = a, y = b });

    ThrowIfNotEqual(a, res.x);
    ThrowIfNotEqual(b, res.y);

    var c = new[] { new { x = 1, y = "a" } }.ToList();
    var tc = PacketConvert.Serialize(c);
    var ra = PacketConvert.Deserialize(tc, c);

    return;
}
Beispiel #7
0
        internal static void Main(string[] args)
        {
            var port   = new Random().Next(40000, 50000);
            var server = new UdpClient(port);

            server.BeginReceive(r =>
            {
                var endpoint = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort);
                var bytes    = server.EndReceive(r, ref endpoint);

                // Deserialize anonymous object
                var value = PacketConvert.Deserialize(bytes, new
                {
                    id   = 0,
                    name = string.Empty,
                    data = new
                    {
                        token     = Guid.Empty,
                        timestamp = DateTime.MinValue
                    }
                });

                Console.WriteLine($"message from : {endpoint}");
                Console.WriteLine($"id : {value.id}");
                Console.WriteLine($"name : {value.name}");
                Console.WriteLine($"token : {value.data.token}");
                Console.WriteLine($"timestamp : {value.data.timestamp:u}");
                Console.WriteLine();
            }, null);

            // Serialize an anonymous object.
            var buffer = PacketConvert.Serialize(new
            {
                id   = 1,
                name = "sharp",
                data = new
                {
                    token     = Guid.NewGuid(),
                    timestamp = DateTime.Now,
                }
            });

            var client = new UdpClient();

            client.Send(buffer, buffer.Length, new IPEndPoint(IPAddress.Loopback, port));
            Thread.Sleep(1000);

            // More samples, see unit test.
            Performance.DoWork();
        }
Beispiel #8
0
        public void ISet()
        {
            var set = new HashSet <int>()
            {
                1, 2, 3, 4
            };
            var buf = PacketConvert.Serialize(set);
            var res = PacketConvert.Deserialize <HashSet <int> >(buf);
            var val = set.SetEquals(res);

            Assert.AreEqual(set.Count, res.Count);
            Assert.AreEqual(val, true);
            return;
        }
Beispiel #9
0
        public void DeserializePartial()
        {
            const int margin = 10;
            var       obj    = new { alpha = 1, beta = "two" };
            var       buf    = PacketConvert.Serialize(obj);
            var       tmp    = new byte[buf.Length + margin * 2];

            Buffer.BlockCopy(buf, 0, tmp, margin, buf.Length);

            var res = PacketConvert.Deserialize(tmp, margin, buf.Length, new { alpha = 0, beta = string.Empty });

            Assert.AreEqual(obj.alpha, res.alpha);
            Assert.AreEqual(obj.beta, res.beta);
            return;
        }
Beispiel #10
0
        public void DynamicObjectArray()
        {
            var source = Enumerable.Range(0, 16).Select(x => new { id = x, name = $"{x:x2}" }).ToArray();
            var buffer = PacketConvert.Serialize(source);
            var result = PacketConvert.Deserialize <byte[][]>(buffer).Select(x => (dynamic) new PacketReader(x)).ToArray();

            for (var i = 0; i < result.Length; i++)
            {
                var item = result[i];
                var id   = (int)item.id;
                var name = (string)item.name;
                Assert.AreEqual(source[i].id, id);
                Assert.AreEqual(source[i].name, name);
            }
        }
Beispiel #11
0
        internal static async Task Main(string[] args)
        {
            var port   = new Random().Next(40000, 50000);
            var server = new UdpClient(port);

            _ = Task.Run(async() =>
            {
                while (true)
                {
                    var result = await server.ReceiveAsync();
                    var value  = PacketConvert.Deserialize(result.Buffer, anonymous: new
                    {
                        id   = default(int),
                        name = default(string),
                        data = new
                        {
                            token    = default(Guid),
                            datetime = default(DateTime)
                        }
                    });

                    var message =
                        $"message from : {result.RemoteEndPoint}" + Environment.NewLine +
                        $"id : {value.id}" + Environment.NewLine +
                        $"name : {value.name}" + Environment.NewLine +
                        $"token : {value.data.token}" + Environment.NewLine +
                        $"datetime : {value.data.datetime:u}" + Environment.NewLine;
                    Console.WriteLine(message);
                }
            });

            var buffer = PacketConvert.Serialize(new
            {
                id   = 1,
                name = "sharp",
                data = new
                {
                    token    = Guid.NewGuid(),
                    datetime = DateTime.Now,
                }
            });

            var client = new UdpClient();

            _ = await client.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Loopback, port));

            await Task.Delay(Timeout.Infinite);
        }
Beispiel #12
0
        public void ISet()
        {
            var random = new Random();
            var set    = new HashSet <int>(Enumerable.Range(0, 16).Select(_ => random.Next()));
            var buf    = PacketConvert.Serialize(set);
            var res    = PacketConvert.Deserialize <HashSet <int> >(buf);

            Assert.AreEqual(set.Count, res.Count);
            Assert.IsTrue(set.SetEquals(res));

            var obj = new { set = (ISet <string>) new HashSet <string>(Enumerable.Range(0, 16).Select(_ => random.Next().ToString())) };
            var ta  = PacketConvert.Serialize(obj);
            var rea = new PacketReader(ta);
            var ra  = rea["set"].Deserialize <ISet <string> >();

            ThrowIfNotEqual(obj.set, ra);
        }
Beispiel #13
0
        public void Collection()
        {
            var arr = Enumerable.Range(0, 8).Select(r => new TestIndex {
                Id = r, Name = r.ToString()
            }).ToArray();
            var buf = PacketConvert.Serialize(arr);
            var rs  = PacketConvert.Deserialize <PacketReader[]>(buf);
            var rr  = PacketConvert.Deserialize <PacketRawReader[]>(buf);
            var ra  = PacketConvert.Deserialize <TestIndex[]>(buf);
            var rl  = PacketConvert.Deserialize <List <TestIndex> >(buf);
            var ri  = PacketConvert.Deserialize <IList <TestIndex> >(buf);
            var rc  = PacketConvert.Deserialize <ICollection <TestIndex> >(buf);

            ThrowIfNotSequenceEqual(arr, ra);
            ThrowIfNotSequenceEqual(arr, rl);
            ThrowIfNotSequenceEqual(arr, ri);
            ThrowIfNotSequenceEqual(arr, rc);
            return;
        }
Beispiel #14
0
        public void DynamicObjectArray()
        {
            var target = Enumerable.Range(0, 16).Select(x => (dynamic) new PacketWriter()).ToArray();

            for (var i = 0; i < target.Length; i++)
            {
                var writer = target[i];
                writer.id        = i;
                writer.body.name = $"{i:d2}";
            }
            var buffer = PacketConvert.Serialize(target.Cast <PacketWriter>());
            var result = PacketConvert.Deserialize(buffer, anonymous: new[] { new { id = 0, body = new { name = (string)null } } });

            Assert.AreEqual(16, result.Length);
            for (var i = 0; i < result.Length; i++)
            {
                var item = result[i];
                Assert.IsNotNull(item);
                Assert.AreEqual(i, item.id);
                Assert.AreEqual($"{i:d2}", item.body.name);
            }
        }
Beispiel #15
0
        public void HashSet()
        {
            var a = new HashSet <byte>()
            {
                1, 128, 255
            };
            var b = new HashSet <string>()
            {
                "a", "beta", "candy", "dave"
            };

            var ta = PacketConvert.Serialize(a);
            var tb = new PacketWriter().SetEnumerable("b", b).GetBytes();

            var ra  = PacketConvert.Deserialize <HashSet <byte> >(ta);
            var rea = new PacketReader(tb);
            var rb  = rea["b"].GetHashSet <string>();

            ThrowIfNotEqual(a, ra);
            ThrowIfNotEqual(b, rb);
            return;
        }
Beispiel #16
0
        public void EmptyCollection()
        {
            var obj = new
            {
                array   = new int[0],
                bytes   = new byte[0],
                sbytes  = new sbyte[0],
                empty   = new IPAddress[0],
                numbers = new List <double>(),
                list    = new List <string>()
            };
            var buf = PacketConvert.Serialize(obj);
            var res = PacketConvert.Deserialize(buf, obj);

            ThrowIfNotSequenceEqual(obj.array, res.array);
            ThrowIfNotSequenceEqual(obj.list, res.list);
            ThrowIfNotSequenceEqual(obj.numbers, res.numbers);
            ThrowIfNotSequenceEqual(obj.empty, res.empty);
            ThrowIfNotSequenceEqual(obj.bytes, res.bytes);
            ThrowIfNotSequenceEqual(obj.sbytes, res.sbytes);
            return;
        }
Beispiel #17
0
        public void Dictionary()
        {
            var a = new Dictionary <string, sbyte> {
                ["a"] = 1, ["beta"] = -1, ["other"] = 127
            };
            var b = new Dictionary <byte, string> {
                [1] = "one", [128] = "many", [255] = "max", [0] = "zero"
            };
            var c = new Dictionary <string, IPAddress> {
                ["loopback"] = IPAddress.Loopback, ["ipv6 loopback"] = IPAddress.IPv6Loopback
            };

            var obj = new { a, b, c };
            var ta  = PacketConvert.Serialize(obj);
            var va  = PacketConvert.Deserialize(ta, new { a = default(Dictionary <string, sbyte>), b = default(IDictionary <byte, string>), c = default(IDictionary <string, IPAddress>) });

            var wtr = new PacketWriter()
                      .SetDictionary("a", a)
                      .SetDictionary("b", b)
                      .SetDictionary("c", c);
            var tb  = wtr.GetBytes();
            var rea = new PacketReader(tb);
            var ra  = rea["a"].GetDictionary <string, sbyte>();
            var rb  = rea["b"].GetDictionary <byte, string>();
            var rc  = rea["c"].GetDictionary <string, IPAddress>();

            Assert.AreEqual(ta.Length, tb.Length);

            ThrowIfNotEqual(a, ra);
            ThrowIfNotEqual(b, rb);
            ThrowIfNotEqual(c, rc);

            ThrowIfNotEqual(a, va.a);
            ThrowIfNotEqual(b, va.b);
            ThrowIfNotEqual(c, va.c);
            return;
        }
Beispiel #18
0
        public void DeserializeOffset()
        {
            var obj = new { id = 1.1, text = "what the" };
            var ta  = PacketConvert.Serialize(obj);
            var buf = new byte[ta.Length + 128];
            var off = new Random().Next(8, 32);

            Buffer.BlockCopy(ta, 0, buf, off, ta.Length);

            var ra = PacketConvert.Deserialize(ta, obj.GetType());
            var rb = PacketConvert.Deserialize(buf, off, ta.Length, obj.GetType());

            void AreEqual(object a, object b)
            {
                var x = a.Cast(obj);
                var y = b.Cast(obj);

                if (x.id == y.id && x.text == y.text)
                {
                    return;
                }
                throw new ApplicationException();
            }

            AreEqual(obj, ra);
            AreEqual(obj, rb);

            var str = "world";
            var tb  = PacketConvert.GetBytes(str);
            var tc  = new byte[tb.Length + 128];

            Buffer.BlockCopy(tb, 0, tc, off, tb.Length);
            var rc = PacketConvert.Deserialize <string>(tc, off, tb.Length);

            Assert.AreEqual(str, rc);
        }
Beispiel #19
0
        /// <summary>
        /// Performance test
        /// </summary>
        internal static void DoWork()
        {
            var dic = new Dictionary <string, List <TimeSpan> >();

            TraceWatch.InstanceDisposed = (tag, span) =>
            {
                if (dic.TryGetValue(tag, out var val))
                {
                    val.Add(span);
                }
                else
                {
                    dic.Add(tag, new List <TimeSpan>()
                    {
                        span
                    });
                }
            };

            const int max  = 1 << 20;
            const int loop = 10;

            var ano = new
            {
                num = 1024,
                str = "string",
                arr = new[] { 7, 11, 555, 1313 },
                sub = new
                {
                    sum = 2.2D,
                    lst = new List <string> {
                        "one", "two", "three"
                    },
                }
            };

            var tmp = PacketConvert.Serialize(ano);

            // release mode
            for (int idx = 0; idx < loop; idx++)
            {
                using (new TraceWatch("BitConverter")) // 8.00 ms
                {
                    for (int i = 0; i < max; i++)
                    {
                        var buf = BitConverter.GetBytes(i);
                        var res = BitConverter.ToInt32(buf, 0);
                    }
                }

                using (new TraceWatch("PacketWriter<>")) // 2228.99 ms, avg
                {
                    for (int i = 0; i < max; i++)
                    {
                        var wtr = new PacketWriter().
                                  SetValue(nameof(ano.num), ano.num).
                                  SetValue(nameof(ano.str), ano.str).
                                  SetEnumerable(nameof(ano.arr), ano.arr).
                                  SetItem(nameof(ano.sub), new PacketWriter().
                                          SetValue(nameof(ano.sub.sum), ano.sub.sum).
                                          SetEnumerable(nameof(ano.sub.lst), ano.sub.lst));
                        var buf = wtr.GetBytes();
                    }
                }

                using (new TraceWatch("Serialize (anonymous)")) // 2453.45 ms, avg
                {
                    for (int i = 0; i < max; i++)
                    {
                        var _ = PacketConvert.Serialize(ano);
                    }
                }

                using (new TraceWatch("Deserialize (anonymous)")) // 1960.96 ms, avg
                {
                    for (int i = 0; i < max; i++)
                    {
                        var _ = PacketConvert.Deserialize(tmp, ano);
                    }
                }
            }

            foreach (var i in dic)
            {
                var key = i.Key;
                var val = i.Value;
                if (val.Count > 6)
                {
                    val.RemoveRange(0, 4);
                }
                var sum = val.Select(r => r.Ticks).Sum();
                var cir = new TimeSpan(sum / val.Count);
                var avg = new TimeSpan(1000 * sum / val.Count / max);
                Console.WriteLine($"{key,-24} | " +
                                  $"total: {new TimeSpan(sum).TotalMilliseconds,10:0.000} ms | " +
                                  $"loop: {cir.TotalMilliseconds,10:0.000} ms | " +
                                  $"avg: {avg.TotalMilliseconds,10:0.0000} ns");
            }
        }
Beispiel #20
0
public void InvalidType()
{
    try
    {
        var list = new HashSet <object> {
            1.2F, 3.4D, "5.6M"
        };
        var result = PacketConvert.Serialize(list);
        Assert.Fail();
    }
    catch (PacketException ex) when(ex.ErrorCode == PacketError.InvalidElementType)
    {
        // ignore
    }

    try
    {
        var empty  = new byte[0];
        var reader = new PacketReader(empty);
        var result = reader.Deserialize <Dictionary <object, string> >();
        Assert.Fail();
    }
    catch (PacketException ex) when(ex.ErrorCode == PacketError.InvalidKeyType)
    {
        // ignore
    }

    try
    {
        var empty  = new Dictionary <object, string>();
        var writer = PacketWriter.Serialize(empty);
        Assert.Fail();
    }
    catch (PacketException ex) when(ex.ErrorCode == PacketError.InvalidKeyType)
    {
        // ignore
    }

    var array      = new[] { 0F, -1.1F, 2.2F };
    var anonymous  = new { solution = "Exchange", count = 4 };
    var collection = new Dictionary <int, object>
    {
        [1]  = 1,
        [2]  = 2L,
        [4]  = "four",
        [8]  = anonymous,
        [16] = array,
    };

    var buffer     = PacketConvert.Serialize(collection);
    var dictionary = PacketConvert.Deserialize <Dictionary <int, object> >(buffer);

    var r1 = ((PacketReader)dictionary[1]).GetValue <int>();
    var r2 = ((PacketReader)dictionary[2]).GetValue <long>();
    var r4 = ((PacketReader)dictionary[4]).GetValue <string>();
    var ro = ((PacketReader)dictionary[8]).Deserialize(anonymous.GetType());
    var ra = ((PacketReader)dictionary[16]).GetArray <float>();

    Assert.AreEqual(collection[1], r1);
    Assert.AreEqual(collection[2], r2);
    Assert.AreEqual(collection[4], r4);

    Assert.AreEqual(anonymous, ro);
    ThrowIfNotSequenceEqual(array, ra);
}