mirror of
https://github.com/msgpack/msgpack-c.git
synced 2025-10-20 22:31:33 +02:00
Compare commits
758 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
0c60cfc5c0 | ||
![]() |
deb6b0e334 | ||
![]() |
27777dcd31 | ||
![]() |
bdb397e043 | ||
![]() |
cb4d851761 | ||
![]() |
7ac16f4834 | ||
![]() |
bf7fece440 | ||
![]() |
c04ef9efe5 | ||
![]() |
b774c07d19 | ||
![]() |
229467cb29 | ||
![]() |
949b472f7e | ||
![]() |
be67d3e362 | ||
![]() |
3e2ae7cc78 | ||
![]() |
505660e1fa | ||
![]() |
09d90e1231 | ||
![]() |
5a9f89ae1f | ||
![]() |
6f56345dd8 | ||
![]() |
edef040688 | ||
![]() |
9fc196e750 | ||
![]() |
dc1698eaf4 | ||
![]() |
53ded063a0 | ||
![]() |
8a2c50c374 | ||
![]() |
f71148f3a6 | ||
![]() |
172105828c | ||
![]() |
6cca6cb20d | ||
![]() |
b7336f817c | ||
![]() |
88356b79be | ||
![]() |
ce9e543882 | ||
![]() |
3ff3ba83f4 | ||
![]() |
edb525a030 | ||
![]() |
ea5314f076 | ||
![]() |
be8e53163b | ||
![]() |
79151f517f | ||
![]() |
e8ffe7ef96 | ||
![]() |
b5a7b5e277 | ||
![]() |
85b5e1088f | ||
![]() |
680ddb1557 | ||
![]() |
44fff522bd | ||
![]() |
90815f0d27 | ||
![]() |
f07950c60a | ||
![]() |
f8c4125892 | ||
![]() |
1f30cc203a | ||
![]() |
764bfdcb9f | ||
![]() |
f290814f64 | ||
![]() |
3a2508545d | ||
![]() |
79a06a338a | ||
![]() |
509f27eee1 | ||
![]() |
e511c32a36 | ||
![]() |
b463d9b687 | ||
![]() |
e96e20ccfd | ||
![]() |
06ebdbfd37 | ||
![]() |
df9fd047b4 | ||
![]() |
85d65c59d2 | ||
![]() |
754126644f | ||
![]() |
220436f4f9 | ||
![]() |
b62a6ae1d0 | ||
![]() |
eae0532b8c | ||
![]() |
d642487f99 | ||
![]() |
320510506b | ||
![]() |
b2839ac78b | ||
![]() |
834d5a0e72 | ||
![]() |
13ce808c47 | ||
![]() |
980a6529c1 | ||
![]() |
c92384fe68 | ||
![]() |
9f563f87b9 | ||
![]() |
44f37b8d1b | ||
![]() |
5f41c1cf3f | ||
![]() |
2a664b9ae6 | ||
![]() |
5456814199 | ||
![]() |
33ceaeb208 | ||
![]() |
b33e60b3ae | ||
![]() |
9dd0a6eb86 | ||
![]() |
ed6faf4e65 | ||
![]() |
df2ee5de49 | ||
![]() |
36fef91a67 | ||
![]() |
3399148d75 | ||
![]() |
0eea92de66 | ||
![]() |
92975bb21d | ||
![]() |
bf18e04134 | ||
![]() |
4a0d7f18fd | ||
![]() |
65c360a2ca | ||
![]() |
71919f7523 | ||
![]() |
31a49db68b | ||
![]() |
0d615442ba | ||
![]() |
8f35dbc306 | ||
![]() |
154bcbc4f7 | ||
![]() |
c96a39d315 | ||
![]() |
06ba74c366 | ||
![]() |
8786a8e6e0 | ||
![]() |
748236fef0 | ||
![]() |
ae1b06f20b | ||
![]() |
b8aa93ce30 | ||
![]() |
49d40a42f1 | ||
![]() |
1845f34b81 | ||
![]() |
43903d446a | ||
![]() |
256da2124b | ||
![]() |
7869e96bac | ||
![]() |
79b51a6e4b | ||
![]() |
cad9f6d46e | ||
![]() |
da2960880a | ||
![]() |
0eacc58e29 | ||
![]() |
3bec736aee | ||
![]() |
3241ffd1b4 | ||
![]() |
d0d7b266bc | ||
![]() |
c24948258b | ||
![]() |
d36666bd98 | ||
![]() |
2794b1d310 | ||
![]() |
f456fa03da | ||
![]() |
356b7b43f8 | ||
![]() |
92718e2140 | ||
![]() |
4021160a64 | ||
![]() |
6f043e3326 | ||
![]() |
74b0b1da21 | ||
![]() |
3a5f676687 | ||
![]() |
4fa7cffc37 | ||
![]() |
79b83e78a5 | ||
![]() |
048a3835e7 | ||
![]() |
4a4891036a | ||
![]() |
ff00c83f15 | ||
![]() |
79d31b7452 | ||
![]() |
20cc6f7463 | ||
![]() |
8acabaa135 | ||
![]() |
ba7183a5b4 | ||
![]() |
28f4338a6c | ||
![]() |
800a93a859 | ||
![]() |
2e969e3a0a | ||
![]() |
3fb31f651d | ||
![]() |
682d25b551 | ||
![]() |
bcad8d4c4c | ||
![]() |
96bab8e02e | ||
![]() |
fa4a615d0f | ||
![]() |
f1265c4fed | ||
![]() |
df01cd9a09 | ||
![]() |
255bac642d | ||
![]() |
6d8c3bd13d | ||
![]() |
75b8272710 | ||
![]() |
2f80e154f2 | ||
![]() |
cc0114c482 | ||
![]() |
e5e2b9095c | ||
![]() |
6977edc032 | ||
![]() |
177cc55ee5 | ||
![]() |
feb7ec03ba | ||
![]() |
6630a643d3 | ||
![]() |
d70e64a434 | ||
![]() |
896ad51102 | ||
![]() |
be6d6560a7 | ||
![]() |
709d0cc33e | ||
![]() |
bd73742552 | ||
![]() |
ed4518e09a | ||
![]() |
6c8301eae8 | ||
![]() |
6e30d504e3 | ||
![]() |
cee09a0261 | ||
![]() |
76a72558b3 | ||
![]() |
22124a33ce | ||
![]() |
3731373de1 | ||
![]() |
bbaf8c2f67 | ||
![]() |
f50694cc96 | ||
![]() |
4930ea7dab | ||
![]() |
96bb4cf49d | ||
![]() |
5e7563ac5b | ||
![]() |
f199b80453 | ||
![]() |
5de8eec206 | ||
![]() |
076bd07f39 | ||
![]() |
00e897503b | ||
![]() |
2f3c47f385 | ||
![]() |
2b28211701 | ||
![]() |
46c794fc2e | ||
![]() |
0408738b48 | ||
![]() |
6cfea98501 | ||
![]() |
33498d3673 | ||
![]() |
ed3ead06fe | ||
![]() |
eb8a338a0e | ||
![]() |
23480bfe8a | ||
![]() |
3384dbc92d | ||
![]() |
8446549ed8 | ||
![]() |
6a9f3ae71d | ||
![]() |
94e5b0d78f | ||
![]() |
0812eb1c04 | ||
![]() |
8cb5ccad99 | ||
![]() |
743d69ec0b | ||
![]() |
f6de4c9479 | ||
![]() |
fb59927d32 | ||
![]() |
c58ce1a975 | ||
![]() |
c6d9bbd7b0 | ||
![]() |
08974f00ed | ||
![]() |
60643f023f | ||
![]() |
65ddd1a455 | ||
![]() |
68a98d3dd0 | ||
![]() |
ca9015452e | ||
![]() |
05ac2603e6 | ||
![]() |
8e923777b8 | ||
![]() |
8949551c2e | ||
![]() |
0b45e9442b | ||
![]() |
1d1a9d7933 | ||
![]() |
58c0fe0f91 | ||
![]() |
b96b62f2ac | ||
![]() |
43fc0a52a6 | ||
![]() |
4f3d9a1ded | ||
![]() |
b50ff920f0 | ||
![]() |
983ae0c5a2 | ||
![]() |
9d4db84987 | ||
![]() |
1f372cf0cc | ||
![]() |
c43d597aa9 | ||
![]() |
dfaa281476 | ||
![]() |
df14629a25 | ||
![]() |
c1c25c455c | ||
![]() |
e65197f386 | ||
![]() |
ecbb8f8711 | ||
![]() |
03aa736199 | ||
![]() |
821b1f0384 | ||
![]() |
233ad3aaff | ||
![]() |
9c4812f4d4 | ||
![]() |
337cc9fa78 | ||
![]() |
dfe29a0329 | ||
![]() |
85e90aa81e | ||
![]() |
86d30fe571 | ||
![]() |
173302267f | ||
![]() |
8e3ea8d26c | ||
![]() |
cb065563c2 | ||
![]() |
27b89b237b | ||
![]() |
21f0d0bfc4 | ||
![]() |
d5e583b09e | ||
![]() |
15fb9bbcb2 | ||
![]() |
a03418ab12 | ||
![]() |
035513844d | ||
![]() |
193906b8ce | ||
![]() |
d354f2e8c2 | ||
![]() |
24a8ee436f | ||
![]() |
6e5f9404b7 | ||
![]() |
64fe90aabb | ||
![]() |
7e31d487e0 | ||
![]() |
ee16e2eb30 | ||
![]() |
003fb3392f | ||
![]() |
0e82278cd5 | ||
![]() |
5b544248bc | ||
![]() |
d4d7495c0a | ||
![]() |
8325cce44c | ||
![]() |
ee0debc5b3 | ||
![]() |
8f1bd12a17 | ||
![]() |
fccf1016e4 | ||
![]() |
1b010a082b | ||
![]() |
324f215316 | ||
![]() |
ace4f1e7f0 | ||
![]() |
5c5f16f148 | ||
![]() |
f50855d5c0 | ||
![]() |
86917b0ba7 | ||
![]() |
7201fcbe0f | ||
![]() |
83f1735fbb | ||
![]() |
80fd8e70f0 | ||
![]() |
698c1c2b7a | ||
![]() |
5d3287f5aa | ||
![]() |
6990fe6f51 | ||
![]() |
0b81068368 | ||
![]() |
5b1851ae22 | ||
![]() |
0d5708a01d | ||
![]() |
67ab510b5d | ||
![]() |
d1264a1289 | ||
![]() |
3b973021a1 | ||
![]() |
182624895f | ||
![]() |
548de3739c | ||
![]() |
718a3efd64 | ||
![]() |
76b8c3250b | ||
![]() |
dafaa8bd8c | ||
![]() |
9c9b2c25ea | ||
![]() |
e89cd81022 | ||
![]() |
5debbd2be8 | ||
![]() |
fe26df5355 | ||
![]() |
85778494e4 | ||
![]() |
a94ce3c715 | ||
![]() |
a440ff1117 | ||
![]() |
8195137bc5 | ||
![]() |
3e2bd25e4e | ||
![]() |
ffd0c2f624 | ||
![]() |
23333c98d7 | ||
![]() |
5a12ab98c4 | ||
![]() |
0b327a63fc | ||
![]() |
15b28a245c | ||
![]() |
6ef5684797 | ||
![]() |
d439b1495b | ||
![]() |
9e096a3f0e | ||
![]() |
0acf6ec150 | ||
![]() |
4b36340474 | ||
![]() |
910e642a8b | ||
![]() |
9f571146fb | ||
![]() |
339725f73d | ||
![]() |
aff964c58b | ||
![]() |
0c07e745f8 | ||
![]() |
419d2e9564 | ||
![]() |
f936a307c6 | ||
![]() |
4e4678edfa | ||
![]() |
cb7a4b3116 | ||
![]() |
5ca4c42a74 | ||
![]() |
1238a7ca07 | ||
![]() |
a9db60a73d | ||
![]() |
bd32ac19d4 | ||
![]() |
eaf9944e43 | ||
![]() |
703fdbc01d | ||
![]() |
2daa08b0e7 | ||
![]() |
05d9d22d9e | ||
![]() |
8b7894f9bd | ||
![]() |
a71439607f | ||
![]() |
aca0d7f969 | ||
![]() |
310a8e4342 | ||
![]() |
24fbe1ef5b | ||
![]() |
33d8faa35d | ||
![]() |
44be714f65 | ||
![]() |
0df3da6b10 | ||
![]() |
79197b6ec7 | ||
![]() |
353b6b51cb | ||
![]() |
bd9a2c0d3a | ||
![]() |
53b0ee6536 | ||
![]() |
78daac0f1b | ||
![]() |
b970b9b9a8 | ||
![]() |
0339db57f1 | ||
![]() |
461b147897 | ||
![]() |
a3cd13b399 | ||
![]() |
eb5d326a1e | ||
![]() |
cce6eb94e2 | ||
![]() |
8311c72c69 | ||
![]() |
9a059285d9 | ||
![]() |
469ac7891d | ||
![]() |
16264a5693 | ||
![]() |
6eedb50f56 | ||
![]() |
5f07215662 | ||
![]() |
d3a02fb2ca | ||
![]() |
2c823f1aaa | ||
![]() |
706293aadc | ||
![]() |
dfdceb4258 | ||
![]() |
0014b7fdb9 | ||
![]() |
3b28f1f8af | ||
![]() |
c689d476ca | ||
![]() |
cc534fd21f | ||
![]() |
124efcf247 | ||
![]() |
dd452b05e3 | ||
![]() |
b5617f7df9 | ||
![]() |
b73ca1ba3a | ||
![]() |
39ad071c4f | ||
![]() |
fa0b576a45 | ||
![]() |
c2c7591987 | ||
![]() |
3e939e3775 | ||
![]() |
f6384e10bc | ||
![]() |
c283842563 | ||
![]() |
1135976225 | ||
![]() |
76679d33df | ||
![]() |
e9d44b90bc | ||
![]() |
8a7a391166 | ||
![]() |
d6c5a9eece | ||
![]() |
56ad6915d0 | ||
![]() |
466c260782 | ||
![]() |
d8e2d1725a | ||
![]() |
33b43d03ac | ||
![]() |
517509db6e | ||
![]() |
95f01a5976 | ||
![]() |
d08d3bf56d | ||
![]() |
587fd669e8 | ||
![]() |
e3553b87fe | ||
![]() |
a078d2360c | ||
![]() |
2d3abf8e6e | ||
![]() |
cacae0fb7d | ||
![]() |
d7fc215c16 | ||
![]() |
bb69aa18f2 | ||
![]() |
e4f515166a | ||
![]() |
f325acb0ea | ||
![]() |
d1b6e65dd8 | ||
![]() |
4688252bd4 | ||
![]() |
b1df5d3ad7 | ||
![]() |
09bad2938e | ||
![]() |
bad69fd397 | ||
![]() |
b4ae6bf82c | ||
![]() |
eac0f83864 | ||
![]() |
3f16f080ac | ||
![]() |
5de2b974fb | ||
![]() |
6a9cb51828 | ||
![]() |
f1c294ca50 | ||
![]() |
c320e44a23 | ||
![]() |
ea36ef3107 | ||
![]() |
fedc37d079 | ||
![]() |
86ccfcc03c | ||
![]() |
bc8d8ab65a | ||
![]() |
a7a23d3bc8 | ||
![]() |
82d33944e6 | ||
![]() |
8a629ad6fb | ||
![]() |
e1711ffcf2 | ||
![]() |
063d51c662 | ||
![]() |
d8e3575a46 | ||
![]() |
6fa609be3f | ||
![]() |
70982e204c | ||
![]() |
2af7df5865 | ||
![]() |
59610e81de | ||
![]() |
cdfac703ef | ||
![]() |
ad5ebd007e | ||
![]() |
1bd347d997 | ||
![]() |
147056073d | ||
![]() |
1b3231e617 | ||
![]() |
7ac4ad3e38 | ||
![]() |
0a345cb12b | ||
![]() |
19ff0dd17f | ||
![]() |
e3bf8a404b | ||
![]() |
dbb28d9a8f | ||
![]() |
19fd4e755c | ||
![]() |
77698cd924 | ||
![]() |
945d279f28 | ||
![]() |
645d296841 | ||
![]() |
57446de875 | ||
![]() |
3473800ab6 | ||
![]() |
7e5c5153a8 | ||
![]() |
1b8979f285 | ||
![]() |
2aac51dd20 | ||
![]() |
69e32d264c | ||
![]() |
71ae75a5bf | ||
![]() |
86043fd87e | ||
![]() |
d8aaef4f04 | ||
![]() |
7fc34b6369 | ||
![]() |
92b346efa7 | ||
![]() |
c790735b9f | ||
![]() |
64711e615e | ||
![]() |
2065affd45 | ||
![]() |
4067c56b5d | ||
![]() |
65515638aa | ||
![]() |
371ba3ffe3 | ||
![]() |
5395b62f2f | ||
![]() |
3e164eab26 | ||
![]() |
ad85533975 | ||
![]() |
d6c2a97931 | ||
![]() |
17def94ba4 | ||
![]() |
cf254ea240 | ||
![]() |
2d05110239 | ||
![]() |
0017f4fce8 | ||
![]() |
02f3dd947a | ||
![]() |
ef0874feba | ||
![]() |
14aa1420f0 | ||
![]() |
c506cd97e0 | ||
![]() |
3761aacb1d | ||
![]() |
233f13aac5 | ||
![]() |
0ced3ec2d2 | ||
![]() |
5b786f65a4 | ||
![]() |
770542c8c7 | ||
![]() |
4f1207a38c | ||
![]() |
2b65f81e23 | ||
![]() |
c10eb2c17b | ||
![]() |
3f5ac54bf5 | ||
![]() |
790f9409b1 | ||
![]() |
a3d831b723 | ||
![]() |
b9483deea3 | ||
![]() |
c211d2ac45 | ||
![]() |
119a03dd5f | ||
![]() |
f3fbb7e1f6 | ||
![]() |
2be98e8467 | ||
![]() |
91b1806e9d | ||
![]() |
8548b3645a | ||
![]() |
4bbfb3f9a3 | ||
![]() |
98eec72522 | ||
![]() |
562d50df4d | ||
![]() |
f3ee5ab372 | ||
![]() |
aa2a3e5b07 | ||
![]() |
8467307239 | ||
![]() |
90da951a6f | ||
![]() |
59f81b331c | ||
![]() |
77a7d3d26a | ||
![]() |
4321b80999 | ||
![]() |
4b93b06323 | ||
![]() |
96fb2e4b7c | ||
![]() |
3dc1048dfb | ||
![]() |
28f4bd5a67 | ||
![]() |
b01c270889 | ||
![]() |
7c92f8a90b | ||
![]() |
a4a04872a3 | ||
![]() |
f2d13cd647 | ||
![]() |
9346908485 | ||
![]() |
b3a7ba14f7 | ||
![]() |
524ef9553c | ||
![]() |
a85f6e72fe | ||
![]() |
1ae6a41336 | ||
![]() |
3ec55791c6 | ||
![]() |
a3accd28ea | ||
![]() |
fc5bc84207 | ||
![]() |
d8b4051d6d | ||
![]() |
804a1cc22d | ||
![]() |
cdd60e5f9c | ||
![]() |
7c76f07384 | ||
![]() |
a3b1ef9527 | ||
![]() |
0bd4150a80 | ||
![]() |
7f7f5253f2 | ||
![]() |
2a0a847634 | ||
![]() |
92ddb37ed3 | ||
![]() |
01f944e6bd | ||
![]() |
732c8d7350 | ||
![]() |
21678aeef5 | ||
![]() |
cda1ca35a4 | ||
![]() |
923580d2cd | ||
![]() |
190af1d32b | ||
![]() |
bffe0443f9 | ||
![]() |
29e99e229b | ||
![]() |
2736b88dd5 | ||
![]() |
e739c60e9f | ||
![]() |
1c0afbc5c5 | ||
![]() |
ee1ba5c0f2 | ||
![]() |
02342ba540 | ||
![]() |
12a130e9bc | ||
![]() |
dfb97e7961 | ||
![]() |
54e03a62bd | ||
![]() |
ec9659ff25 | ||
![]() |
0a41b253f3 | ||
![]() |
002b86198c | ||
![]() |
7161a235f1 | ||
![]() |
391034a785 | ||
![]() |
446a7fbd67 | ||
![]() |
2ccb09434f | ||
![]() |
7974060a40 | ||
![]() |
e8abcc1765 | ||
![]() |
1be1927a1f | ||
![]() |
894ff71664 | ||
![]() |
93bed9c5df | ||
![]() |
34c008adce | ||
![]() |
22ddd91b1f | ||
![]() |
e121f34407 | ||
![]() |
df8a3e870a | ||
![]() |
13b6708a09 | ||
![]() |
6aa196cf55 | ||
![]() |
142493076a | ||
![]() |
3d905a7a4f | ||
![]() |
0a8a6ed168 | ||
![]() |
68b6fa46e6 | ||
![]() |
80f7c54e4d | ||
![]() |
c0e2041006 | ||
![]() |
f6d2cd7704 | ||
![]() |
6d9a629b15 | ||
![]() |
ead8edc7cd | ||
![]() |
664eefdddb | ||
![]() |
220d76c974 | ||
![]() |
d973192b5e | ||
![]() |
978bb5059f | ||
![]() |
f59178bc33 | ||
![]() |
53899cc492 | ||
![]() |
6379d0fe0f | ||
![]() |
a1c4d8696a | ||
![]() |
7f42ed86f2 | ||
![]() |
6bb8b4c994 | ||
![]() |
afefbe4e56 | ||
![]() |
5cd37e5505 | ||
![]() |
d6a825981d | ||
![]() |
a1c01c6722 | ||
![]() |
8d182f1d79 | ||
![]() |
29707bd2ea | ||
![]() |
c2bf2a8174 | ||
![]() |
b402849557 | ||
![]() |
cb85dcfcb8 | ||
![]() |
49379140c7 | ||
![]() |
63f6c86b46 | ||
![]() |
1865898cd4 | ||
![]() |
8935ecfdb8 | ||
![]() |
4902bed409 | ||
![]() |
e6f6aba207 | ||
![]() |
bab622de25 | ||
![]() |
a86c1624a7 | ||
![]() |
c707392a5a | ||
![]() |
1f07721ec4 | ||
![]() |
4767e45035 | ||
![]() |
f2a64ed685 | ||
![]() |
2c9966a0a3 | ||
![]() |
953aa95c64 | ||
![]() |
446266776e | ||
![]() |
845af014dc | ||
![]() |
7c8f8703a1 | ||
![]() |
a0c18e4380 | ||
![]() |
e8d8099563 | ||
![]() |
2c9d90d463 | ||
![]() |
130d2064d5 | ||
![]() |
a10eb2a0d7 | ||
![]() |
b71cc5d7ee | ||
![]() |
8512f9eda1 | ||
![]() |
80058083b8 | ||
![]() |
d5a17a3c25 | ||
![]() |
eab7c87781 | ||
![]() |
d2962d8676 | ||
![]() |
5e602fb575 | ||
![]() |
599964ea5f | ||
![]() |
562de7926b | ||
![]() |
8eaed95e02 | ||
![]() |
3cffd46008 | ||
![]() |
e239bfda8a | ||
![]() |
bd887b660d | ||
![]() |
7c1e0ea95d | ||
![]() |
afbddbfcda | ||
![]() |
9eeb702ca5 | ||
![]() |
4cb6d6995f | ||
![]() |
fe7e7a8d07 | ||
![]() |
f8ee79ab72 | ||
![]() |
a11165830b | ||
![]() |
11cde61eab | ||
![]() |
cd862409cc | ||
![]() |
7644555d6b | ||
![]() |
07e68aa694 | ||
![]() |
0ae206b1bb | ||
![]() |
5bdac96375 | ||
![]() |
f0e044ecd8 | ||
![]() |
f32234291e | ||
![]() |
83acd6529f | ||
![]() |
6a60cb4dc0 | ||
![]() |
1de03fbe18 | ||
![]() |
0e0a2aa981 | ||
![]() |
af73b9d11b | ||
![]() |
859969241a | ||
![]() |
6852a8ca9d | ||
![]() |
c694f1a4a9 | ||
![]() |
d36543b204 | ||
![]() |
6981234736 | ||
![]() |
10bf3ee9de | ||
![]() |
9953218de1 | ||
![]() |
50c74103aa | ||
![]() |
c5e15123fd | ||
![]() |
4adcdb5ba8 | ||
![]() |
60b36ffaa3 | ||
![]() |
d86104ed5d | ||
![]() |
0f02ef20a9 | ||
![]() |
0768cf17b6 | ||
![]() |
197205853f | ||
![]() |
bebcc24ab8 | ||
![]() |
987248ccbb | ||
![]() |
56ece4db0f | ||
![]() |
c7f8b94ccd | ||
![]() |
95b820305a | ||
![]() |
599b200ca5 | ||
![]() |
a9566b31be | ||
![]() |
f30837d726 | ||
![]() |
1242ffa4c6 | ||
![]() |
37c0347c47 | ||
![]() |
65befb84a0 | ||
![]() |
a41f7ce3bd | ||
![]() |
81ced6bf2a | ||
![]() |
fa8033f998 | ||
![]() |
19e3178d0c | ||
![]() |
1e6262f24f | ||
![]() |
beb2284440 | ||
![]() |
0c4f0de13d | ||
![]() |
0cd31a4b96 | ||
![]() |
ef0a86e7cc | ||
![]() |
b79c1345b9 | ||
![]() |
5bb8b6f16c | ||
![]() |
f6f675d1e1 | ||
![]() |
9f684e7670 | ||
![]() |
a998706452 | ||
![]() |
5e19bc6f84 | ||
![]() |
169f287970 | ||
![]() |
c56926428c | ||
![]() |
43eab5c4e5 | ||
![]() |
c6424c2ce7 | ||
![]() |
dfe19d308c | ||
![]() |
b75db110dc | ||
![]() |
9e50ba6ec6 | ||
![]() |
aca2ba13c2 | ||
![]() |
c5afe7a573 | ||
![]() |
8b90968cb1 | ||
![]() |
9281dba896 | ||
![]() |
c7555f1c3c | ||
![]() |
e781831032 | ||
![]() |
8025895168 | ||
![]() |
799935e44c | ||
![]() |
209d8d058c | ||
![]() |
0368a70dd7 | ||
![]() |
c3603426de | ||
![]() |
80db9971b5 | ||
![]() |
e3e771708e | ||
![]() |
b9bca2a19f | ||
![]() |
ffae70a99a | ||
![]() |
10ec1e48b0 | ||
![]() |
84123f5445 | ||
![]() |
25531d8393 | ||
![]() |
adfadc542a | ||
![]() |
7682e1cb57 | ||
![]() |
1fe4109a42 | ||
![]() |
b97baf4d47 | ||
![]() |
f91728561f | ||
![]() |
2b75d54ce1 | ||
![]() |
cdc09a7d30 | ||
![]() |
4cc6c3e535 | ||
![]() |
8f43e033a4 | ||
![]() |
918dbd1926 | ||
![]() |
8fc86ce7fa | ||
![]() |
bf0cb40586 | ||
![]() |
a62aefe74b | ||
![]() |
138d232149 | ||
![]() |
8fa64e3ab2 | ||
![]() |
8d0d2bd3fc | ||
![]() |
2146f5f623 | ||
![]() |
623df23570 | ||
![]() |
4a15d8b6d2 | ||
![]() |
af83a62474 | ||
![]() |
a0705a6c67 | ||
![]() |
712b8eec3d | ||
![]() |
558e9c21ed | ||
![]() |
23a7137e6a | ||
![]() |
71a1cb0184 | ||
![]() |
09b47cc536 | ||
![]() |
b5c78de2dd | ||
![]() |
a1bd14e516 | ||
![]() |
9684c8664f | ||
![]() |
3c75361e5a | ||
![]() |
c44c9ab74d | ||
![]() |
8cc9c871b7 | ||
![]() |
31d211cded | ||
![]() |
c42cba1d54 | ||
![]() |
c87f7cb9ac | ||
![]() |
421bee3871 | ||
![]() |
2c7573a032 | ||
![]() |
fe2a0f5089 | ||
![]() |
59ba8dec4e | ||
![]() |
ff0e1bbbc0 | ||
![]() |
18c712cd99 | ||
![]() |
8de1f764fd | ||
![]() |
a91c1ec6d9 | ||
![]() |
c8e351b31e | ||
![]() |
b4c98584db | ||
![]() |
1d17836b7d | ||
![]() |
193a739749 | ||
![]() |
48da2b8353 | ||
![]() |
40dc9de6c9 | ||
![]() |
d7469e4694 | ||
![]() |
fdfabc9f88 | ||
![]() |
5658ca5b90 | ||
![]() |
8b79e6d3c7 | ||
![]() |
8c67087a15 | ||
![]() |
057f73a73e | ||
![]() |
d3bb37d113 | ||
![]() |
6c91b862c9 | ||
![]() |
cba47b635a | ||
![]() |
cd83388f8b | ||
![]() |
02ae247536 | ||
![]() |
1621a68191 | ||
![]() |
2aef495d62 | ||
![]() |
227c168b65 | ||
![]() |
dcbcf5842f | ||
![]() |
8a3ac6d9bd | ||
![]() |
6cabad19d5 | ||
![]() |
dad7a03d19 | ||
![]() |
7b152640d9 | ||
![]() |
78fddff34e | ||
![]() |
78f542f6c0 | ||
![]() |
f8a016edb5 | ||
![]() |
9ac69337e8 | ||
![]() |
ca0c844f32 | ||
![]() |
e629e8784f | ||
![]() |
e944c1ee93 | ||
![]() |
02c882bda3 | ||
![]() |
2c29377abf | ||
![]() |
21992f1b9e | ||
![]() |
8a3f090684 | ||
![]() |
a4258505a9 | ||
![]() |
ba4a971bfa | ||
![]() |
6abc120279 | ||
![]() |
64c36b7a8f | ||
![]() |
64b9f0762c | ||
![]() |
e799082e5c | ||
![]() |
eab66a022e | ||
![]() |
485915c27a | ||
![]() |
45fb482ab4 | ||
![]() |
33a7d56042 | ||
![]() |
8f7f23a0e5 |
58
.gitignore
vendored
Normal file
58
.gitignore
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
# Files generated by the bootstrap script.
|
||||
/INSTALL
|
||||
/NEWS
|
||||
/README
|
||||
/ac/
|
||||
/aclocal.m4
|
||||
/autom4te.cache/
|
||||
/config.h.in
|
||||
/configure
|
||||
/msgpack_vc2008.sln
|
||||
/msgpack_vc2008.vcproj
|
||||
/src/msgpack/pack_define.h
|
||||
/src/msgpack/pack_template.h
|
||||
/src/msgpack/sysdep.h
|
||||
/src/msgpack/type/define.hpp
|
||||
/src/msgpack/type/tuple.hpp
|
||||
/src/msgpack/unpack_define.h
|
||||
/src/msgpack/unpack_template.h
|
||||
/src/msgpack/zone.hpp
|
||||
/test/cases.mpac
|
||||
/test/cases_compact.mpac
|
||||
Makefile.in
|
||||
|
||||
# Files generated by the configure script.
|
||||
|
||||
/config.h
|
||||
/config.log
|
||||
/config.status
|
||||
/libtool
|
||||
/msgpack.pc
|
||||
/src/msgpack/version.h
|
||||
/stamp-h1
|
||||
Makefile
|
||||
.deps
|
||||
.libs
|
||||
|
||||
# Files generated by make.
|
||||
*.o
|
||||
*.so
|
||||
*.lo
|
||||
*.la
|
||||
|
||||
# Files generated by make check.
|
||||
# TODO: Replace these with something like /test/*_test
|
||||
/test/buffer
|
||||
/test/cases
|
||||
/test/convert
|
||||
/test/fixint
|
||||
/test/fixint_c
|
||||
/test/msgpack_test
|
||||
/test/msgpackc_test
|
||||
/test/object
|
||||
/test/pack_unpack
|
||||
/test/pack_unpack_c
|
||||
/test/streaming
|
||||
/test/streaming_c
|
||||
/test/version
|
||||
/test/zone
|
58
ChangeLog
Normal file
58
ChangeLog
Normal file
@@ -0,0 +1,58 @@
|
||||
2013-12-23 version 0.5.8:
|
||||
|
||||
* Move to the new github repository msgpack/msgpack-c
|
||||
* Support the new deserialization specification
|
||||
* fixes the problem of unpack helpers for array and map with 32bit compilers (#37, #38)
|
||||
* Other bug fixes and refactoring: #46, #41, #36, #35, #33, #32, #30, #29, #28, #27, #26, #25, #8, #3
|
||||
* Update of documents: #23, #18, #17
|
||||
|
||||
2011-08-08 version 0.5.7:
|
||||
|
||||
* fixes compile error problem with llvm-gcc and Mac OS X Lion
|
||||
|
||||
2011-04-24 version 0.5.6:
|
||||
|
||||
* #42 fixes double-free problem on msgpack_unpacker_release_zone
|
||||
|
||||
2011-02-24 version 0.5.5:
|
||||
|
||||
* eliminates dependency of winsock2.h header
|
||||
* fixes msgpack_vc.postbuild.bat file
|
||||
* fixes some implicit cast warnings
|
||||
|
||||
2010-08-29 version 0.5.4:
|
||||
|
||||
* includes msgpack_vc2008.vcproj file in source package
|
||||
* fixes type::fix_int types
|
||||
|
||||
2010-08-27 version 0.5.3:
|
||||
|
||||
* adds type::fix_{u,}int{8,16,32,64} types
|
||||
* adds msgpack_pack_fix_{u,}int{8,16,32,64} functions
|
||||
* adds packer<Stream>::pack_fix_{u,}int{8,16,32,64} functions
|
||||
* fixes include paths
|
||||
|
||||
2010-07-14 version 0.5.2:
|
||||
|
||||
* type::raw::str(), operator==, operator!=, operator< and operator> are now const
|
||||
* generates version.h using AC_OUTPUT macro in ./configure
|
||||
|
||||
2010-07-06 version 0.5.1:
|
||||
|
||||
* Add msgpack_vrefbuffer_new and msgpack_vrefbuffer_free
|
||||
* Add msgpack_sbuffer_new and msgpack_sbuffer_free
|
||||
* Add msgpack_unpacker_next and msgpack_unpack_next
|
||||
* msgpack::unpack returns void
|
||||
* Add MSGPACK_VERSION{,_MAJOR,_MINOR} macros to check header version
|
||||
* Add msgpack_version{,_major,_minor} functions to check library version
|
||||
* ./configure supports --disable-cxx option not to build C++ API
|
||||
|
||||
2010-04-29 version 0.5.0:
|
||||
|
||||
* msgpack_object_type is changed. MSGPACK_OBJECT_NIL is now 0x00.
|
||||
* New safe streaming deserializer API.
|
||||
* Add object::object(const T&) and object::operator=(const T&)
|
||||
* Add operator==(object, const T&)
|
||||
* MSGPACK_DEFINE macro defines msgpack_object(object* obj, zone* z)
|
||||
* C++ programs doesn't need to link "msgpackc" library.
|
||||
|
@@ -6,11 +6,16 @@ DOC_FILES = \
|
||||
NOTICE \
|
||||
msgpack_vc8.vcproj \
|
||||
msgpack_vc8.sln \
|
||||
msgpack_vc8.postbuild.bat
|
||||
msgpack_vc2008.vcproj \
|
||||
msgpack_vc2008.sln \
|
||||
msgpack_vc.postbuild.bat
|
||||
|
||||
EXTRA_DIST = \
|
||||
$(DOC_FILES)
|
||||
|
||||
pkgconfigdir = $(libdir)/pkgconfig
|
||||
pkgconfig_DATA = msgpack.pc
|
||||
|
||||
doxygen:
|
||||
./preprocess clean
|
||||
cd src && $(MAKE) doxygen
|
194
QUICKSTART-C.md
Normal file
194
QUICKSTART-C.md
Normal file
@@ -0,0 +1,194 @@
|
||||
# Implementation Status
|
||||
|
||||
The serialization library is production-ready.
|
||||
|
||||
Currently, no RPC implementation is not available.
|
||||
|
||||
# Install
|
||||
|
||||
|
||||
## Mac OS X with MacPorts
|
||||
|
||||
On Mac OS X, you can install MessagePack for C using MacPorts.
|
||||
|
||||
```
|
||||
$ sudo port install msgpack
|
||||
```
|
||||
|
||||
You might need to run `sudo port selfupdate` before installing to update the package repository.
|
||||
|
||||
You can also install via Homebrew.
|
||||
|
||||
```
|
||||
$ sudo brew install msgpack
|
||||
```
|
||||
|
||||
## FreeBSD with Ports Collection
|
||||
|
||||
On FreeBSD, you can use Ports Collection. Install [net/msgpack|http://www.freebsd.org/cgi/cvsweb.cgi/ports/devel/msgpack/] package.
|
||||
|
||||
## Gentoo Linux with Portage
|
||||
|
||||
On Gentoo Linux, you can use emerge. Install [dev-libs/msgpack|http://gentoo-portage.com/dev-libs/msgpack] package.
|
||||
|
||||
## Other UNIX-like platform with ./configure
|
||||
|
||||
On the other UNIX-like platforms, download source package from [Releases|http://msgpack.org/releases/cpp/] and run `./configure && make && make install`.
|
||||
|
||||
```
|
||||
$ wget http://msgpack.org/releases/cpp/msgpack-0.5.5.tar.gz
|
||||
$ tar zxvf msgpack-0.5.5.tar.gz
|
||||
$ cd msgpack-0.5.5
|
||||
$ ./configure
|
||||
$ make
|
||||
$ sudo make install
|
||||
```
|
||||
|
||||
## Windows
|
||||
|
||||
On Windows, download source package from [here|https://sourceforge.net/projects/msgpack/files/] and extract it.
|
||||
Then open `msgpack_vc8.vcproj` file and build it using batch build. It builds libraries on `lib/` folder and header files on `include/` folder.
|
||||
|
||||
You can build using command line as follows:
|
||||
|
||||
```
|
||||
> vcbuild msgpack_vc2008.vcproj
|
||||
> dir lib % DLL files are here
|
||||
> dir include % header files are here
|
||||
```
|
||||
|
||||
## Install from git repository
|
||||
|
||||
You need to install gcc (4.1.0 or higher), autotools.
|
||||
|
||||
```
|
||||
$ git clone git@github.com:msgpack/msgpack.git
|
||||
$ cd msgpack/cpp
|
||||
$ ./bootstrap
|
||||
$ ./configure
|
||||
$ make
|
||||
$ sudo make install
|
||||
```
|
||||
|
||||
# Serialization QuickStart for C
|
||||
|
||||
## First program
|
||||
|
||||
Include `msgpack.h` header and link `msgpack` library to use MessagePack on your program.
|
||||
|
||||
```c
|
||||
#include <msgpack.h>
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
|
||||
/* creates buffer and serializer instance. */
|
||||
msgpack_sbuffer* buffer = msgpack_sbuffer_new();
|
||||
msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write);
|
||||
|
||||
/* serializes ["Hello", "MessagePack"]. */
|
||||
msgpack_pack_array(pk, 2);
|
||||
msgpack_pack_raw(pk, 5);
|
||||
msgpack_pack_raw_body(pk, "Hello", 5);
|
||||
msgpack_pack_raw(pk, 11);
|
||||
msgpack_pack_raw_body(pk, "MessagePack", 11);
|
||||
|
||||
/* deserializes it. */
|
||||
msgpack_unpacked msg;
|
||||
msgpack_unpacked_init(&msg);
|
||||
bool success = msgpack_unpack_next(&msg, buffer->data, buffer->size, NULL);
|
||||
|
||||
/* prints the deserialized object. */
|
||||
msgpack_object obj = msg.data;
|
||||
msgpack_object_print(stdout, obj); /*=> ["Hello", "MessagePack"] */
|
||||
|
||||
/* cleaning */
|
||||
msgpack_sbuffer_free(buffer);
|
||||
msgpack_packer_free(pk);
|
||||
}
|
||||
```
|
||||
|
||||
## Simple program with a loop
|
||||
|
||||
```c
|
||||
#include <msgpack.h>
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
|
||||
/* creates buffer and serializer instance. */
|
||||
msgpack_sbuffer* buffer = msgpack_sbuffer_new();
|
||||
msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write);
|
||||
|
||||
int j;
|
||||
|
||||
for(j = 0; j<23; j++) {
|
||||
/* NB: the buffer needs to be cleared on each iteration */
|
||||
msgpack_sbuffer_clear(buffer);
|
||||
|
||||
/* serializes ["Hello", "MessagePack"]. */
|
||||
msgpack_pack_array(pk, 3);
|
||||
msgpack_pack_raw(pk, 5);
|
||||
msgpack_pack_raw_body(pk, "Hello", 5);
|
||||
msgpack_pack_raw(pk, 11);
|
||||
msgpack_pack_raw_body(pk, "MessagePack", 11);
|
||||
msgpack_pack_int(pk, j);
|
||||
|
||||
/* deserializes it. */
|
||||
msgpack_unpacked msg;
|
||||
msgpack_unpacked_init(&msg);
|
||||
bool success = msgpack_unpack_next(&msg, buffer->data, buffer->size, NULL);
|
||||
|
||||
/* prints the deserialized object. */
|
||||
msgpack_object obj = msg.data;
|
||||
msgpack_object_print(stdout, obj); /*=> ["Hello", "MessagePack"] */
|
||||
puts("");
|
||||
}
|
||||
|
||||
/* cleaning */
|
||||
msgpack_sbuffer_free(buffer);
|
||||
msgpack_packer_free(pk);
|
||||
}
|
||||
```
|
||||
|
||||
## Streaming feature
|
||||
|
||||
```c
|
||||
#include <msgpack.h>
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
/* serializes multiple objects using msgpack_packer. */
|
||||
msgpack_sbuffer* buffer = msgpack_sbuffer_new();
|
||||
msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write);
|
||||
msgpack_pack_int(pk, 1);
|
||||
msgpack_pack_int(pk, 2);
|
||||
msgpack_pack_int(pk, 3);
|
||||
|
||||
/* deserializes these objects using msgpack_unpacker. */
|
||||
msgpack_unpacker pac;
|
||||
msgpack_unpacker_init(&pac, MSGPACK_UNPACKER_INIT_BUFFER_SIZE);
|
||||
|
||||
/* feeds the buffer. */
|
||||
msgpack_unpacker_reserve_buffer(&pac, buffer->size);
|
||||
memcpy(msgpack_unpacker_buffer(&pac), buffer->data, buffer->size);
|
||||
msgpack_unpacker_buffer_consumed(&pac, buffer->size);
|
||||
|
||||
/* now starts streaming deserialization. */
|
||||
msgpack_unpacked result;
|
||||
msgpack_unpacked_init(&result);
|
||||
|
||||
while(msgpack_unpacker_next(&pac, &result)) {
|
||||
msgpack_object_print(stdout, result.data);
|
||||
puts("");
|
||||
}
|
||||
|
||||
/* results:
|
||||
* $ gcc stream.cc -lmsgpack -o stream
|
||||
* $ ./stream
|
||||
* 1
|
||||
* 2
|
||||
* 3
|
||||
*/
|
||||
}
|
||||
```
|
159
QUICKSTART-CPP.md
Normal file
159
QUICKSTART-CPP.md
Normal file
@@ -0,0 +1,159 @@
|
||||
# Implementation Status
|
||||
|
||||
The serialization library is production-ready.
|
||||
|
||||
Currently, RPC implementation is testing phase. Requires newer kernel, not running on RHEL5/CentOS5.
|
||||
|
||||
# Install
|
||||
|
||||
Same as QuickStart for C Language.
|
||||
|
||||
# Serialization QuickStart for C+\+
|
||||
|
||||
## First program
|
||||
|
||||
Include `msgpack.hpp` header and link `msgpack` library to use MessagePack on your program.
|
||||
|
||||
```cpp
|
||||
#include <msgpack.hpp>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
int main(void) {
|
||||
// serializes this object.
|
||||
std::vector<std::string> vec;
|
||||
vec.push_back("Hello");
|
||||
vec.push_back("MessagePack");
|
||||
|
||||
// serialize it into simple buffer.
|
||||
msgpack::sbuffer sbuf;
|
||||
msgpack::pack(sbuf, vec);
|
||||
|
||||
// deserialize it.
|
||||
msgpack::unpacked msg;
|
||||
msgpack::unpack(&msg, sbuf.data(), sbuf.size());
|
||||
|
||||
// print the deserialized object.
|
||||
msgpack::object obj = msg.get();
|
||||
std::cout << obj << std::endl; //=> ["Hello", "MessagePack"]
|
||||
|
||||
// convert it into statically typed object.
|
||||
std::vector<std::string> rvec;
|
||||
obj.convert(&rvec);
|
||||
}
|
||||
```
|
||||
|
||||
Compile it as follows:
|
||||
|
||||
```
|
||||
$ g++ hello.cc -lmsgpack -o hello
|
||||
$ ./hello
|
||||
["Hello", "MessagePack"]
|
||||
```
|
||||
|
||||
## Streaming feature
|
||||
|
||||
```cpp
|
||||
#include <msgpack.hpp>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
int main(void) {
|
||||
// serializes multiple objects using msgpack::packer.
|
||||
msgpack::sbuffer buffer;
|
||||
|
||||
msgpack::packer<msgpack::sbuffer> pk(&buffer);
|
||||
pk.pack(std::string("Log message ... 1"));
|
||||
pk.pack(std::string("Log message ... 2"));
|
||||
pk.pack(std::string("Log message ... 3"));
|
||||
|
||||
// deserializes these objects using msgpack::unpacker.
|
||||
msgpack::unpacker pac;
|
||||
|
||||
// feeds the buffer.
|
||||
pac.reserve_buffer(buffer.size());
|
||||
memcpy(pac.buffer(), buffer.data(), buffer.size());
|
||||
pac.buffer_consumed(buffer.size());
|
||||
|
||||
// now starts streaming deserialization.
|
||||
msgpack::unpacked result;
|
||||
while(pac.next(&result)) {
|
||||
std::cout << result.get() << std::endl;
|
||||
}
|
||||
|
||||
// results:
|
||||
// $ g++ stream.cc -lmsgpack -o stream
|
||||
// $ ./stream
|
||||
// "Log message ... 1"
|
||||
// "Log message ... 2"
|
||||
// "Log message ... 3"
|
||||
}
|
||||
```
|
||||
|
||||
### Streaming into an array or map
|
||||
|
||||
```cpp
|
||||
#include <msgpack.hpp>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
int main(void) {
|
||||
// serializes multiple objects into one message containing an array using msgpack::packer.
|
||||
msgpack::sbuffer buffer;
|
||||
|
||||
msgpack::packer<msgpack::sbuffer> pk(&buffer);
|
||||
pk.pack_array(3)
|
||||
pk.pack(std::string("Log message ... 1"));
|
||||
pk.pack(std::string("Log message ... 2"));
|
||||
pk.pack(std::string("Log message ... 3"));
|
||||
|
||||
// serializes multiple objects into one message containing a map using msgpack::packer.
|
||||
msgpack::sbuffer buffer2;
|
||||
|
||||
msgpack::packer<msgpack::sbuffer> pk2(&buffer2);
|
||||
pk2.pack_map(2)
|
||||
pk2.pack(std::string("x"));
|
||||
pk2.pack(3);
|
||||
pk2.pack(std::string("y));
|
||||
pk2.pack(3.4321);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## User-defined classes
|
||||
|
||||
You can use serialize/deserializes user-defined classes using MSGPACK_DEFINE macro.
|
||||
|
||||
```cpp
|
||||
#include <msgpack.hpp>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
class myclass {
|
||||
private:
|
||||
std::string m_str;
|
||||
std::vector<int> m_vec;
|
||||
public:
|
||||
MSGPACK_DEFINE(m_str, m_vec);
|
||||
};
|
||||
|
||||
int main(void) {
|
||||
std::vector<myclass> vec;
|
||||
// add some elements into vec...
|
||||
|
||||
// you can serialize myclass directly
|
||||
msgpack::sbuffer sbuf;
|
||||
msgpack::pack(sbuf, vec);
|
||||
|
||||
msgpack::unpacked msg;
|
||||
msgpack::unpack(&msg, sbuf.data(), sbuf.size());
|
||||
|
||||
msgpack::object obj = msg.get();
|
||||
|
||||
// you can convert object to myclass directly
|
||||
std::vector<myclass> rvec;
|
||||
obj.convert(&rvec);
|
||||
}
|
||||
```
|
86
README.md
86
README.md
@@ -1,37 +1,73 @@
|
||||
MessagePack
|
||||
===========
|
||||
Extremely efficient object serialization library. It's like JSON, but very fast and small.
|
||||
MessagePack for C/C++
|
||||
=====================
|
||||
Binary-based efficient object serialization library.
|
||||
|
||||
|
||||
## What's MessagePack?
|
||||
## Installation
|
||||
|
||||
MessagePack is a binary-based efficient object serialization library. It enables to exchange structured objects between many languages like JSON. But unlike JSON, it is very fast and small.
|
||||
Download latest package from [releases of MessagePack](http://sourceforge.net/projects/msgpack/files/) and extract it.
|
||||
|
||||
Typical small integer (like flags or error code) is saved only in 1 byte, and typical short string only needs 1 byte except the length of the string itself. \[1,2,3\] (3 elements array) is serialized in 4 bytes using MessagePack as follows:
|
||||
On UNIX-like platform, run ./configure && make && sudo make install:
|
||||
|
||||
require 'msgpack'
|
||||
msg = [1,2,3].to_msgpack #=> "\x93\x01\x02\x03"
|
||||
MessagePack.unpack(msg) #=> [1,2,3]
|
||||
$ ./configure
|
||||
$ make
|
||||
$ sudo make install
|
||||
|
||||
On Windows, open msgpack_vc8.vcproj or msgpack_vc2008 file and build it using batch build. DLLs are built on lib folder,
|
||||
and the headers are built on include folder.
|
||||
|
||||
To use the library in your program, include msgpack.hpp header and link "msgpack" library.
|
||||
|
||||
|
||||
## Performance
|
||||
## Example
|
||||
```CPP
|
||||
#include <msgpack.hpp>
|
||||
#include <vector>
|
||||
|
||||
int main(void) {
|
||||
// This is target object.
|
||||
std::vector<std::string> target;
|
||||
target.push_back("Hello,");
|
||||
target.push_back("World!");
|
||||
|
||||
// Serialize it.
|
||||
msgpack::sbuffer sbuf; // simple buffer
|
||||
msgpack::pack(&sbuf, target);
|
||||
|
||||
// Deserialize the serialized data.
|
||||
msgpack::unpacked msg; // includes memory pool and deserialized object
|
||||
msgpack::unpack(&msg, sbuf.data(), sbuf.size());
|
||||
msgpack::object obj = msg.get();
|
||||
|
||||
// Print the deserialized object to stdout.
|
||||
std::cout << obj << std::endl; // ["Hello," "World!"]
|
||||
|
||||
// Convert the deserialized object to staticaly typed object.
|
||||
std::vector<std::string> result;
|
||||
obj.convert(&result);
|
||||
|
||||
// If the type is mismatched, it throws msgpack::type_error.
|
||||
obj.as<int>(); // type is mismatched, msgpack::type_error is thrown
|
||||
}
|
||||
```
|
||||
|
||||

|
||||
See [QuickStart for C](QUICKSTART-C.md) and [QuickStart for C++](QUICKSTART-CPP.md) for other example codes.
|
||||
|
||||
In this test, it measured the elapsed time of serializing and deserializing 200,000 target objects. The target object consists of the three integers and 512 bytes string.
|
||||
The source code of this test is available from [frsyuki' serializer-speed-test repository.](http://github.com/frsyuki/serializer-speed-test)
|
||||
## License
|
||||
|
||||
Copyright (C) 2008-2010 FURUHASHI Sadayuki
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
## Getting Started
|
||||
|
||||
Usage and other documents about implementations in each language are found at [the web site.](http://msgpack.sourceforge.net/)
|
||||
|
||||
|
||||
## Learn More
|
||||
|
||||
- [Project Web Site](http://msgpack.sourceforge.net/)
|
||||
- [MessagePack format specification](http://msgpack.sourceforge.net/spec)
|
||||
- [Repository at github](http://github.com/msgpack/msgpack)
|
||||
- [Wiki](http://msgpack.sourceforge.net/start)
|
||||
- [MessagePack-RPC](http://github.com/msgpack/msgpack-rpc)
|
||||
See also NOTICE file.
|
||||
|
||||
|
@@ -38,7 +38,8 @@ test -f ChangeLog || touch ChangeLog
|
||||
test -f NEWS || touch NEWS
|
||||
test -f README || cp -f README.md README
|
||||
|
||||
if ! ./preprocess; then
|
||||
./preprocess
|
||||
if [ $? -ne 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
@@ -1,13 +1,13 @@
|
||||
AC_INIT(src/object.cpp)
|
||||
AC_CONFIG_AUX_DIR(ac)
|
||||
AM_INIT_AUTOMAKE(msgpack, 0.5.2)
|
||||
AM_INIT_AUTOMAKE(msgpack, 0.5.8)
|
||||
AC_CONFIG_HEADER(config.h)
|
||||
|
||||
AC_SUBST(CFLAGS)
|
||||
CFLAGS="-O4 -Wall $CFLAGS"
|
||||
CFLAGS="-O3 -Wall $CFLAGS"
|
||||
|
||||
AC_SUBST(CXXFLAGS)
|
||||
CXXFLAGS="-O4 -Wall $CXXFLAGS"
|
||||
CXXFLAGS="-O3 -Wall $CXXFLAGS"
|
||||
|
||||
|
||||
AC_PROG_CC
|
||||
@@ -16,7 +16,7 @@ AC_PROG_CC
|
||||
AC_MSG_CHECKING([if C++ API is enabled])
|
||||
AC_ARG_ENABLE(cxx,
|
||||
AS_HELP_STRING([--disable-cxx],
|
||||
[don't build C++ API]) )
|
||||
[don't build C++ API]) ) #'
|
||||
AC_MSG_RESULT([$enable_cxx])
|
||||
if test "$enable_cxx" != "no"; then
|
||||
AC_PROG_CXX
|
||||
@@ -47,20 +47,44 @@ AC_CACHE_CHECK([for __sync_* atomic operations], msgpack_cv_atomic_ops, [
|
||||
AC_TRY_LINK([
|
||||
int atomic_sub(int i) { return __sync_sub_and_fetch(&i, 1); }
|
||||
int atomic_add(int i) { return __sync_add_and_fetch(&i, 1); }
|
||||
], [], msgpack_cv_atomic_ops="yes")
|
||||
], [atomic_sub(1); atomic_add(1);], msgpack_cv_atomic_ops="yes")
|
||||
])
|
||||
if test "$msgpack_cv_atomic_ops" != "yes"; then
|
||||
AC_MSG_ERROR([__sync_* atomic operations are not supported.
|
||||
if test "$enable_cxx" = "no"; then
|
||||
AC_MSG_ERROR([__sync_* atomic operations are not found. Try to enable C++ support.
|
||||
If you are using gcc >= 4.1 and the default target CPU architecture is "i386", try to
|
||||
add CFLAGS="-march=i686" and CXXFLAGS="-march=i686" options to ./configure as follows:
|
||||
|
||||
Note that gcc < 4.1 is not supported.
|
||||
$ ./configure CFLAGS="-march=i686" CXXFLAGS="-march=i686"
|
||||
])
|
||||
fi
|
||||
|
||||
AC_LANG_PUSH([C++])
|
||||
AC_CACHE_CHECK([for __gnu_cxx::__exchange_and_add], msgpack_cv_gcc_cxx_atomic_ops, [
|
||||
AC_TRY_LINK([
|
||||
#include <bits/atomicity.h>
|
||||
int atomic_sub(int i) { return __gnu_cxx::__exchange_and_add(&i, -1) - 1; }
|
||||
int atomic_add(int i) { return __gnu_cxx::__exchange_and_add(&i, 1) + 1; }
|
||||
], [atomic_sub(1); atomic_add(1);], msgpack_cv_gcc_cxx_atomic_ops="yes")
|
||||
])
|
||||
AC_LANG_POP([C++])
|
||||
|
||||
if test "$msgpack_cv_gcc_cxx_atomic_ops" != "yes"; then
|
||||
AC_MSG_ERROR([__sync_* atomic operations nor __gnu_cxx::__exchange_and_add are not found.
|
||||
|
||||
If you are using gcc >= 4.1 and the default target CPU architecture is "i386", try to
|
||||
add CFLAGS="--march=i686" and CXXFLAGS="-march=i686" options to ./configure as follows:
|
||||
add CFLAGS="-march=i686" and CXXFLAGS="-march=i686" options to ./configure as follows:
|
||||
|
||||
$ ./configure CFLAGS="-march=i686" CXXFLAGS="-march=i686"
|
||||
])
|
||||
|
||||
else
|
||||
enable_gcc_cxx_atomic=yes
|
||||
fi
|
||||
fi
|
||||
|
||||
AM_CONDITIONAL(ENABLE_GCC_CXX_ATOMIC, test "$enable_gcc_cxx_atomic" = "yes")
|
||||
|
||||
|
||||
major=`echo $VERSION | sed 's/\([[0-9]]*\)\.\([[0-9]]*\).*/\1/'`
|
||||
minor=`echo $VERSION | sed 's/\([[0-9]]*\)\.\([[0-9]]*\).*/\2/'`
|
||||
@@ -69,6 +93,7 @@ AC_SUBST(VERSION_MINOR, $minor)
|
||||
|
||||
|
||||
AC_OUTPUT([Makefile
|
||||
msgpack.pc
|
||||
src/Makefile
|
||||
src/msgpack/version.h
|
||||
test/Makefile])
|
@@ -1,25 +0,0 @@
|
||||
|
||||
2010-07-14 version 0.5.2:
|
||||
|
||||
* type::raw::str(), operator==, operator!=, operator< and operator> are now const
|
||||
* generates version.h using AC_OUTPUT macro in ./configure
|
||||
|
||||
2010-07-06 version 0.5.1:
|
||||
|
||||
* Add msgpack_vrefbuffer_new and msgpack_vrefbuffer_free
|
||||
* Add msgpack_sbuffer_new and msgpack_sbuffer_free
|
||||
* Add msgpack_unpacker_next and msgpack_unpack_next
|
||||
* msgpack::unpack returns void
|
||||
* Add MSGPACK_VERSION{,_MAJOR,_MINOR} macros to check header version
|
||||
* Add msgpack_version{,_major,_minor} functions to check library version
|
||||
* ./configure supports --disable-cxx option not to build C++ API
|
||||
|
||||
2010-04-29 version 0.5.0:
|
||||
|
||||
* msgpack_object_type is changed. MSGPACK_OBJECT_NIL is now 0x00.
|
||||
* New safe streaming deserializer API.
|
||||
* Add object::object(const T&) and object::operator=(const T&)
|
||||
* Add operator==(object, const T&)
|
||||
* MSGPACK_DEFINE macro defines msgpack_object(object* obj, zone* z)
|
||||
* C++ programs doesn't need to link "msgpackc" library.
|
||||
|
@@ -1,78 +0,0 @@
|
||||
MessagePack for C/C++
|
||||
=====================
|
||||
Binary-based efficient object serialization library.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
Download latest package from [releases of MessagePack](http://sourceforge.net/projects/msgpack/files/) and extract it.
|
||||
|
||||
On UNIX-like platform, run ./configure && make && sudo make install:
|
||||
|
||||
$ ./configure
|
||||
$ make
|
||||
$ sudo make install
|
||||
|
||||
On Windows, open msgpack_vc8.vcproj file and build it using batch build. DLLs are built on lib folder, and the headers are built on include folder.
|
||||
|
||||
To use the library in your program, include msgpack.hpp header and link msgpack and msgpackc library.
|
||||
|
||||
|
||||
## Example
|
||||
|
||||
#include <msgpack.hpp>
|
||||
#include <vector>
|
||||
|
||||
int main(void) {
|
||||
// This is target object.
|
||||
std::vector<std::string> target;
|
||||
target.push_back("Hello,");
|
||||
target.push_back("World!");
|
||||
|
||||
// Serialize it.
|
||||
msgpack::sbuffer buffer; // simple buffer
|
||||
msgpack::pack(&buffer, target);
|
||||
|
||||
// Deserialize the serialized data.
|
||||
msgpack::zone mempool; // this manages the life of deserialized object
|
||||
msgpack::object obj;
|
||||
msgpack::unpack_return ret =
|
||||
msgpack::unpack(buffer.data, buffer.size, NULL, &mempool, &obj);
|
||||
|
||||
if(ret != msgapck::UNPACK_SUCCESS) {
|
||||
// error check
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// Print the deserialized object to stdout.
|
||||
std::cout << obj << std::endl; // ["Hello," "World!"]
|
||||
|
||||
// Convert the deserialized object to staticaly typed object.
|
||||
std::vector<std::string> result;
|
||||
obj.convert(&result);
|
||||
|
||||
// If the type is mismatched, it throws msgpack::type_error.
|
||||
obj.as<int>(); // type is mismatched, msgpack::type_error is thrown
|
||||
}
|
||||
|
||||
API document and other example codes are available at the [wiki.](http://msgpack.sourceforge.net/start)
|
||||
|
||||
|
||||
## License
|
||||
|
||||
Copyright (C) 2008-2010 FURUHASHI Sadayuki
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
See also NOTICE file.
|
||||
|
@@ -1,31 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
preprocess() {
|
||||
ruby -r erb -e 'puts ERB.new(ARGF.read).result' $1.erb > $1.tmp
|
||||
if [ "$?" != 0 ]; then
|
||||
echo ""
|
||||
echo "** preprocess failed **"
|
||||
echo ""
|
||||
exit 1
|
||||
else
|
||||
mv $1.tmp $1
|
||||
fi
|
||||
}
|
||||
|
||||
if [ "$1" == "clean" ];then
|
||||
rm -f src/msgpack/type/tuple.hpp
|
||||
rm -f src/msgpack/type/define.hpp
|
||||
rm -f src/msgpack/zone.hpp
|
||||
else
|
||||
preprocess src/msgpack/type/tuple.hpp
|
||||
preprocess src/msgpack/type/define.hpp
|
||||
preprocess src/msgpack/zone.hpp
|
||||
fi
|
||||
cp -f ../msgpack/sysdep.h src/msgpack/
|
||||
cp -f ../msgpack/pack_define.h src/msgpack/
|
||||
cp -f ../msgpack/pack_template.h src/msgpack/
|
||||
cp -f ../msgpack/unpack_define.h src/msgpack/
|
||||
cp -f ../msgpack/unpack_template.h src/msgpack/
|
||||
cp -f ../test/cases.mpac test/
|
||||
cp -f ../test/cases_compact.mpac test/
|
||||
|
@@ -1,15 +0,0 @@
|
||||
#include "msgpack/type/bool.hpp"
|
||||
#include "msgpack/type/float.hpp"
|
||||
#include "msgpack/type/int.hpp"
|
||||
#include "msgpack/type/list.hpp"
|
||||
#include "msgpack/type/deque.hpp"
|
||||
#include "msgpack/type/map.hpp"
|
||||
#include "msgpack/type/nil.hpp"
|
||||
#include "msgpack/type/pair.hpp"
|
||||
#include "msgpack/type/raw.hpp"
|
||||
#include "msgpack/type/set.hpp"
|
||||
#include "msgpack/type/string.hpp"
|
||||
#include "msgpack/type/vector.hpp"
|
||||
#include "msgpack/type/tuple.hpp"
|
||||
#include "msgpack/type/define.hpp"
|
||||
|
@@ -1,57 +0,0 @@
|
||||
#include <msgpack.h>
|
||||
#include <gtest/gtest.h>
|
||||
#include <stdio.h>
|
||||
|
||||
TEST(streaming, basic)
|
||||
{
|
||||
msgpack_sbuffer* buffer = msgpack_sbuffer_new();
|
||||
|
||||
msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write);
|
||||
EXPECT_EQ(0, msgpack_pack_int(pk, 1));
|
||||
EXPECT_EQ(0, msgpack_pack_int(pk, 2));
|
||||
EXPECT_EQ(0, msgpack_pack_int(pk, 3));
|
||||
msgpack_packer_free(pk);
|
||||
|
||||
const char* input = buffer->data;
|
||||
const char* const eof = input + buffer->size;
|
||||
|
||||
msgpack_unpacker pac;
|
||||
msgpack_unpacker_init(&pac, MSGPACK_UNPACKER_INIT_BUFFER_SIZE);
|
||||
|
||||
msgpack_unpacked result;
|
||||
msgpack_unpacked_init(&result);
|
||||
|
||||
int count = 0;
|
||||
while(count < 3) {
|
||||
msgpack_unpacker_reserve_buffer(&pac, 32*1024);
|
||||
|
||||
/* read buffer into msgpack_unapcker_buffer(&pac) upto
|
||||
* msgpack_unpacker_buffer_capacity(&pac) bytes. */
|
||||
size_t len = 1;
|
||||
memcpy(msgpack_unpacker_buffer(&pac), input, len);
|
||||
input += len;
|
||||
|
||||
msgpack_unpacker_buffer_consumed(&pac, len);
|
||||
|
||||
while(msgpack_unpacker_next(&pac, &result)) {
|
||||
msgpack_object obj = result.data;
|
||||
switch(count++) {
|
||||
case 0:
|
||||
EXPECT_EQ(MSGPACK_OBJECT_POSITIVE_INTEGER, result.data.type);
|
||||
EXPECT_EQ(1, result.data.via.u64);
|
||||
break;
|
||||
case 1:
|
||||
EXPECT_EQ(MSGPACK_OBJECT_POSITIVE_INTEGER, result.data.type);
|
||||
EXPECT_EQ(2, result.data.via.u64);
|
||||
break;
|
||||
case 2:
|
||||
EXPECT_EQ(MSGPACK_OBJECT_POSITIVE_INTEGER, result.data.type);
|
||||
EXPECT_EQ(3, result.data.via.u64);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
EXPECT_TRUE(input < eof);
|
||||
}
|
||||
}
|
||||
|
4
erlang/.gitignore
vendored
4
erlang/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
MANIFEST
|
||||
*.beam
|
||||
.omakedb*
|
||||
*.omc
|
@@ -1,42 +0,0 @@
|
||||
########################################################################
|
||||
# Permission is hereby granted, free of charge, to any person
|
||||
# obtaining a copy of this file, to deal in the File without
|
||||
# restriction, including without limitation the rights to use,
|
||||
# copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
# sell copies of the File, and to permit persons to whom the
|
||||
# File is furnished to do so, subject to the following condition:
|
||||
#
|
||||
# THE FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE FILE OR
|
||||
# THE USE OR OTHER DEALINGS IN THE FILE.
|
||||
|
||||
########################################################################
|
||||
# The standard OMakefile.
|
||||
# You will usually need to modify this file for your project.
|
||||
|
||||
########################################################################
|
||||
# Phony targets are scoped, so you probably want to declare them first.
|
||||
#
|
||||
|
||||
.PHONY: all clean test #install
|
||||
|
||||
########################################################################
|
||||
# Subdirectories.
|
||||
# You may want to include some subdirectories in this project.
|
||||
# If so, define the subdirectory targets and uncomment this section.
|
||||
#
|
||||
|
||||
.DEFAULT: msgpack.beam
|
||||
|
||||
msgpack.beam: msgpack.erl
|
||||
erlc $<
|
||||
|
||||
test: msgpack.beam
|
||||
erl -noshell -s msgpack test -s init stop
|
||||
|
||||
clean:
|
||||
-rm *.beam
|
@@ -1,45 +0,0 @@
|
||||
########################################################################
|
||||
# Permission is hereby granted, free of charge, to any person
|
||||
# obtaining a copy of this file, to deal in the File without
|
||||
# restriction, including without limitation the rights to use,
|
||||
# copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
# sell copies of the File, and to permit persons to whom the
|
||||
# File is furnished to do so, subject to the following condition:
|
||||
#
|
||||
# THE FILE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE FILE OR
|
||||
# THE USE OR OTHER DEALINGS IN THE FILE.
|
||||
|
||||
########################################################################
|
||||
# The standard OMakeroot file.
|
||||
# You will not normally need to modify this file.
|
||||
# By default, your changes should be placed in the
|
||||
# OMakefile in this directory.
|
||||
#
|
||||
# If you decide to modify this file, note that it uses exactly
|
||||
# the same syntax as the OMakefile.
|
||||
#
|
||||
|
||||
#
|
||||
# Include the standard installed configuration files.
|
||||
# Any of these can be deleted if you are not using them,
|
||||
# but you probably want to keep the Common file.
|
||||
#
|
||||
open build/C
|
||||
open build/OCaml
|
||||
open build/LaTeX
|
||||
|
||||
#
|
||||
# The command-line variables are defined *after* the
|
||||
# standard configuration has been loaded.
|
||||
#
|
||||
DefineCommandVars()
|
||||
|
||||
#
|
||||
# Include the OMakefile in this directory.
|
||||
#
|
||||
.SUBDIRS: .
|
@@ -1,9 +0,0 @@
|
||||
MessagePack for Erlang
|
||||
======================
|
||||
Binary-based efficient object serialization library.
|
||||
|
||||
see wiki ( http://redmine.msgpack.org/projects/msgpack/wiki/QuickStartErlang ) for details
|
||||
|
||||
# Status
|
||||
|
||||
0.1.0 released.
|
@@ -1,362 +0,0 @@
|
||||
%%
|
||||
%% MessagePack for Erlang
|
||||
%%
|
||||
%% Copyright (C) 2009-2010 UENISHI Kota
|
||||
%%
|
||||
%% Licensed under the Apache License, Version 2.0 (the "License");
|
||||
%% you may not use this file except in compliance with the License.
|
||||
%% You may obtain a copy of the License at
|
||||
%%
|
||||
%% http://www.apache.org/licenses/LICENSE-2.0
|
||||
%%
|
||||
%% Unless required by applicable law or agreed to in writing, software
|
||||
%% distributed under the License is distributed on an "AS IS" BASIS,
|
||||
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
%% See the License for the specific language governing permissions and
|
||||
%% limitations under the License.
|
||||
|
||||
-module(msgpack).
|
||||
-author('kuenishi+msgpack@gmail.com').
|
||||
|
||||
%% tuples, atoms are not supported. lists, integers, double, and so on.
|
||||
%% see http://msgpack.sourceforge.jp/spec for
|
||||
%% supported formats. APIs are almost compatible
|
||||
%% for C API (http://msgpack.sourceforge.jp/c:doc)
|
||||
%% except buffering functions (both copying and zero-copying).
|
||||
-export([pack/1, unpack/1, unpack_all/1]).
|
||||
-export([pack_map/1]).
|
||||
|
||||
% compile:
|
||||
% erl> c(msgpack).
|
||||
% erl> S = <some term>.
|
||||
% erl> {S, <<>>} = msgpack:unpack( msgpack:pack(S) ).
|
||||
-type reason() :: enomem | badarg | no_code_matches.
|
||||
-type msgpack_term() :: [msgpack_term()]
|
||||
| {[{msgpack_term(),msgpack_term()}]}
|
||||
| integer() | float() | binary().
|
||||
|
||||
% ===== external APIs ===== %
|
||||
-spec pack(Term::msgpack_term()) -> binary().
|
||||
pack(I) when is_integer(I) andalso I < 0 ->
|
||||
pack_int_(I);
|
||||
pack(I) when is_integer(I) ->
|
||||
pack_uint_(I);
|
||||
pack(F) when is_float(F) ->
|
||||
pack_double(F);
|
||||
pack(nil) ->
|
||||
<< 16#C0:8 >>;
|
||||
pack(true) ->
|
||||
<< 16#C3:8 >>;
|
||||
pack(false) ->
|
||||
<< 16#C2:8 >>;
|
||||
pack(Bin) when is_binary(Bin) ->
|
||||
pack_raw(Bin);
|
||||
pack(List) when is_list(List) ->
|
||||
pack_array(List);
|
||||
pack({Map}) when is_list(Map) ->
|
||||
pack_map(Map);
|
||||
pack(Map) when is_tuple(Map), element(1,Map)=:=dict ->
|
||||
pack_map(dict:to_list(Map));
|
||||
pack(_Other) ->
|
||||
{error, undefined}.
|
||||
|
||||
% unpacking.
|
||||
% if failed in decoding and not end, get more data
|
||||
% and feed more Bin into this function.
|
||||
% TODO: error case for imcomplete format when short for any type formats.
|
||||
-spec unpack( Bin::binary() )-> {msgpack_term(), binary()} |
|
||||
{more, non_neg_integer()} | {more, undefined} |
|
||||
{error, reason()}.
|
||||
unpack(Bin) when not is_binary(Bin)->
|
||||
{error, badarg};
|
||||
unpack(Bin) when bit_size(Bin) >= 8 ->
|
||||
unpack_(Bin);
|
||||
unpack(<<>>)->
|
||||
{more, 1};
|
||||
unpack(_) ->
|
||||
{more, undefined}.
|
||||
|
||||
-spec unpack_all( binary() ) -> [msgpack_term()].
|
||||
unpack_all(Data)->
|
||||
case unpack(Data) of
|
||||
{ Term, Binary } when bit_size(Binary) =:= 0 ->
|
||||
[Term];
|
||||
{ Term, Binary } when is_binary(Binary) ->
|
||||
[Term|unpack_all(Binary)]
|
||||
end.
|
||||
|
||||
-spec pack_map(M::[{msgpack_term(),msgpack_term()}])-> binary().
|
||||
pack_map(M)->
|
||||
case length(M) of
|
||||
Len when Len < 16 ->
|
||||
<< 2#1000:4, Len:4/integer-unit:1, (pack_map_(M, <<>>))/binary >>;
|
||||
Len when Len < 16#10000 -> % 65536
|
||||
<< 16#DE:8, Len:16/big-unsigned-integer-unit:1, (pack_map_(M, <<>>))/binary >>;
|
||||
Len ->
|
||||
<< 16#DF:8, Len:32/big-unsigned-integer-unit:1, (pack_map_(M, <<>>))/binary >>
|
||||
end.
|
||||
|
||||
% ===== internal APIs ===== %
|
||||
|
||||
% positive fixnum
|
||||
pack_uint_(N) when N < 128 ->
|
||||
<< 2#0:1, N:7 >>;
|
||||
% uint 8
|
||||
pack_uint_(N) when N < 256 ->
|
||||
<< 16#CC:8, N:8 >>;
|
||||
% uint 16
|
||||
pack_uint_(N) when N < 65536 ->
|
||||
<< 16#CD:8, N:16/big-unsigned-integer-unit:1 >>;
|
||||
% uint 32
|
||||
pack_uint_(N) when N < 16#FFFFFFFF->
|
||||
<< 16#CE:8, N:32/big-unsigned-integer-unit:1 >>;
|
||||
% uint 64
|
||||
pack_uint_(N) ->
|
||||
<< 16#CF:8, N:64/big-unsigned-integer-unit:1 >>.
|
||||
|
||||
% negative fixnum
|
||||
pack_int_(N) when is_integer(N) , N >= -32->
|
||||
<< 2#111:3, N:5 >>;
|
||||
% int 8
|
||||
pack_int_(N) when N > -128 ->
|
||||
<< 16#D0:8, N:8/big-signed-integer-unit:1 >>;
|
||||
% int 16
|
||||
pack_int_(N) when N > -32768 ->
|
||||
<< 16#D1:8, N:16/big-signed-integer-unit:1 >>;
|
||||
% int 32
|
||||
pack_int_(N) when N > -16#FFFFFFFF ->
|
||||
<< 16#D2:8, N:32/big-signed-integer-unit:1 >>;
|
||||
% int 64
|
||||
pack_int_(N) ->
|
||||
<< 16#D3:8, N:64/big-signed-integer-unit:1 >>.
|
||||
|
||||
% float : erlang's float is always IEEE 754 64bit format.
|
||||
%pack_float(F) when is_float(F)->
|
||||
% << 16#CA:8, F:32/big-float-unit:1 >>.
|
||||
% pack_double(F).
|
||||
% double
|
||||
pack_double(F) ->
|
||||
<< 16#CB:8, F:64/big-float-unit:1 >>.
|
||||
|
||||
% raw bytes
|
||||
pack_raw(Bin) ->
|
||||
case byte_size(Bin) of
|
||||
Len when Len < 6->
|
||||
<< 2#101:3, Len:5, Bin/binary >>;
|
||||
Len when Len < 16#10000 -> % 65536
|
||||
<< 16#DA:8, Len:16/big-unsigned-integer-unit:1, Bin/binary >>;
|
||||
Len ->
|
||||
<< 16#DB:8, Len:32/big-unsigned-integer-unit:1, Bin/binary >>
|
||||
end.
|
||||
|
||||
% list / tuple
|
||||
pack_array(L) ->
|
||||
case length(L) of
|
||||
Len when Len < 16 ->
|
||||
<< 2#1001:4, Len:4/integer-unit:1, (pack_array_(L, <<>>))/binary >>;
|
||||
Len when Len < 16#10000 -> % 65536
|
||||
<< 16#DC:8, Len:16/big-unsigned-integer-unit:1,(pack_array_(L, <<>>))/binary >>;
|
||||
Len ->
|
||||
<< 16#DD:8, Len:32/big-unsigned-integer-unit:1,(pack_array_(L, <<>>))/binary >>
|
||||
end.
|
||||
pack_array_([], Acc) -> Acc;
|
||||
pack_array_([Head|Tail], Acc) ->
|
||||
pack_array_(Tail, <<Acc/binary, (pack(Head))/binary>>).
|
||||
|
||||
% FIXME! this should be without lists:reverse/1
|
||||
unpack_array_(<<>>, 0, RetList) -> {lists:reverse(RetList), <<>>};
|
||||
unpack_array_(Remain, 0, RetList) when is_binary(Remain)-> {lists:reverse(RetList), Remain};
|
||||
unpack_array_(<<>>, RestLen, _RetList) when RestLen > 0 -> {more, undefined};
|
||||
unpack_array_(Bin, RestLen, RetList) when is_binary(Bin)->
|
||||
case unpack(Bin) of
|
||||
{more, _} -> {more, undefined};
|
||||
{Term, Rest}-> unpack_array_(Rest, RestLen-1, [Term|RetList])
|
||||
end.
|
||||
|
||||
pack_map_([], Acc) -> Acc;
|
||||
pack_map_([{Key,Value}|Tail], Acc) ->
|
||||
pack_map_(Tail, << Acc/binary, (pack(Key))/binary, (pack(Value))/binary>>).
|
||||
|
||||
% FIXME! this should be without lists:reverse/1
|
||||
-spec unpack_map_(binary(), non_neg_integer(), [{term(), msgpack_term()}])->
|
||||
{more, non_neg_integer()} | { any(), binary()}.
|
||||
unpack_map_(Bin, 0, Acc) -> {{lists:reverse(Acc)}, Bin};
|
||||
unpack_map_(Bin, Len, Acc) ->
|
||||
case unpack(Bin) of
|
||||
{more, _} -> {more, undefined};
|
||||
{Key, Rest} ->
|
||||
case unpack(Rest) of
|
||||
{more, _} -> {more, undefined};
|
||||
{Value, Rest2} ->
|
||||
unpack_map_(Rest2,Len-1,[{Key,Value}|Acc])
|
||||
end
|
||||
end.
|
||||
|
||||
-spec unpack_(Payload::binary()) ->
|
||||
{more, pos_integer()} | {msgpack_term(), binary()} | {error, reason()}.
|
||||
unpack_(Binary)->
|
||||
case Binary of
|
||||
% ATOMS
|
||||
<<16#C0, Rest/binary>> -> {nil, Rest};
|
||||
<<16#C2, Rest/binary>> -> {false, Rest};
|
||||
<<16#C3, Rest/binary>> -> {true, Rest};
|
||||
% Floats
|
||||
<<16#CA, V:32/float-unit:1, Rest/binary>> -> {V, Rest};
|
||||
<<16#CB, V:64/float-unit:1, Rest/binary>> -> {V, Rest};
|
||||
% Unsigned integers
|
||||
<<16#CC, V:8/unsigned-integer, Rest/binary>> -> {V, Rest};
|
||||
<<16#CD, V:16/big-unsigned-integer-unit:1, Rest/binary>> -> {V, Rest};
|
||||
<<16#CE, V:32/big-unsigned-integer-unit:1, Rest/binary>> -> {V, Rest};
|
||||
<<16#CF, V:64/big-unsigned-integer-unit:1, Rest/binary>> -> {V, Rest};
|
||||
% Signed integers
|
||||
<<16#D0, V:8/signed-integer, Rest/binary>> -> {V, Rest};
|
||||
<<16#D1, V:16/big-signed-integer-unit:1, Rest/binary>> -> {V, Rest};
|
||||
<<16#D2, V:32/big-signed-integer-unit:1, Rest/binary>> -> {V, Rest};
|
||||
<<16#D3, V:64/big-signed-integer-unit:1, Rest/binary>> -> {V, Rest};
|
||||
% Raw bytes
|
||||
<<16#DA, L:16/unsigned-integer-unit:1, V:L/binary, Rest/binary>> -> {V, Rest};
|
||||
<<16#DB, L:32/unsigned-integer-unit:1, V:L/binary, Rest/binary>> -> {V, Rest};
|
||||
% Arrays
|
||||
<<16#DC, L:16/big-unsigned-integer-unit:1, Rest/binary>> -> unpack_array_(Rest, L, []);
|
||||
<<16#DD, L:32/big-unsigned-integer-unit:1, Rest/binary>> -> unpack_array_(Rest, L, []);
|
||||
% Maps
|
||||
<<16#DE, L:16/big-unsigned-integer-unit:1, Rest/binary>> -> unpack_map_(Rest, L, []);
|
||||
<<16#DF, L:32/big-unsigned-integer-unit:1, Rest/binary>> -> unpack_map_(Rest, L, []);
|
||||
|
||||
% Tag-encoded lengths (kept last, for speed)
|
||||
<<0:1, V:7, Rest/binary>> -> {V, Rest}; % positive int
|
||||
<<2#111:3, V:5, Rest/binary>> -> {V - 2#100000, Rest}; % negative int
|
||||
<<2#101:3, L:5, V:L/binary, Rest/binary>> -> {V, Rest}; % raw bytes
|
||||
<<2#1001:4, L:4, Rest/binary>> -> unpack_array_(Rest, L, []); % array
|
||||
<<2#1000:4, L:4, Rest/binary>> -> unpack_map_(Rest, L, []); % map
|
||||
|
||||
% Incomplete / invalid data
|
||||
<<16#CA, Rest/binary>> -> {more, 4-byte_size(Rest)};
|
||||
<<16#CB, Rest/binary>> -> {more, 8-byte_size(Rest)};
|
||||
<<16#CC>> -> {more, 1};
|
||||
<<16#CD, Rest/binary>> -> {more, 2-byte_size(Rest)};
|
||||
<<16#CE, Rest/binary>> -> {more, 4-byte_size(Rest)};
|
||||
<<16#CF, Rest/binary>> -> {more, 8-byte_size(Rest)};
|
||||
<<16#D0>> -> {more, 1};
|
||||
<<16#D1, Rest/binary>> -> {more, 2-byte_size(Rest)};
|
||||
<<16#D2, Rest/binary>> -> {more, 4-byte_size(Rest)};
|
||||
<<16#D3, Rest/binary>> -> {more, 8-byte_size(Rest)};
|
||||
<<16#DA, Rest/binary>> -> {more, 16-byte_size(Rest)};
|
||||
<<16#DB, Rest/binary>> -> {more, 32-byte_size(Rest)};
|
||||
<<16#DC, Rest/binary>> -> {more, 2-byte_size(Rest)};
|
||||
<<16#DD, Rest/binary>> -> {more, 4-byte_size(Rest)};
|
||||
<<16#DE, Rest/binary>> -> {more, 2-byte_size(Rest)};
|
||||
<<16#DF, Rest/binary>> -> {more, 4-byte_size(Rest)};
|
||||
<<2#101:3, L:5, Rest/binary>> -> {more, L-byte_size(Rest)};
|
||||
|
||||
<<>> -> {more, 1};
|
||||
<<2#101:3, _/binary>> -> {more, undefined};
|
||||
<<F:8, Rest/binary>> when F==16#C1;
|
||||
F==16#C7; F==16#C8; F==16#C9; F==16#D5;
|
||||
F==16#D6; F==16#D7; F==16#D8; F==16#D9->
|
||||
{error, {badarg, <<F, Rest/binary>>}};
|
||||
Other ->
|
||||
{error, {badarg, Other}}
|
||||
end.
|
||||
|
||||
|
||||
% ===== test codes ===== %
|
||||
-include_lib("eunit/include/eunit.hrl").
|
||||
-ifdef(EUNIT).
|
||||
|
||||
compare_all([], [])-> ok;
|
||||
compare_all([], R)-> {toomuchrhs, R};
|
||||
compare_all(L, [])-> {toomuchlhs, L};
|
||||
compare_all([LH|LTL], [RH|RTL]) ->
|
||||
LH=RH,
|
||||
compare_all(LTL, RTL).
|
||||
|
||||
test_data()->
|
||||
[true, false, nil,
|
||||
0, 1, 2, 123, 512, 1230, 678908, 16#FFFFFFFFFF,
|
||||
-1, -23, -512, -1230, -567898, -16#FFFFFFFFFF,
|
||||
123.123, -234.4355, 1.0e-34, 1.0e64,
|
||||
[23, 234, 0.23],
|
||||
<<"hogehoge">>, <<"243546rf7g68h798j", 0, 23, 255>>,
|
||||
<<"hoasfdafdas][">>,
|
||||
[0,42, <<"sum">>, [1,2]], [1,42, nil, [3]],
|
||||
-234, -40000, -16#10000000, -16#100000000,
|
||||
42
|
||||
].
|
||||
|
||||
basic_test()->
|
||||
Tests = test_data(),
|
||||
Passed = test_(Tests),
|
||||
Passed = length(Tests).
|
||||
|
||||
port_test()->
|
||||
Tests = test_data(),
|
||||
{[Tests],<<>>} = msgpack:unpack(msgpack:pack([Tests])),
|
||||
Port = open_port({spawn, "ruby ../test/crosslang.rb"}, [binary]),
|
||||
true = port_command(Port, msgpack:pack(Tests) ),
|
||||
receive
|
||||
{Port, {data, Data}}-> {Tests, <<>>}=msgpack:unpack(Data)
|
||||
after 1024-> ?assert(false) end,
|
||||
port_close(Port).
|
||||
|
||||
test_p(Len,Term,OrigBin,Len) ->
|
||||
{Term, <<>>}=msgpack:unpack(OrigBin);
|
||||
test_p(I,_,OrigBin,Len) when I < Len->
|
||||
<<Bin:I/binary, _/binary>> = OrigBin,
|
||||
case msgpack:unpack(Bin) of
|
||||
{more, N} when not is_integer(N) ->
|
||||
?assertEqual(undefined, N);
|
||||
{more, N} ->
|
||||
?assert( N < Len )
|
||||
end.
|
||||
|
||||
partial_test()-> % error handling test.
|
||||
Term = lists:seq(0, 45),
|
||||
Bin=msgpack:pack(Term),
|
||||
BinLen = byte_size(Bin),
|
||||
[test_p(X, Term, Bin, BinLen) || X <- lists:seq(0,BinLen)].
|
||||
|
||||
long_test()->
|
||||
Longer = lists:seq(0, 655),
|
||||
% Longest = lists:seq(0,12345),
|
||||
{Longer, <<>>} = msgpack:unpack(msgpack:pack(Longer)),
|
||||
% {Longest, <<>>} = msgpack:unpack(msgpack:pack(Longest)).
|
||||
ok.
|
||||
|
||||
map_test()->
|
||||
Ints = lists:seq(0, 65),
|
||||
Map = {[ {X, X*2} || X <- Ints ] ++ [{<<"hage">>, 324}, {43542, [nil, true, false]}]},
|
||||
{Map2, <<>>} = msgpack:unpack(msgpack:pack(Map)),
|
||||
?assertEqual(Map, Map2),
|
||||
ok.
|
||||
|
||||
unknown_test()->
|
||||
Tests = [0, 1, 2, 123, 512, 1230, 678908,
|
||||
-1, -23, -512, -1230, -567898,
|
||||
<<"hogehoge">>, <<"243546rf7g68h798j">>,
|
||||
123.123,
|
||||
-234.4355, 1.0e-34, 1.0e64,
|
||||
[23, 234, 0.23],
|
||||
[0,42,<<"sum">>, [1,2]], [1,42, nil, [3]],
|
||||
{[{1,2},{<<"hoge">>,nil}]},
|
||||
-234, -50000,
|
||||
42
|
||||
],
|
||||
Port = open_port({spawn, "ruby testcase_generator.rb"}, [binary]),
|
||||
receive
|
||||
{Port, {data, Data}}->
|
||||
compare_all(Tests, msgpack:unpack_all(Data))
|
||||
after 1024-> ?assert(false) end,
|
||||
port_close(Port).
|
||||
|
||||
test_([]) -> 0;
|
||||
test_([Before|Rest])->
|
||||
Pack = msgpack:pack(Before),
|
||||
{After, <<>>} = msgpack:unpack( Pack ),
|
||||
?assertEqual(Before, After),
|
||||
1+test_(Rest).
|
||||
|
||||
other_test()->
|
||||
{more,1}=msgpack:unpack(<<>>).
|
||||
|
||||
-endif.
|
@@ -1,65 +0,0 @@
|
||||
begin
|
||||
require 'rubygems'
|
||||
rescue LoadError
|
||||
end
|
||||
require 'msgpack'
|
||||
|
||||
def usage
|
||||
puts <<EOF
|
||||
Usage: #{$0} [out-file]
|
||||
|
||||
This tool is for testing of accepting MessagePack random-term.
|
||||
This does following behavior:
|
||||
|
||||
1. serializes the objects in this file, using Ruby implementation
|
||||
of MessagePack (Note that Ruby implementation is considered valid)
|
||||
2. Writes the serialized binaries into <out-file> (default: stdout)
|
||||
|
||||
EOF
|
||||
exit 1
|
||||
end
|
||||
|
||||
code = 1
|
||||
outio = $stdout
|
||||
|
||||
if ARGV.length > 2
|
||||
usage
|
||||
end
|
||||
|
||||
if fname = ARGV[0]
|
||||
unless fname == "-"
|
||||
begin
|
||||
outio = File.open(fname, "w")
|
||||
rescue
|
||||
puts "can't open output file: #{$!}"
|
||||
exit 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
objs = [0, 1, 2, 123, 512, 1230, 678908,
|
||||
-1, -23, -512, -1230, -567898,
|
||||
"hogehoge", "243546rf7g68h798j",
|
||||
123.123,
|
||||
-234.4355, 1.0e-34, 1.0e64,
|
||||
[23, 234, 0.23],
|
||||
[0,42,"sum", [1,2]], [1,42, nil, [3]],
|
||||
{ 1 => 2, "hoge" => nil },
|
||||
-234, -50000,
|
||||
42
|
||||
]
|
||||
begin
|
||||
objs.each do |obj|
|
||||
outio.write MessagePack.pack(obj)
|
||||
outio.flush
|
||||
end
|
||||
rescue EOFError
|
||||
code=0
|
||||
rescue
|
||||
$stderr.puts $!
|
||||
code=1
|
||||
end
|
||||
|
||||
outio.close
|
||||
exit code
|
||||
|
@@ -17,7 +17,7 @@ namespace myprotocol {
|
||||
|
||||
struct Put : define< tuple<uint32_t, std::string, raw_ref> > {
|
||||
Put() { }
|
||||
Put(uint32_t f, const std::string& k, const char* valref, size_t vallen) :
|
||||
Put(uint32_t f, const std::string& k, const char* valref, uint32_t vallen) :
|
||||
define_type(msgpack_type( f, k, raw_ref(valref,vallen) )) { }
|
||||
uint32_t& flags() { return get<0>(); }
|
||||
std::string& key() { return get<1>(); }
|
||||
|
@@ -1,5 +0,0 @@
|
||||
require 'msgpack'
|
||||
|
||||
serialized = [1, -1, true, false, nil, {"key" => "value"}].to_msgpack
|
||||
p MessagePack.unpack(serialized)
|
||||
|
36
example/speed_test_uint32_array.c
Normal file
36
example/speed_test_uint32_array.c
Normal file
@@ -0,0 +1,36 @@
|
||||
#include <msgpack.h>
|
||||
#include <assert.h>
|
||||
|
||||
void test()
|
||||
{
|
||||
size_t size = 10000000;
|
||||
msgpack_sbuffer buf;
|
||||
msgpack_sbuffer_init(&buf);
|
||||
|
||||
msgpack_packer * pk = msgpack_packer_new(&buf, msgpack_sbuffer_write);
|
||||
|
||||
msgpack_pack_array(pk, size);
|
||||
{
|
||||
int idx = 0;
|
||||
for (; idx < size; ++idx)
|
||||
msgpack_pack_uint32(pk, 1);
|
||||
}
|
||||
msgpack_packer_free(pk);
|
||||
|
||||
|
||||
size_t upk_pos = 0;
|
||||
msgpack_unpacked msg;
|
||||
msgpack_unpacked_init(&msg);
|
||||
|
||||
while (msgpack_unpack_next(&msg, buf.data, buf.size, &upk_pos)) {
|
||||
}
|
||||
|
||||
msgpack_sbuffer_destroy(&buf);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int i = 0;
|
||||
for (; i < 10; ++i) test();
|
||||
return 0;
|
||||
}
|
37
example/speed_test_uint64_array.c
Normal file
37
example/speed_test_uint64_array.c
Normal file
@@ -0,0 +1,37 @@
|
||||
#include <msgpack.h>
|
||||
#include <assert.h>
|
||||
|
||||
void test()
|
||||
{
|
||||
uint64_t test_u64 = 0xFFF0000000000001LL;
|
||||
size_t size = 10000000;
|
||||
msgpack_sbuffer buf;
|
||||
msgpack_sbuffer_init(&buf);
|
||||
|
||||
msgpack_packer * pk = msgpack_packer_new(&buf, msgpack_sbuffer_write);
|
||||
|
||||
msgpack_pack_array(pk, size);
|
||||
{
|
||||
int idx = 0;
|
||||
for (; idx < size; ++idx)
|
||||
msgpack_pack_uint64(pk, test_u64);
|
||||
}
|
||||
msgpack_packer_free(pk);
|
||||
|
||||
|
||||
size_t upk_pos = 0;
|
||||
msgpack_unpacked msg;
|
||||
msgpack_unpacked_init(&msg);
|
||||
|
||||
while (msgpack_unpack_next(&msg, buf.data, buf.size, &upk_pos)) {
|
||||
}
|
||||
|
||||
msgpack_sbuffer_destroy(&buf);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int i = 0;
|
||||
for (; i < 10; ++i) test();
|
||||
return 0;
|
||||
}
|
@@ -1,72 +0,0 @@
|
||||
require 'msgpack'
|
||||
|
||||
class Server
|
||||
def initialize(sock)
|
||||
@sock = sock
|
||||
@pk = MessagePack::Unpacker.new
|
||||
@buffer = ''
|
||||
@nread = 0
|
||||
end
|
||||
|
||||
def run
|
||||
while true
|
||||
begin
|
||||
data = @sock.sysread(1024)
|
||||
rescue
|
||||
puts "connection closed (#{$!})"
|
||||
return
|
||||
end
|
||||
receive_data(data)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def receive_data(data)
|
||||
@buffer << data
|
||||
|
||||
while true
|
||||
@nread = @pk.execute(@buffer, @nread)
|
||||
|
||||
if @pk.finished?
|
||||
msg = @pk.data
|
||||
process_message(msg)
|
||||
|
||||
@pk.reset
|
||||
@buffer.slice!(0, @nread)
|
||||
@nread = 0
|
||||
|
||||
next unless @buffer.empty?
|
||||
end
|
||||
|
||||
break
|
||||
end
|
||||
|
||||
if @buffer.length > 10*1024*1024
|
||||
raise "message is too large"
|
||||
end
|
||||
|
||||
rescue
|
||||
puts "error while processing client packet: #{$!}"
|
||||
end
|
||||
|
||||
def process_message(msg)
|
||||
puts "message reached: #{msg.inspect}"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
rpipe, wpipe = IO.pipe
|
||||
|
||||
# run server thread
|
||||
thread = Thread.new(Server.new(rpipe)) {|srv|
|
||||
srv.run
|
||||
}
|
||||
|
||||
# client thread:
|
||||
wpipe.write ["put", "apple", "red"].to_msgpack
|
||||
wpipe.write ["put", "lemon", "yellow"].to_msgpack
|
||||
wpipe.write ["get", "apple"].to_msgpack
|
||||
wpipe.close
|
||||
|
||||
thread.join
|
||||
|
@@ -1,24 +0,0 @@
|
||||
Copyright (c) 2009, Hideyuki Tanaka
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the Hideyuki Tanaka nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY Hideyuki Tanaka ''AS IS'' AND ANY
|
||||
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
@@ -1,3 +0,0 @@
|
||||
#!/usr/bin/env runhaskell
|
||||
> import Distribution.Simple
|
||||
> main = defaultMain
|
@@ -1,137 +0,0 @@
|
||||
#include <msgpack.h>
|
||||
|
||||
void msgpack_sbuffer_init_wrap(msgpack_sbuffer* sbuf)
|
||||
{
|
||||
msgpack_sbuffer_init(sbuf);
|
||||
}
|
||||
|
||||
void msgpack_sbuffer_destroy_wrap(msgpack_sbuffer* sbuf)
|
||||
{
|
||||
msgpack_sbuffer_destroy(sbuf);
|
||||
}
|
||||
|
||||
int msgpack_sbuffer_write_wrap(void* data, const char* buf, unsigned int len)
|
||||
{
|
||||
return msgpack_sbuffer_write(data, buf, len);
|
||||
}
|
||||
|
||||
msgpack_packer* msgpack_packer_new_wrap(void *data, msgpack_packer_write callback)
|
||||
{
|
||||
return msgpack_packer_new(data, callback);
|
||||
}
|
||||
|
||||
void msgpack_packer_free_wrap(msgpack_packer* pk)
|
||||
{
|
||||
msgpack_packer_free(pk);
|
||||
}
|
||||
|
||||
int msgpack_pack_uint8_wrap(msgpack_packer* pk, uint8_t d)
|
||||
{
|
||||
return msgpack_pack_uint8(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_uint16_wrap(msgpack_packer* pk, uint16_t d)
|
||||
{
|
||||
return msgpack_pack_uint16(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_uint32_wrap(msgpack_packer* pk, uint32_t d)
|
||||
{
|
||||
return msgpack_pack_uint32(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_uint64_wrap(msgpack_packer* pk, uint64_t d)
|
||||
{
|
||||
return msgpack_pack_uint64(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_int8_wrap(msgpack_packer* pk, int8_t d)
|
||||
{
|
||||
return msgpack_pack_int8(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_int16_wrap(msgpack_packer* pk, int16_t d)
|
||||
{
|
||||
return msgpack_pack_int16(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_int32_wrap(msgpack_packer* pk, int32_t d)
|
||||
{
|
||||
return msgpack_pack_int32(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_int64_wrap(msgpack_packer* pk, int64_t d)
|
||||
{
|
||||
return msgpack_pack_int64(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_double_wrap(msgpack_packer* pk, double d)
|
||||
{
|
||||
return msgpack_pack_double(pk, d);
|
||||
}
|
||||
|
||||
int msgpack_pack_nil_wrap(msgpack_packer* pk)
|
||||
{
|
||||
return msgpack_pack_nil(pk);
|
||||
}
|
||||
|
||||
int msgpack_pack_true_wrap(msgpack_packer* pk)
|
||||
{
|
||||
return msgpack_pack_true(pk);
|
||||
}
|
||||
|
||||
int msgpack_pack_false_wrap(msgpack_packer* pk)
|
||||
{
|
||||
return msgpack_pack_false(pk);
|
||||
}
|
||||
|
||||
int msgpack_pack_array_wrap(msgpack_packer* pk, unsigned int n)
|
||||
{
|
||||
return msgpack_pack_array(pk, n);
|
||||
}
|
||||
|
||||
int msgpack_pack_map_wrap(msgpack_packer* pk, unsigned int n)
|
||||
{
|
||||
return msgpack_pack_map(pk, n);
|
||||
}
|
||||
|
||||
int msgpack_pack_raw_wrap(msgpack_packer* pk, size_t l)
|
||||
{
|
||||
return msgpack_pack_raw(pk, l);
|
||||
}
|
||||
|
||||
int msgpack_pack_raw_body_wrap(msgpack_packer* pk, const void *b, size_t l)
|
||||
{
|
||||
return msgpack_pack_raw_body(pk, b, l);
|
||||
}
|
||||
|
||||
bool msgpack_unpacker_reserve_buffer_wrap(msgpack_unpacker *mpac, size_t size)
|
||||
{
|
||||
return msgpack_unpacker_reserve_buffer(mpac, size);
|
||||
}
|
||||
|
||||
char *msgpack_unpacker_buffer_wrap(msgpack_unpacker *mpac)
|
||||
{
|
||||
return msgpack_unpacker_buffer(mpac);
|
||||
}
|
||||
|
||||
size_t msgpack_unpacker_buffer_capacity_wrap(const msgpack_unpacker *mpac)
|
||||
{
|
||||
return msgpack_unpacker_buffer_capacity(mpac);
|
||||
}
|
||||
|
||||
void msgpack_unpacker_buffer_consumed_wrap(msgpack_unpacker *mpac, size_t size)
|
||||
{
|
||||
msgpack_unpacker_buffer_consumed(mpac, size);
|
||||
}
|
||||
|
||||
void msgpack_unpacker_data_wrap(msgpack_unpacker *mpac, msgpack_object *obj)
|
||||
{
|
||||
*obj=msgpack_unpacker_data(mpac);
|
||||
}
|
||||
|
||||
size_t msgpack_unpacker_message_size_wrap(const msgpack_unpacker *mpac)
|
||||
{
|
||||
return msgpack_unpacker_message_size(mpac);
|
||||
}
|
||||
|
@@ -1,32 +0,0 @@
|
||||
Name: msgpack
|
||||
Version: 0.2.2
|
||||
License: BSD3
|
||||
License-File: LICENSE
|
||||
Author: Hideyuki Tanaka
|
||||
Maintainer: Hideyuki Tanaka <tanaka.hideyuki@gmail.com>
|
||||
Category: Data
|
||||
Synopsis: A Haskell binding to MessagePack
|
||||
Description:
|
||||
A Haskell binding to MessagePack <http://msgpack.sourceforge.jp/>
|
||||
Homepage: http://github.com/tanakh/hsmsgpack
|
||||
Stability: Experimental
|
||||
Tested-with: GHC==6.10.4
|
||||
Cabal-Version: >=1.2
|
||||
Build-Type: Simple
|
||||
|
||||
library
|
||||
build-depends: base>=4 && <5, mtl, bytestring
|
||||
ghc-options: -O2 -Wall
|
||||
hs-source-dirs: src
|
||||
extra-libraries: msgpackc
|
||||
|
||||
Exposed-modules:
|
||||
Data.MessagePack
|
||||
Data.MessagePack.Base
|
||||
Data.MessagePack.Class
|
||||
Data.MessagePack.Feed
|
||||
Data.MessagePack.Monad
|
||||
Data.MessagePack.Stream
|
||||
|
||||
C-Sources:
|
||||
cbits/msgpack.c
|
@@ -1,63 +0,0 @@
|
||||
--------------------------------------------------------------------
|
||||
-- |
|
||||
-- Module : Data.MessagePack
|
||||
-- Copyright : (c) Hideyuki Tanaka, 2009
|
||||
-- License : BSD3
|
||||
--
|
||||
-- Maintainer: tanaka.hideyuki@gmail.com
|
||||
-- Stability : experimental
|
||||
-- Portability: portable
|
||||
--
|
||||
-- Simple interface to pack and unpack MessagePack data.
|
||||
--
|
||||
--------------------------------------------------------------------
|
||||
|
||||
module Data.MessagePack(
|
||||
module Data.MessagePack.Base,
|
||||
module Data.MessagePack.Class,
|
||||
module Data.MessagePack.Feed,
|
||||
module Data.MessagePack.Monad,
|
||||
module Data.MessagePack.Stream,
|
||||
|
||||
-- * Pack and Unpack
|
||||
packb,
|
||||
unpackb,
|
||||
|
||||
-- * Pure version of Pack and Unpack
|
||||
packb',
|
||||
unpackb',
|
||||
) where
|
||||
|
||||
import Data.ByteString (ByteString)
|
||||
import System.IO.Unsafe
|
||||
|
||||
import Data.MessagePack.Base
|
||||
import Data.MessagePack.Class
|
||||
import Data.MessagePack.Feed
|
||||
import Data.MessagePack.Monad
|
||||
import Data.MessagePack.Stream
|
||||
|
||||
-- | Pack Haskell data to MessagePack string.
|
||||
packb :: OBJECT a => a -> IO ByteString
|
||||
packb dat = do
|
||||
sb <- newSimpleBuffer
|
||||
pc <- newPacker sb
|
||||
pack pc dat
|
||||
simpleBufferData sb
|
||||
|
||||
-- | Unpack MessagePack string to Haskell data.
|
||||
unpackb :: OBJECT a => ByteString -> IO (Result a)
|
||||
unpackb bs = do
|
||||
withZone $ \z -> do
|
||||
r <- unpackObject z bs
|
||||
return $ case r of
|
||||
Left err -> Left (show err)
|
||||
Right (_, dat) -> fromObject dat
|
||||
|
||||
-- | Pure version of 'packb'.
|
||||
packb' :: OBJECT a => a -> ByteString
|
||||
packb' dat = unsafePerformIO $ packb dat
|
||||
|
||||
-- | Pure version of 'unpackb'.
|
||||
unpackb' :: OBJECT a => ByteString -> Result a
|
||||
unpackb' bs = unsafePerformIO $ unpackb bs
|
@@ -1,584 +0,0 @@
|
||||
{-# LANGUAGE CPP #-}
|
||||
{-# LANGUAGE ForeignFunctionInterface #-}
|
||||
|
||||
--------------------------------------------------------------------
|
||||
-- |
|
||||
-- Module : Data.MessagePack.Base
|
||||
-- Copyright : (c) Hideyuki Tanaka, 2009
|
||||
-- License : BSD3
|
||||
--
|
||||
-- Maintainer: tanaka.hideyuki@gmail.com
|
||||
-- Stability : experimental
|
||||
-- Portability: portable
|
||||
--
|
||||
-- Low Level Interface to MessagePack C API
|
||||
--
|
||||
--------------------------------------------------------------------
|
||||
|
||||
module Data.MessagePack.Base(
|
||||
-- * Simple Buffer
|
||||
SimpleBuffer,
|
||||
newSimpleBuffer,
|
||||
simpleBufferData,
|
||||
|
||||
-- * Serializer
|
||||
Packer,
|
||||
newPacker,
|
||||
|
||||
packU8,
|
||||
packU16,
|
||||
packU32,
|
||||
packU64,
|
||||
packS8,
|
||||
packS16,
|
||||
packS32,
|
||||
packS64,
|
||||
|
||||
packTrue,
|
||||
packFalse,
|
||||
|
||||
packInt,
|
||||
packDouble,
|
||||
packNil,
|
||||
packBool,
|
||||
|
||||
packArray,
|
||||
packMap,
|
||||
packRAW,
|
||||
packRAWBody,
|
||||
packRAW',
|
||||
|
||||
-- * Stream Deserializer
|
||||
Unpacker,
|
||||
defaultInitialBufferSize,
|
||||
newUnpacker,
|
||||
unpackerReserveBuffer,
|
||||
unpackerBuffer,
|
||||
unpackerBufferCapacity,
|
||||
unpackerBufferConsumed,
|
||||
unpackerFeed,
|
||||
unpackerExecute,
|
||||
unpackerData,
|
||||
unpackerReleaseZone,
|
||||
unpackerResetZone,
|
||||
unpackerReset,
|
||||
unpackerMessageSize,
|
||||
|
||||
-- * MessagePack Object
|
||||
Object(..),
|
||||
packObject,
|
||||
|
||||
UnpackReturn(..),
|
||||
unpackObject,
|
||||
|
||||
-- * Memory Zone
|
||||
Zone,
|
||||
newZone,
|
||||
freeZone,
|
||||
withZone,
|
||||
) where
|
||||
|
||||
import Control.Exception
|
||||
import Control.Monad
|
||||
import Data.ByteString (ByteString)
|
||||
import qualified Data.ByteString as BS hiding (pack, unpack)
|
||||
import Data.Int
|
||||
import Data.Word
|
||||
import Foreign.C
|
||||
import Foreign.Concurrent
|
||||
import Foreign.ForeignPtr hiding (newForeignPtr)
|
||||
import Foreign.Marshal.Alloc
|
||||
import Foreign.Marshal.Array
|
||||
import Foreign.Ptr
|
||||
import Foreign.Storable
|
||||
|
||||
#include <msgpack.h>
|
||||
|
||||
type SimpleBuffer = ForeignPtr ()
|
||||
|
||||
type WriteCallback = Ptr () -> CString -> CUInt -> IO CInt
|
||||
|
||||
-- | Create a new Simple Buffer. It will be deleted automatically.
|
||||
newSimpleBuffer :: IO SimpleBuffer
|
||||
newSimpleBuffer = do
|
||||
ptr <- mallocBytes (#size msgpack_sbuffer)
|
||||
fptr <- newForeignPtr ptr $ do
|
||||
msgpack_sbuffer_destroy ptr
|
||||
free ptr
|
||||
withForeignPtr fptr $ \p ->
|
||||
msgpack_sbuffer_init p
|
||||
return fptr
|
||||
|
||||
-- | Get data of Simple Buffer.
|
||||
simpleBufferData :: SimpleBuffer -> IO ByteString
|
||||
simpleBufferData sb =
|
||||
withForeignPtr sb $ \ptr -> do
|
||||
size <- (#peek msgpack_sbuffer, size) ptr
|
||||
dat <- (#peek msgpack_sbuffer, data) ptr
|
||||
BS.packCStringLen (dat, fromIntegral (size :: CSize))
|
||||
|
||||
foreign import ccall "msgpack_sbuffer_init_wrap" msgpack_sbuffer_init ::
|
||||
Ptr () -> IO ()
|
||||
|
||||
foreign import ccall "msgpack_sbuffer_destroy_wrap" msgpack_sbuffer_destroy ::
|
||||
Ptr () -> IO ()
|
||||
|
||||
foreign import ccall "msgpack_sbuffer_write_wrap" msgpack_sbuffer_write ::
|
||||
WriteCallback
|
||||
|
||||
type Packer = ForeignPtr ()
|
||||
|
||||
-- | Create new Packer. It will be deleted automatically.
|
||||
newPacker :: SimpleBuffer -> IO Packer
|
||||
newPacker sbuf = do
|
||||
cb <- wrap_callback msgpack_sbuffer_write
|
||||
ptr <- withForeignPtr sbuf $ \ptr ->
|
||||
msgpack_packer_new ptr cb
|
||||
fptr <- newForeignPtr ptr $ do
|
||||
msgpack_packer_free ptr
|
||||
return fptr
|
||||
|
||||
foreign import ccall "msgpack_packer_new_wrap" msgpack_packer_new ::
|
||||
Ptr () -> FunPtr WriteCallback -> IO (Ptr ())
|
||||
|
||||
foreign import ccall "msgpack_packer_free_wrap" msgpack_packer_free ::
|
||||
Ptr () -> IO ()
|
||||
|
||||
foreign import ccall "wrapper" wrap_callback ::
|
||||
WriteCallback -> IO (FunPtr WriteCallback)
|
||||
|
||||
packU8 :: Packer -> Word8 -> IO Int
|
||||
packU8 pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_uint8 ptr n
|
||||
|
||||
foreign import ccall "msgpack_pack_uint8_wrap" msgpack_pack_uint8 ::
|
||||
Ptr () -> Word8 -> IO CInt
|
||||
|
||||
packU16 :: Packer -> Word16 -> IO Int
|
||||
packU16 pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_uint16 ptr n
|
||||
|
||||
foreign import ccall "msgpack_pack_uint16_wrap" msgpack_pack_uint16 ::
|
||||
Ptr () -> Word16 -> IO CInt
|
||||
|
||||
packU32 :: Packer -> Word32 -> IO Int
|
||||
packU32 pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_uint32 ptr n
|
||||
|
||||
foreign import ccall "msgpack_pack_uint32_wrap" msgpack_pack_uint32 ::
|
||||
Ptr () -> Word32 -> IO CInt
|
||||
|
||||
packU64 :: Packer -> Word64 -> IO Int
|
||||
packU64 pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_uint64 ptr n
|
||||
|
||||
foreign import ccall "msgpack_pack_uint64_wrap" msgpack_pack_uint64 ::
|
||||
Ptr () -> Word64 -> IO CInt
|
||||
|
||||
packS8 :: Packer -> Int8 -> IO Int
|
||||
packS8 pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_int8 ptr n
|
||||
|
||||
foreign import ccall "msgpack_pack_int8_wrap" msgpack_pack_int8 ::
|
||||
Ptr () -> Int8 -> IO CInt
|
||||
|
||||
packS16 :: Packer -> Int16 -> IO Int
|
||||
packS16 pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_int16 ptr n
|
||||
|
||||
foreign import ccall "msgpack_pack_int16_wrap" msgpack_pack_int16 ::
|
||||
Ptr () -> Int16 -> IO CInt
|
||||
|
||||
packS32 :: Packer -> Int32 -> IO Int
|
||||
packS32 pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_int32 ptr n
|
||||
|
||||
foreign import ccall "msgpack_pack_int32_wrap" msgpack_pack_int32 ::
|
||||
Ptr () -> Int32 -> IO CInt
|
||||
|
||||
packS64 :: Packer -> Int64 -> IO Int
|
||||
packS64 pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_int64 ptr n
|
||||
|
||||
foreign import ccall "msgpack_pack_int64_wrap" msgpack_pack_int64 ::
|
||||
Ptr () -> Int64 -> IO CInt
|
||||
|
||||
-- | Pack an integral data.
|
||||
packInt :: Integral a => Packer -> a -> IO Int
|
||||
packInt pc n = packS64 pc $ fromIntegral n
|
||||
|
||||
-- | Pack a double data.
|
||||
packDouble :: Packer -> Double -> IO Int
|
||||
packDouble pc d =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_double ptr (realToFrac d)
|
||||
|
||||
foreign import ccall "msgpack_pack_double_wrap" msgpack_pack_double ::
|
||||
Ptr () -> CDouble -> IO CInt
|
||||
|
||||
-- | Pack a nil.
|
||||
packNil :: Packer -> IO Int
|
||||
packNil pc =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_nil ptr
|
||||
|
||||
foreign import ccall "msgpack_pack_nil_wrap" msgpack_pack_nil ::
|
||||
Ptr () -> IO CInt
|
||||
|
||||
packTrue :: Packer -> IO Int
|
||||
packTrue pc =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_true ptr
|
||||
|
||||
foreign import ccall "msgpack_pack_true_wrap" msgpack_pack_true ::
|
||||
Ptr () -> IO CInt
|
||||
|
||||
packFalse :: Packer -> IO Int
|
||||
packFalse pc =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_false ptr
|
||||
|
||||
foreign import ccall "msgpack_pack_false_wrap" msgpack_pack_false ::
|
||||
Ptr () -> IO CInt
|
||||
|
||||
-- | Pack a bool data.
|
||||
packBool :: Packer -> Bool -> IO Int
|
||||
packBool pc True = packTrue pc
|
||||
packBool pc False = packFalse pc
|
||||
|
||||
-- | 'packArray' @p n@ starts packing an array.
|
||||
-- Next @n@ data will consist this array.
|
||||
packArray :: Packer -> Int -> IO Int
|
||||
packArray pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_array ptr (fromIntegral n)
|
||||
|
||||
foreign import ccall "msgpack_pack_array_wrap" msgpack_pack_array ::
|
||||
Ptr () -> CUInt -> IO CInt
|
||||
|
||||
-- | 'packMap' @p n@ starts packing a map.
|
||||
-- Next @n@ pairs of data (2*n data) will consist this map.
|
||||
packMap :: Packer -> Int -> IO Int
|
||||
packMap pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_map ptr (fromIntegral n)
|
||||
|
||||
foreign import ccall "msgpack_pack_map_wrap" msgpack_pack_map ::
|
||||
Ptr () -> CUInt -> IO CInt
|
||||
|
||||
-- | 'packRAW' @p n@ starts packing a byte sequence.
|
||||
-- Next total @n@ bytes of 'packRAWBody' call will consist this sequence.
|
||||
packRAW :: Packer -> Int -> IO Int
|
||||
packRAW pc n =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
msgpack_pack_raw ptr (fromIntegral n)
|
||||
|
||||
foreign import ccall "msgpack_pack_raw_wrap" msgpack_pack_raw ::
|
||||
Ptr () -> CSize -> IO CInt
|
||||
|
||||
-- | Pack a byte sequence.
|
||||
packRAWBody :: Packer -> ByteString -> IO Int
|
||||
packRAWBody pc bs =
|
||||
liftM fromIntegral $ withForeignPtr pc $ \ptr ->
|
||||
BS.useAsCStringLen bs $ \(str, len) ->
|
||||
msgpack_pack_raw_body ptr (castPtr str) (fromIntegral len)
|
||||
|
||||
foreign import ccall "msgpack_pack_raw_body_wrap" msgpack_pack_raw_body ::
|
||||
Ptr () -> Ptr () -> CSize -> IO CInt
|
||||
|
||||
-- | Pack a single byte stream. It calls 'packRAW' and 'packRAWBody'.
|
||||
packRAW' :: Packer -> ByteString -> IO Int
|
||||
packRAW' pc bs = do
|
||||
_ <- packRAW pc (BS.length bs)
|
||||
packRAWBody pc bs
|
||||
|
||||
type Unpacker = ForeignPtr ()
|
||||
|
||||
defaultInitialBufferSize :: Int
|
||||
defaultInitialBufferSize = 32 * 1024 -- #const MSGPACK_UNPACKER_DEFAULT_INITIAL_BUFFER_SIZE
|
||||
|
||||
-- | 'newUnpacker' @initialBufferSize@ creates a new Unpacker. It will be deleted automatically.
|
||||
newUnpacker :: Int -> IO Unpacker
|
||||
newUnpacker initialBufferSize = do
|
||||
ptr <- msgpack_unpacker_new (fromIntegral initialBufferSize)
|
||||
fptr <- newForeignPtr ptr $ do
|
||||
msgpack_unpacker_free ptr
|
||||
return fptr
|
||||
|
||||
foreign import ccall "msgpack_unpacker_new" msgpack_unpacker_new ::
|
||||
CSize -> IO (Ptr ())
|
||||
|
||||
foreign import ccall "msgpack_unpacker_free" msgpack_unpacker_free ::
|
||||
Ptr() -> IO ()
|
||||
|
||||
-- | 'unpackerReserveBuffer' @up size@ reserves at least @size@ bytes of buffer.
|
||||
unpackerReserveBuffer :: Unpacker -> Int -> IO Bool
|
||||
unpackerReserveBuffer up size =
|
||||
withForeignPtr up $ \ptr ->
|
||||
liftM (/=0) $ msgpack_unpacker_reserve_buffer ptr (fromIntegral size)
|
||||
|
||||
foreign import ccall "msgpack_unpacker_reserve_buffer_wrap" msgpack_unpacker_reserve_buffer ::
|
||||
Ptr () -> CSize -> IO CChar
|
||||
|
||||
-- | Get a pointer of unpacker buffer.
|
||||
unpackerBuffer :: Unpacker -> IO (Ptr CChar)
|
||||
unpackerBuffer up =
|
||||
withForeignPtr up $ \ptr ->
|
||||
msgpack_unpacker_buffer ptr
|
||||
|
||||
foreign import ccall "msgpack_unpacker_buffer_wrap" msgpack_unpacker_buffer ::
|
||||
Ptr () -> IO (Ptr CChar)
|
||||
|
||||
-- | Get size of allocated buffer.
|
||||
unpackerBufferCapacity :: Unpacker -> IO Int
|
||||
unpackerBufferCapacity up =
|
||||
withForeignPtr up $ \ptr ->
|
||||
liftM fromIntegral $ msgpack_unpacker_buffer_capacity ptr
|
||||
|
||||
foreign import ccall "msgpack_unpacker_buffer_capacity_wrap" msgpack_unpacker_buffer_capacity ::
|
||||
Ptr () -> IO CSize
|
||||
|
||||
-- | 'unpackerBufferConsumed' @up size@ notices that writed @size@ bytes to buffer.
|
||||
unpackerBufferConsumed :: Unpacker -> Int -> IO ()
|
||||
unpackerBufferConsumed up size =
|
||||
withForeignPtr up $ \ptr ->
|
||||
msgpack_unpacker_buffer_consumed ptr (fromIntegral size)
|
||||
|
||||
foreign import ccall "msgpack_unpacker_buffer_consumed_wrap" msgpack_unpacker_buffer_consumed ::
|
||||
Ptr () -> CSize -> IO ()
|
||||
|
||||
-- | Write byte sequence to Unpacker. It is utility funciton, calls 'unpackerReserveBuffer', 'unpackerBuffer' and 'unpackerBufferConsumed'.
|
||||
unpackerFeed :: Unpacker -> ByteString -> IO ()
|
||||
unpackerFeed up bs =
|
||||
BS.useAsCStringLen bs $ \(str, len) -> do
|
||||
True <- unpackerReserveBuffer up len
|
||||
ptr <- unpackerBuffer up
|
||||
copyArray ptr str len
|
||||
unpackerBufferConsumed up len
|
||||
|
||||
-- | Execute deserializing. It returns 0 when buffer contains not enough bytes, returns 1 when succeeded, returns negative value when it failed.
|
||||
unpackerExecute :: Unpacker -> IO Int
|
||||
unpackerExecute up =
|
||||
withForeignPtr up $ \ptr ->
|
||||
liftM fromIntegral $ msgpack_unpacker_execute ptr
|
||||
|
||||
foreign import ccall "msgpack_unpacker_execute" msgpack_unpacker_execute ::
|
||||
Ptr () -> IO CInt
|
||||
|
||||
-- | Returns a deserialized object when 'unpackerExecute' returned 1.
|
||||
unpackerData :: Unpacker -> IO Object
|
||||
unpackerData up =
|
||||
withForeignPtr up $ \ptr ->
|
||||
allocaBytes (#size msgpack_object) $ \pobj -> do
|
||||
msgpack_unpacker_data ptr pobj
|
||||
peekObject pobj
|
||||
|
||||
foreign import ccall "msgpack_unpacker_data_wrap" msgpack_unpacker_data ::
|
||||
Ptr () -> Ptr () -> IO ()
|
||||
|
||||
-- | Release memory zone. The returned zone must be freed by calling 'freeZone'.
|
||||
unpackerReleaseZone :: Unpacker -> IO Zone
|
||||
unpackerReleaseZone up =
|
||||
withForeignPtr up $ \ptr ->
|
||||
msgpack_unpacker_release_zone ptr
|
||||
|
||||
foreign import ccall "msgpack_unpacker_release_zone" msgpack_unpacker_release_zone ::
|
||||
Ptr () -> IO (Ptr ())
|
||||
|
||||
-- | Free memory zone used by Unapcker.
|
||||
unpackerResetZone :: Unpacker -> IO ()
|
||||
unpackerResetZone up =
|
||||
withForeignPtr up $ \ptr ->
|
||||
msgpack_unpacker_reset_zone ptr
|
||||
|
||||
foreign import ccall "msgpack_unpacker_reset_zone" msgpack_unpacker_reset_zone ::
|
||||
Ptr () -> IO ()
|
||||
|
||||
-- | Reset Unpacker state except memory zone.
|
||||
unpackerReset :: Unpacker -> IO ()
|
||||
unpackerReset up =
|
||||
withForeignPtr up $ \ptr ->
|
||||
msgpack_unpacker_reset ptr
|
||||
|
||||
foreign import ccall "msgpack_unpacker_reset" msgpack_unpacker_reset ::
|
||||
Ptr () -> IO ()
|
||||
|
||||
-- | Returns number of bytes of sequence of deserializing object.
|
||||
unpackerMessageSize :: Unpacker -> IO Int
|
||||
unpackerMessageSize up =
|
||||
withForeignPtr up $ \ptr ->
|
||||
liftM fromIntegral $ msgpack_unpacker_message_size ptr
|
||||
|
||||
foreign import ccall "msgpack_unpacker_message_size_wrap" msgpack_unpacker_message_size ::
|
||||
Ptr () -> IO CSize
|
||||
|
||||
type Zone = Ptr ()
|
||||
|
||||
-- | Create a new memory zone. It must be freed manually.
|
||||
newZone :: IO Zone
|
||||
newZone =
|
||||
msgpack_zone_new (#const MSGPACK_ZONE_CHUNK_SIZE)
|
||||
|
||||
-- | Free a memory zone.
|
||||
freeZone :: Zone -> IO ()
|
||||
freeZone z =
|
||||
msgpack_zone_free z
|
||||
|
||||
-- | Create a memory zone, then execute argument, then free memory zone.
|
||||
withZone :: (Zone -> IO a) -> IO a
|
||||
withZone z =
|
||||
bracket newZone freeZone z
|
||||
|
||||
foreign import ccall "msgpack_zone_new" msgpack_zone_new ::
|
||||
CSize -> IO Zone
|
||||
|
||||
foreign import ccall "msgpack_zone_free" msgpack_zone_free ::
|
||||
Zone -> IO ()
|
||||
|
||||
-- | Object Representation of MessagePack data.
|
||||
data Object =
|
||||
ObjectNil
|
||||
| ObjectBool Bool
|
||||
| ObjectInteger Int
|
||||
| ObjectDouble Double
|
||||
| ObjectRAW ByteString
|
||||
| ObjectArray [Object]
|
||||
| ObjectMap [(Object, Object)]
|
||||
deriving (Show)
|
||||
|
||||
peekObject :: Ptr a -> IO Object
|
||||
peekObject ptr = do
|
||||
typ <- (#peek msgpack_object, type) ptr
|
||||
case (typ :: CInt) of
|
||||
(#const MSGPACK_OBJECT_NIL) ->
|
||||
return ObjectNil
|
||||
(#const MSGPACK_OBJECT_BOOLEAN) ->
|
||||
peekObjectBool ptr
|
||||
(#const MSGPACK_OBJECT_POSITIVE_INTEGER) ->
|
||||
peekObjectPositiveInteger ptr
|
||||
(#const MSGPACK_OBJECT_NEGATIVE_INTEGER) ->
|
||||
peekObjectNegativeInteger ptr
|
||||
(#const MSGPACK_OBJECT_DOUBLE) ->
|
||||
peekObjectDouble ptr
|
||||
(#const MSGPACK_OBJECT_RAW) ->
|
||||
peekObjectRAW ptr
|
||||
(#const MSGPACK_OBJECT_ARRAY) ->
|
||||
peekObjectArray ptr
|
||||
(#const MSGPACK_OBJECT_MAP) ->
|
||||
peekObjectMap ptr
|
||||
_ ->
|
||||
fail $ "peekObject: unknown object type (" ++ show typ ++ ")"
|
||||
|
||||
peekObjectBool :: Ptr a -> IO Object
|
||||
peekObjectBool ptr = do
|
||||
b <- (#peek msgpack_object, via.boolean) ptr
|
||||
return $ ObjectBool $ (b :: CUChar) /= 0
|
||||
|
||||
peekObjectPositiveInteger :: Ptr a -> IO Object
|
||||
peekObjectPositiveInteger ptr = do
|
||||
n <- (#peek msgpack_object, via.u64) ptr
|
||||
return $ ObjectInteger $ fromIntegral (n :: Word64)
|
||||
|
||||
peekObjectNegativeInteger :: Ptr a -> IO Object
|
||||
peekObjectNegativeInteger ptr = do
|
||||
n <- (#peek msgpack_object, via.i64) ptr
|
||||
return $ ObjectInteger $ fromIntegral (n :: Int64)
|
||||
|
||||
peekObjectDouble :: Ptr a -> IO Object
|
||||
peekObjectDouble ptr = do
|
||||
d <- (#peek msgpack_object, via.dec) ptr
|
||||
return $ ObjectDouble $ realToFrac (d :: CDouble)
|
||||
|
||||
peekObjectRAW :: Ptr a -> IO Object
|
||||
peekObjectRAW ptr = do
|
||||
size <- (#peek msgpack_object, via.raw.size) ptr
|
||||
p <- (#peek msgpack_object, via.raw.ptr) ptr
|
||||
bs <- BS.packCStringLen (p, fromIntegral (size :: Word32))
|
||||
return $ ObjectRAW bs
|
||||
|
||||
peekObjectArray :: Ptr a -> IO Object
|
||||
peekObjectArray ptr = do
|
||||
csize <- (#peek msgpack_object, via.array.size) ptr
|
||||
let size = fromIntegral (csize :: Word32)
|
||||
p <- (#peek msgpack_object, via.array.ptr) ptr
|
||||
objs <- mapM (\i -> peekObject $ p `plusPtr`
|
||||
((#size msgpack_object) * i))
|
||||
[0..size-1]
|
||||
return $ ObjectArray objs
|
||||
|
||||
peekObjectMap :: Ptr a -> IO Object
|
||||
peekObjectMap ptr = do
|
||||
csize <- (#peek msgpack_object, via.map.size) ptr
|
||||
let size = fromIntegral (csize :: Word32)
|
||||
p <- (#peek msgpack_object, via.map.ptr) ptr
|
||||
dat <- mapM (\i -> peekObjectKV $ p `plusPtr`
|
||||
((#size msgpack_object_kv) * i))
|
||||
[0..size-1]
|
||||
return $ ObjectMap dat
|
||||
|
||||
peekObjectKV :: Ptr a -> IO (Object, Object)
|
||||
peekObjectKV ptr = do
|
||||
k <- peekObject $ ptr `plusPtr` (#offset msgpack_object_kv, key)
|
||||
v <- peekObject $ ptr `plusPtr` (#offset msgpack_object_kv, val)
|
||||
return (k, v)
|
||||
|
||||
-- | Pack a Object.
|
||||
packObject :: Packer -> Object -> IO ()
|
||||
packObject pc ObjectNil = packNil pc >> return ()
|
||||
|
||||
packObject pc (ObjectBool b) = packBool pc b >> return ()
|
||||
|
||||
packObject pc (ObjectInteger n) = packInt pc n >> return ()
|
||||
|
||||
packObject pc (ObjectDouble d) = packDouble pc d >> return ()
|
||||
|
||||
packObject pc (ObjectRAW bs) = packRAW' pc bs >> return ()
|
||||
|
||||
packObject pc (ObjectArray ls) = do
|
||||
_ <- packArray pc (length ls)
|
||||
mapM_ (packObject pc) ls
|
||||
|
||||
packObject pc (ObjectMap ls) = do
|
||||
_ <- packMap pc (length ls)
|
||||
mapM_ (\(a, b) -> packObject pc a >> packObject pc b) ls
|
||||
|
||||
data UnpackReturn =
|
||||
UnpackContinue -- ^ not enough bytes to unpack object
|
||||
| UnpackParseError -- ^ got invalid bytes
|
||||
| UnpackError -- ^ other error
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | Unpack a single MessagePack object from byte sequence.
|
||||
unpackObject :: Zone -> ByteString -> IO (Either UnpackReturn (Int, Object))
|
||||
unpackObject z dat =
|
||||
allocaBytes (#size msgpack_object) $ \ptr ->
|
||||
BS.useAsCStringLen dat $ \(str, len) ->
|
||||
alloca $ \poff -> do
|
||||
poke poff 0
|
||||
ret <- msgpack_unpack str (fromIntegral len) poff z ptr
|
||||
case ret of
|
||||
(#const MSGPACK_UNPACK_SUCCESS) -> do
|
||||
off <- peek poff
|
||||
obj <- peekObject ptr
|
||||
return $ Right (fromIntegral off, obj)
|
||||
(#const MSGPACK_UNPACK_EXTRA_BYTES) -> do
|
||||
off <- peek poff
|
||||
obj <- peekObject ptr
|
||||
return $ Right (fromIntegral off, obj)
|
||||
(#const MSGPACK_UNPACK_CONTINUE) ->
|
||||
return $ Left UnpackContinue
|
||||
(#const MSGPACK_UNPACK_PARSE_ERROR) ->
|
||||
return $ Left UnpackParseError
|
||||
_ ->
|
||||
return $ Left UnpackError
|
||||
|
||||
foreign import ccall "msgpack_unpack" msgpack_unpack ::
|
||||
Ptr CChar -> CSize -> Ptr CSize -> Zone -> Ptr () -> IO CInt
|
@@ -1,101 +0,0 @@
|
||||
{-# LANGUAGE TypeSynonymInstances #-}
|
||||
{-# LANGUAGE FlexibleInstances #-}
|
||||
{-# LANGUAGE OverlappingInstances #-}
|
||||
{-# LANGUAGE IncoherentInstances #-}
|
||||
|
||||
--------------------------------------------------------------------
|
||||
-- |
|
||||
-- Module : Data.MessagePack.Class
|
||||
-- Copyright : (c) Hideyuki Tanaka, 2009
|
||||
-- License : BSD3
|
||||
--
|
||||
-- Maintainer: tanaka.hideyuki@gmail.com
|
||||
-- Stability : experimental
|
||||
-- Portability: portable
|
||||
--
|
||||
-- Serializing Haskell values to and from MessagePack Objects.
|
||||
--
|
||||
--------------------------------------------------------------------
|
||||
|
||||
module Data.MessagePack.Class(
|
||||
-- * Serialization to and from Object
|
||||
OBJECT(..),
|
||||
Result,
|
||||
pack,
|
||||
) where
|
||||
|
||||
import Control.Monad.Error
|
||||
import Data.ByteString.Char8 (ByteString)
|
||||
import qualified Data.ByteString.Char8 as C8
|
||||
|
||||
import Data.MessagePack.Base
|
||||
|
||||
-- | The class of types serializable to and from MessagePack object
|
||||
class OBJECT a where
|
||||
toObject :: a -> Object
|
||||
fromObject :: Object -> Result a
|
||||
|
||||
-- | A type for parser results
|
||||
type Result a = Either String a
|
||||
|
||||
instance OBJECT Object where
|
||||
toObject = id
|
||||
fromObject = Right
|
||||
|
||||
fromObjectError :: String
|
||||
fromObjectError = "fromObject: cannot cast"
|
||||
|
||||
instance OBJECT () where
|
||||
toObject = const ObjectNil
|
||||
fromObject ObjectNil = Right ()
|
||||
fromObject _ = Left fromObjectError
|
||||
|
||||
instance OBJECT Int where
|
||||
toObject = ObjectInteger
|
||||
fromObject (ObjectInteger n) = Right n
|
||||
fromObject _ = Left fromObjectError
|
||||
|
||||
instance OBJECT Bool where
|
||||
toObject = ObjectBool
|
||||
fromObject (ObjectBool b) = Right b
|
||||
fromObject _ = Left fromObjectError
|
||||
|
||||
instance OBJECT Double where
|
||||
toObject = ObjectDouble
|
||||
fromObject (ObjectDouble d) = Right d
|
||||
fromObject _ = Left fromObjectError
|
||||
|
||||
instance OBJECT ByteString where
|
||||
toObject = ObjectRAW
|
||||
fromObject (ObjectRAW bs) = Right bs
|
||||
fromObject _ = Left fromObjectError
|
||||
|
||||
instance OBJECT String where
|
||||
toObject = toObject . C8.pack
|
||||
fromObject obj = liftM C8.unpack $ fromObject obj
|
||||
|
||||
instance OBJECT a => OBJECT [a] where
|
||||
toObject = ObjectArray . map toObject
|
||||
fromObject (ObjectArray arr) =
|
||||
mapM fromObject arr
|
||||
fromObject _ =
|
||||
Left fromObjectError
|
||||
|
||||
instance (OBJECT a, OBJECT b) => OBJECT [(a, b)] where
|
||||
toObject =
|
||||
ObjectMap . map (\(a, b) -> (toObject a, toObject b))
|
||||
fromObject (ObjectMap mem) = do
|
||||
mapM (\(a, b) -> liftM2 (,) (fromObject a) (fromObject b)) mem
|
||||
fromObject _ =
|
||||
Left fromObjectError
|
||||
|
||||
instance OBJECT a => OBJECT (Maybe a) where
|
||||
toObject (Just a) = toObject a
|
||||
toObject Nothing = ObjectNil
|
||||
|
||||
fromObject ObjectNil = return Nothing
|
||||
fromObject obj = liftM Just $ fromObject obj
|
||||
|
||||
-- | Pack a serializable Haskell value.
|
||||
pack :: OBJECT a => Packer -> a -> IO ()
|
||||
pack pc = packObject pc . toObject
|
@@ -1,62 +0,0 @@
|
||||
--------------------------------------------------------------------
|
||||
-- |
|
||||
-- Module : Data.MessagePack.Feed
|
||||
-- Copyright : (c) Hideyuki Tanaka, 2009
|
||||
-- License : BSD3
|
||||
--
|
||||
-- Maintainer: tanaka.hideyuki@gmail.com
|
||||
-- Stability : experimental
|
||||
-- Portability: portable
|
||||
--
|
||||
-- Feeders for Stream Deserializers
|
||||
--
|
||||
--------------------------------------------------------------------
|
||||
|
||||
module Data.MessagePack.Feed(
|
||||
-- * Feeder type
|
||||
Feeder,
|
||||
-- * Feeders
|
||||
feederFromHandle,
|
||||
feederFromFile,
|
||||
feederFromString,
|
||||
) where
|
||||
|
||||
import Data.ByteString (ByteString)
|
||||
import qualified Data.ByteString as BS
|
||||
import Data.IORef
|
||||
import System.IO
|
||||
|
||||
-- | Feeder returns Just ByteString when bytes remains, otherwise Nothing.
|
||||
type Feeder = IO (Maybe ByteString)
|
||||
|
||||
-- | Feeder from Handle
|
||||
feederFromHandle :: Handle -> IO Feeder
|
||||
feederFromHandle h = return $ do
|
||||
bs <- BS.hGetNonBlocking h bufSize
|
||||
if BS.length bs > 0
|
||||
then do return $ Just bs
|
||||
else do
|
||||
c <- BS.hGet h 1
|
||||
if BS.length c > 0
|
||||
then do return $ Just c
|
||||
else do
|
||||
hClose h
|
||||
return Nothing
|
||||
where
|
||||
bufSize = 4096
|
||||
|
||||
-- | Feeder from File
|
||||
feederFromFile :: FilePath -> IO Feeder
|
||||
feederFromFile path =
|
||||
openFile path ReadMode >>= feederFromHandle
|
||||
|
||||
-- | Feeder from ByteString
|
||||
feederFromString :: ByteString -> IO Feeder
|
||||
feederFromString bs = do
|
||||
r <- newIORef (Just bs)
|
||||
return $ f r
|
||||
where
|
||||
f r = do
|
||||
mb <- readIORef r
|
||||
writeIORef r Nothing
|
||||
return mb
|
@@ -1,156 +0,0 @@
|
||||
--------------------------------------------------------------------
|
||||
-- |
|
||||
-- Module : Data.MessagePack.Monad
|
||||
-- Copyright : (c) Hideyuki Tanaka, 2009
|
||||
-- License : BSD3
|
||||
--
|
||||
-- Maintainer: tanaka.hideyuki@gmail.com
|
||||
-- Stability : experimental
|
||||
-- Portability: portable
|
||||
--
|
||||
-- Monadic Stream Serializers and Deserializers
|
||||
--
|
||||
--------------------------------------------------------------------
|
||||
|
||||
module Data.MessagePack.Monad(
|
||||
-- * Classes
|
||||
MonadPacker(..),
|
||||
MonadUnpacker(..),
|
||||
|
||||
-- * Packer and Unpacker type
|
||||
PackerT(..),
|
||||
UnpackerT(..),
|
||||
|
||||
-- * Packers
|
||||
packToString,
|
||||
packToHandle,
|
||||
packToFile,
|
||||
|
||||
-- * Unpackers
|
||||
unpackFrom,
|
||||
unpackFromString,
|
||||
unpackFromHandle,
|
||||
unpackFromFile,
|
||||
) where
|
||||
|
||||
import Control.Monad
|
||||
import Control.Monad.Trans
|
||||
import Data.ByteString (ByteString)
|
||||
import qualified Data.ByteString as BS
|
||||
import System.IO
|
||||
|
||||
import Data.MessagePack.Base hiding (Unpacker)
|
||||
import qualified Data.MessagePack.Base as Base
|
||||
import Data.MessagePack.Class
|
||||
import Data.MessagePack.Feed
|
||||
|
||||
class Monad m => MonadPacker m where
|
||||
-- | Serialize a object
|
||||
put :: OBJECT a => a -> m ()
|
||||
|
||||
class Monad m => MonadUnpacker m where
|
||||
-- | Deserialize a object
|
||||
get :: OBJECT a => m a
|
||||
|
||||
-- | Serializer Type
|
||||
newtype PackerT m r = PackerT { runPackerT :: Base.Packer -> m r }
|
||||
|
||||
instance Monad m => Monad (PackerT m) where
|
||||
a >>= b =
|
||||
PackerT $ \pc -> do
|
||||
r <- runPackerT a pc
|
||||
runPackerT (b r) pc
|
||||
|
||||
return r =
|
||||
PackerT $ \_ -> return r
|
||||
|
||||
instance MonadTrans PackerT where
|
||||
lift m = PackerT $ \_ -> m
|
||||
|
||||
instance MonadIO m => MonadIO (PackerT m) where
|
||||
liftIO = lift . liftIO
|
||||
|
||||
instance MonadIO m => MonadPacker (PackerT m) where
|
||||
put v = PackerT $ \pc -> liftIO $ do
|
||||
pack pc v
|
||||
|
||||
-- | Execute given serializer and returns byte sequence.
|
||||
packToString :: MonadIO m => PackerT m r -> m ByteString
|
||||
packToString m = do
|
||||
sb <- liftIO $ newSimpleBuffer
|
||||
pc <- liftIO $ newPacker sb
|
||||
_ <- runPackerT m pc
|
||||
liftIO $ simpleBufferData sb
|
||||
|
||||
-- | Execute given serializer and write byte sequence to Handle.
|
||||
packToHandle :: MonadIO m => Handle -> PackerT m r -> m ()
|
||||
packToHandle h m = do
|
||||
sb <- packToString m
|
||||
liftIO $ BS.hPut h sb
|
||||
liftIO $ hFlush h
|
||||
|
||||
-- | Execute given serializer and write byte sequence to file.
|
||||
packToFile :: MonadIO m => FilePath -> PackerT m r -> m ()
|
||||
packToFile p m = do
|
||||
sb <- packToString m
|
||||
liftIO $ BS.writeFile p sb
|
||||
|
||||
-- | Deserializer type
|
||||
newtype UnpackerT m r = UnpackerT { runUnpackerT :: Base.Unpacker -> Feeder -> m r }
|
||||
|
||||
instance Monad m => Monad (UnpackerT m) where
|
||||
a >>= b =
|
||||
UnpackerT $ \up feed -> do
|
||||
r <- runUnpackerT a up feed
|
||||
runUnpackerT (b r) up feed
|
||||
|
||||
return r =
|
||||
UnpackerT $ \_ _ -> return r
|
||||
|
||||
instance MonadTrans UnpackerT where
|
||||
lift m = UnpackerT $ \_ _ -> m
|
||||
|
||||
instance MonadIO m => MonadIO (UnpackerT m) where
|
||||
liftIO = lift . liftIO
|
||||
|
||||
instance MonadIO m => MonadUnpacker (UnpackerT m) where
|
||||
get = UnpackerT $ \up feed -> liftIO $ do
|
||||
executeOne up feed
|
||||
obj <- unpackerData up
|
||||
freeZone =<< unpackerReleaseZone up
|
||||
unpackerReset up
|
||||
let Right r = fromObject obj
|
||||
return r
|
||||
|
||||
where
|
||||
executeOne up feed = do
|
||||
resp <- unpackerExecute up
|
||||
guard $ resp>=0
|
||||
when (resp==0) $ do
|
||||
Just bs <- feed
|
||||
unpackerFeed up bs
|
||||
executeOne up feed
|
||||
|
||||
-- | Execute deserializer using given feeder.
|
||||
unpackFrom :: MonadIO m => Feeder -> UnpackerT m r -> m r
|
||||
unpackFrom f m = do
|
||||
up <- liftIO $ newUnpacker defaultInitialBufferSize
|
||||
runUnpackerT m up f
|
||||
|
||||
-- | Execute deserializer using given handle.
|
||||
unpackFromHandle :: MonadIO m => Handle -> UnpackerT m r -> m r
|
||||
unpackFromHandle h m =
|
||||
flip unpackFrom m =<< liftIO (feederFromHandle h)
|
||||
|
||||
-- | Execute deserializer using given file content.
|
||||
unpackFromFile :: MonadIO m => FilePath -> UnpackerT m r -> m r
|
||||
unpackFromFile p m = do
|
||||
h <- liftIO $ openFile p ReadMode
|
||||
r <- flip unpackFrom m =<< liftIO (feederFromHandle h)
|
||||
liftIO $ hClose h
|
||||
return r
|
||||
|
||||
-- | Execute deserializer from given byte sequence.
|
||||
unpackFromString :: MonadIO m => ByteString -> UnpackerT m r -> m r
|
||||
unpackFromString bs m = do
|
||||
flip unpackFrom m =<< liftIO (feederFromString bs)
|
@@ -1,82 +0,0 @@
|
||||
--------------------------------------------------------------------
|
||||
-- |
|
||||
-- Module : Data.MessagePack.Stream
|
||||
-- Copyright : (c) Hideyuki Tanaka, 2009
|
||||
-- License : BSD3
|
||||
--
|
||||
-- Maintainer: tanaka.hideyuki@gmail.com
|
||||
-- Stability : experimental
|
||||
-- Portability: portable
|
||||
--
|
||||
-- Lazy Stream Serializers and Deserializers
|
||||
--
|
||||
--------------------------------------------------------------------
|
||||
|
||||
module Data.MessagePack.Stream(
|
||||
unpackObjects,
|
||||
unpackObjectsFromFile,
|
||||
unpackObjectsFromHandle,
|
||||
unpackObjectsFromString,
|
||||
) where
|
||||
|
||||
import Data.ByteString (ByteString)
|
||||
import System.IO
|
||||
import System.IO.Unsafe
|
||||
|
||||
import Data.MessagePack.Base
|
||||
import Data.MessagePack.Feed
|
||||
|
||||
-- | Unpack objects using given feeder.
|
||||
unpackObjects :: Feeder -> IO [Object]
|
||||
unpackObjects feeder = do
|
||||
up <- newUnpacker defaultInitialBufferSize
|
||||
f up
|
||||
where
|
||||
f up = unsafeInterleaveIO $ do
|
||||
mbo <- unpackOnce up
|
||||
case mbo of
|
||||
Just o -> do
|
||||
os <- f up
|
||||
return $ o:os
|
||||
Nothing ->
|
||||
return []
|
||||
|
||||
unpackOnce up = do
|
||||
resp <- unpackerExecute up
|
||||
case resp of
|
||||
0 -> do
|
||||
r <- feedOnce up
|
||||
if r
|
||||
then unpackOnce up
|
||||
else return Nothing
|
||||
1 -> do
|
||||
obj <- unpackerData up
|
||||
freeZone =<< unpackerReleaseZone up
|
||||
unpackerReset up
|
||||
return $ Just obj
|
||||
_ ->
|
||||
error $ "unpackerExecute fails: " ++ show resp
|
||||
|
||||
feedOnce up = do
|
||||
dat <- feeder
|
||||
case dat of
|
||||
Nothing ->
|
||||
return False
|
||||
Just bs -> do
|
||||
unpackerFeed up bs
|
||||
return True
|
||||
|
||||
-- | Unpack objects from file.
|
||||
unpackObjectsFromFile :: FilePath -> IO [Object]
|
||||
unpackObjectsFromFile fname =
|
||||
unpackObjects =<< feederFromFile fname
|
||||
|
||||
-- | Unpack objects from handle.
|
||||
unpackObjectsFromHandle :: Handle -> IO [Object]
|
||||
unpackObjectsFromHandle h =
|
||||
unpackObjects =<< feederFromHandle h
|
||||
|
||||
-- | Unpack oobjects from given byte sequence.
|
||||
unpackObjectsFromString :: ByteString -> IO [Object]
|
||||
unpackObjectsFromString bs =
|
||||
unpackObjects =<< feederFromString bs
|
@@ -1,16 +0,0 @@
|
||||
import Control.Monad.Trans
|
||||
import Data.MessagePack
|
||||
|
||||
main = do
|
||||
sb <- packToString $ do
|
||||
put [1,2,3::Int]
|
||||
put (3.14 :: Double)
|
||||
put "Hoge"
|
||||
|
||||
print sb
|
||||
|
||||
unpackFromString sb $ do
|
||||
arr <- get
|
||||
dbl <- get
|
||||
str <- get
|
||||
liftIO $ print (arr :: [Int], dbl :: Double, str :: String)
|
@@ -1,14 +0,0 @@
|
||||
import Control.Applicative
|
||||
import qualified Data.ByteString as BS
|
||||
import Data.MessagePack
|
||||
|
||||
main = do
|
||||
sb <- newSimpleBuffer
|
||||
pc <- newPacker sb
|
||||
pack pc [1,2,3::Int]
|
||||
pack pc True
|
||||
pack pc "hoge"
|
||||
bs <- simpleBufferData sb
|
||||
|
||||
os <- unpackObjectsFromString bs
|
||||
mapM_ print os
|
@@ -1,36 +0,0 @@
|
||||
import Control.Monad
|
||||
import Data.MessagePack
|
||||
|
||||
{-
|
||||
main = do
|
||||
sb <- newSimpleBuffer
|
||||
pc <- newPacker sb
|
||||
|
||||
pack pc [(1,2),(2,3),(3::Int,4::Int)]
|
||||
pack pc [4,5,6::Int]
|
||||
pack pc "hoge"
|
||||
|
||||
bs <- simpleBufferData sb
|
||||
print bs
|
||||
|
||||
up <- newUnpacker defaultInitialBufferSize
|
||||
|
||||
unpackerFeed up bs
|
||||
|
||||
let f = do
|
||||
res <- unpackerExecute up
|
||||
when (res==1) $ do
|
||||
obj <- unpackerData up
|
||||
print obj
|
||||
f
|
||||
|
||||
f
|
||||
|
||||
return ()
|
||||
-}
|
||||
|
||||
main = do
|
||||
bs <- packb [(1,2),(2,3),(3::Int,4::Int)]
|
||||
print bs
|
||||
dat <- unpackb bs
|
||||
print (dat :: Result [(Int, Int)])
|
4
java/.gitignore
vendored
4
java/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
target
|
||||
.project
|
||||
.classpath
|
||||
*~
|
@@ -1,5 +0,0 @@
|
||||
#Mon Apr 19 22:18:48 JST 2010
|
||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
|
||||
eclipse.preferences.version=1
|
||||
org.eclipse.jdt.core.compiler.source=1.6
|
||||
org.eclipse.jdt.core.compiler.compliance=1.6
|
@@ -1,9 +0,0 @@
|
||||
Release 0.3 - 2010/05/23
|
||||
NEW FEATURES
|
||||
Added Unbuffered API + Direct Conversion API to the Unpacker.
|
||||
|
||||
BUG FIXES
|
||||
Zero-length Array and Map is deserialized as List and Map, instead of the
|
||||
array of the Object.
|
||||
|
||||
fixed the bug around Packer.packByte().
|
202
java/LICENSE.txt
202
java/LICENSE.txt
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
@@ -1,24 +0,0 @@
|
||||
|
||||
.PHONY: compile test eclipse clean package
|
||||
|
||||
all:
|
||||
compile
|
||||
|
||||
package:
|
||||
mvn package
|
||||
|
||||
install:
|
||||
mvn install
|
||||
|
||||
compile:
|
||||
mvn compile
|
||||
|
||||
test:
|
||||
mvn test
|
||||
|
||||
# generate .project and .classpath file for Eclipse
|
||||
eclipse:
|
||||
mvn eclipse:eclipse
|
||||
|
||||
clean:
|
||||
mvn clean
|
28
java/README
28
java/README
@@ -1,28 +0,0 @@
|
||||
|
||||
To build the JAR file of Message Pack, you need to install Maven (http://maven.apache.org), then type the following command:
|
||||
|
||||
$ mvn package
|
||||
|
||||
To locally install the project, type
|
||||
$ mvn install
|
||||
|
||||
To generate project files (.project, .classpath) for Eclipse, do
|
||||
|
||||
$ mvn eclipse:eclipse
|
||||
|
||||
then import the folder from your Eclipse.
|
||||
|
||||
Next, open the preference page in Eclipse and add the CLASSPATH variable:
|
||||
|
||||
M2_REPO = $HOME/.m2/repository
|
||||
|
||||
where $HOME is your home directory. In Windows XP, $HOME is:
|
||||
C:/Documents and Settings/(user name)/.m2/repository
|
||||
|
||||
|
||||
# How to release the project (compile, test, tagging, deploy)
|
||||
|
||||
$ mvn release:prepare
|
||||
$ mvn release:perform
|
||||
|
||||
|
303
java/build.xml
303
java/build.xml
@@ -1,303 +0,0 @@
|
||||
<project name="MessagePack for Java" default="jar"
|
||||
xmlns:ivy="antlib:org.apache.ivy.ant"
|
||||
xmlns:mvn="urn:maven-artifact-ant">
|
||||
|
||||
<property name="Name" value="MessagePack"/>
|
||||
<property name="name" value="msgpack"/>
|
||||
<property name="version" value="0.0.1"/>
|
||||
<property name="fullname" value="${name}-${version}"/>
|
||||
<property name="year" value="2010"/>
|
||||
|
||||
<!-- Load user's default properties. -->
|
||||
<property file="${user.home}/build.properties" />
|
||||
|
||||
<property name="src.dir" value="${basedir}/src/main/java"/>
|
||||
<property name="java.src.dir" value="${src.dir}/"/>
|
||||
<property name="build.dir" value="${basedir}/build"/>
|
||||
<property name="lib.dir" value="${basedir}/lib"/>
|
||||
<property name="dist.dir" value="${basedir}/dist"/>
|
||||
|
||||
<property name="build.classes" value="${build.dir}/classes"/>
|
||||
<property name="build.doc" value="${build.dir}/doc"/>
|
||||
<property name="build.javadoc" value="${build.doc}/api/"/>
|
||||
<property name="build.javadoc.log" value="${build.dir}/javadoc.log"/>
|
||||
|
||||
<property name="test.count" value="100"/>
|
||||
<property name="test.junit.output.format" value="plain"/>
|
||||
<property name="test.java.src.dir" value="${basedir}/src/test/java"/>
|
||||
<property name="test.java.build.dir" value="${build.dir}/test"/>
|
||||
<property name="test.java.classes" value="${test.java.build.dir}/classes"/>
|
||||
<property name="test.java.include" value="Test*"/>
|
||||
|
||||
<property name="javac.encoding" value="ISO-8859-1"/>
|
||||
<property name="javac.debug" value="on"/>
|
||||
<property name="javac.optimize" value="on"/>
|
||||
<property name="javac.deprecation" value="off"/>
|
||||
<property name="javac.version" value="1.6"/>
|
||||
<property name="javac.args" value=""/>
|
||||
<property name="javac.args.warnings" value="-Xlint:unchecked"/>
|
||||
|
||||
<property name="javadoc.link.java"
|
||||
value="http://java.sun.com/javase/6/docs/api/"/>
|
||||
<property name="javadoc.packages" value="org.${name}.*"/>
|
||||
|
||||
<!-- ivy settings -->
|
||||
<property name="ivy.version" value="2.1.0"/>
|
||||
<property name="ivy.url"
|
||||
value="http://repo2.maven.org/maven2/org/apache/ivy/ivy" />
|
||||
<property name="ivy.home" value="${user.home}/.ant" />
|
||||
<property name="ivy.lib" value="${build.dir}/lib"/>
|
||||
<property name="ivy.test.lib" value="${build.dir}/test/lib"/>
|
||||
<property name="mvn.repo"
|
||||
value="https://repository.apache.org/content/repositories/snapshots"/>
|
||||
|
||||
<!-- the normal classpath -->
|
||||
<path id="libs">
|
||||
<fileset dir="${ivy.lib}">
|
||||
<include name="**/*.jar" />
|
||||
</fileset>
|
||||
</path>
|
||||
<path id="java.classpath">
|
||||
<pathelement location="${build.classes}"/>
|
||||
<fileset dir="${lib.dir}">
|
||||
<include name="**/*.jar" />
|
||||
<exclude name="**/excluded/" />
|
||||
</fileset>
|
||||
<fileset dir="${ant.home}/lib">
|
||||
<include name="ant.jar" />
|
||||
</fileset>
|
||||
<path refid="libs" />
|
||||
</path>
|
||||
<path id="test.libs">
|
||||
<fileset dir="${ivy.test.lib}">
|
||||
<include name="**/*.jar" />
|
||||
</fileset>
|
||||
</path>
|
||||
<path id="test.java.classpath">
|
||||
<pathelement location="${test.java.classes}" />
|
||||
<path refid="java.classpath"/>
|
||||
<path refid="test.libs"/>
|
||||
</path>
|
||||
|
||||
<!-- init & clean -->
|
||||
<target name="init">
|
||||
<mkdir dir="${build.dir}" />
|
||||
<mkdir dir="${lib.dir}" />
|
||||
<mkdir dir="${build.classes}" />
|
||||
|
||||
<mkdir dir="${test.java.build.dir}"/>
|
||||
<mkdir dir="${test.java.classes}"/>
|
||||
|
||||
<mkdir dir="${ivy.lib}"/>
|
||||
<mkdir dir="${ivy.test.lib}"/>
|
||||
<condition property="ivy.jar.exists">
|
||||
<available file="${lib.dir}/ivy-${ivy.version}.jar"/>
|
||||
</condition>
|
||||
</target>
|
||||
<target name="clean">
|
||||
<delete dir="${build.dir}" />
|
||||
</target>
|
||||
|
||||
<!-- ivy targets -->
|
||||
<target name="ivy-download" unless="ivy.jar.exists" depends="init">
|
||||
<delete dir="${lib.dir}"
|
||||
includes="ivy-*.jar" excludes="ivy-${ivy.version}.jar"/>
|
||||
<get src="${ivy.url}/${ivy.version}/ivy-${ivy.version}.jar"
|
||||
dest="${lib.dir}/ivy-${ivy.version}.jar" usetimestamp="true"/>
|
||||
</target>
|
||||
<target name="ivy-init" depends="ivy-download" unless="ivy.initialized">
|
||||
<taskdef resource="org/apache/ivy/ant/antlib.xml"
|
||||
uri="antlib:org.apache.ivy.ant" classpathref="java.classpath"/>
|
||||
<!-- ensure that ivy taskdef is only run once, otw ant will error -->
|
||||
<property name="ivy.initialized" value="true"/>
|
||||
</target>
|
||||
|
||||
<target name="ivy-retrieve-build" depends="init,ivy-init">
|
||||
<ivy:retrieve type="jar" conf="build"
|
||||
pattern="${ivy.lib}/[artifact]-[revision].[ext]"/>
|
||||
</target>
|
||||
<target name="ivy-retrieve-test" depends="init,ivy-init">
|
||||
<ivy:retrieve type="jar" conf="test"
|
||||
pattern="${ivy.test.lib}/[artifact]-[revision].[ext]"/>
|
||||
</target>
|
||||
|
||||
<!-- compiler -->
|
||||
<macrodef name="java-compiler">
|
||||
<attribute name="dest" default="${build.classes}"/>
|
||||
<attribute name="includes" default="**/*.java"/>
|
||||
<attribute name="excludes" default=""/>
|
||||
<attribute name="classpath" default="java.classpath"/>
|
||||
<element name="src" implicit="yes"/>
|
||||
<sequential>
|
||||
<javac
|
||||
destdir="@{dest}"
|
||||
includes="@{includes}"
|
||||
excludes="@{excludes}"
|
||||
encoding="${javac.encoding}"
|
||||
debug="${javac.debug}"
|
||||
optimize="${javac.optimize}"
|
||||
target="${javac.version}"
|
||||
source="${javac.version}"
|
||||
deprecation="${javac.deprecation}">
|
||||
<compilerarg line="${javac.args} ${javac.args.warnings}" />
|
||||
<classpath refid="@{classpath}"/>
|
||||
<src />
|
||||
</javac>
|
||||
</sequential>
|
||||
</macrodef>
|
||||
|
||||
<!-- compile -->
|
||||
<target name="compile" depends="init,ivy-retrieve-build">
|
||||
<java-compiler>
|
||||
<src path="${java.src.dir}"/>
|
||||
</java-compiler>
|
||||
</target>
|
||||
|
||||
<!-- test -->
|
||||
<macrodef name="test-runner">
|
||||
<attribute name="files.location" />
|
||||
<attribute name="tests.pattern" />
|
||||
<attribute name="test.dir" default="${test.java.build.dir}" />
|
||||
<sequential>
|
||||
<junit showoutput="yes"
|
||||
printsummary="withOutAndErr"
|
||||
haltonfailure="no"
|
||||
fork="yes" forkMode="once"
|
||||
errorProperty="tests.failed" failureProperty="tests.failed">
|
||||
<sysproperty key="test.count" value="${test.count}"/>
|
||||
<sysproperty key="test.dir" value="@{test.dir}"/>
|
||||
<classpath refid="test.java.classpath"/>
|
||||
<formatter type="${test.junit.output.format}"/>
|
||||
<batchtest todir="${test.java.build.dir}" unless="testcase">
|
||||
<fileset dir="@{files.location}"
|
||||
includes="@{tests.pattern}"
|
||||
excludes="**/${test.java.exclude}.java" />
|
||||
</batchtest>
|
||||
<batchtest todir="${test.java.build.dir}" if="testcase">
|
||||
<fileset dir="@{files.location}" includes="**/${testcase}.java"/>
|
||||
</batchtest>
|
||||
</junit>
|
||||
<fail if="tests.failed">Tests Failed!</fail>
|
||||
</sequential>
|
||||
</macrodef>
|
||||
<target name="compile-test" depends="ivy-retrieve-test,compile">
|
||||
<java-compiler dest="${test.java.classes}"
|
||||
classpath="test.java.classpath">
|
||||
<src path="${test.java.src.dir}/org" />
|
||||
</java-compiler>
|
||||
</target>
|
||||
<target name="test" depends="init,compile-test">
|
||||
<test-runner files.location="${test.java.src.dir}"
|
||||
tests.pattern="**/${test.java.include}.java"/>
|
||||
</target>
|
||||
|
||||
<!-- jar -->
|
||||
<target name="jar" depends="compile">
|
||||
<jar jarfile="${build.dir}/${name}-${version}.jar" basedir="${build.classes}" >
|
||||
<manifest>
|
||||
<section name="org/${name}">
|
||||
<attribute name="Implementation-Title" value="${Name}"/>
|
||||
<attribute name="Implementation-Version" value="${version}"/>
|
||||
</section>
|
||||
</manifest>
|
||||
</jar>
|
||||
</target>
|
||||
|
||||
<!-- javadoc -->
|
||||
<target name="javadoc" depends="compile" description="Generate javadoc">
|
||||
<mkdir dir="${build.javadoc}"/>
|
||||
<record name="${build.javadoc.log}" action="start"/>
|
||||
<javadoc
|
||||
Locale="en_US"
|
||||
packagenames="org.${org}.${name}.*"
|
||||
destdir="${build.javadoc}"
|
||||
encoding="UTF-8"
|
||||
docencoding="UTF-8"
|
||||
author="true"
|
||||
version="true"
|
||||
use="true"
|
||||
windowtitle="${Name} ${version} API"
|
||||
doctitle="${Name} ${version} API"
|
||||
bottom="Copyright &copy; ${year} The ${Name} Project"
|
||||
>
|
||||
<packageset dir="${java.src.dir}"/>
|
||||
<link href="${javadoc.link.java}"/>
|
||||
<classpath >
|
||||
<path refid="java.classpath" />
|
||||
</classpath>
|
||||
</javadoc>
|
||||
<record name="${build.javadoc.log}" action="stop"/>
|
||||
<condition property="javadoc.warnings">
|
||||
<isfileselected file="${build.javadoc.log}">
|
||||
<contains text=": warning - "/>
|
||||
</isfileselected>
|
||||
</condition>
|
||||
<fail if="javadoc.warnings">Javadoc warnings!</fail>
|
||||
</target>
|
||||
<target name="javadoc-jar" depends="javadoc">
|
||||
<jar jarfile="${build.dir}/${fullname}-javadoc.jar">
|
||||
<fileset dir="${build.javadoc}" includes="**/*"/>
|
||||
</jar>
|
||||
</target>
|
||||
|
||||
<!-- sources -->
|
||||
<target name="source">
|
||||
<jar jarfile="${build.dir}/${fullname}-sources.jar">
|
||||
<fileset dir="${java.src.dir}" includes="**/*.java"/>
|
||||
</jar>
|
||||
</target>
|
||||
|
||||
<!-- pom -->
|
||||
<target name="pom" depends="ivy-init">
|
||||
<ivy:makepom ivyfile="${basedir}/ivy.xml"
|
||||
pomfile="${dist.dir}/${fullname}.pom">
|
||||
<mapping conf="default" scope="compile"/>
|
||||
<mapping conf="test" scope="test"/>
|
||||
</ivy:makepom>
|
||||
</target>
|
||||
|
||||
<!-- dist -->
|
||||
<target name="dist" depends="jar, pom, source, javadoc-jar"
|
||||
description="Build distribution">
|
||||
<mkdir dir="${dist.dir}"/>
|
||||
<copy todir="${dist.dir}">
|
||||
<fileset file="${build.dir}/${fullname}.jar"/>
|
||||
<fileset file="${build.dir}/${fullname}-sources.jar"/>
|
||||
<fileset file="${build.dir}/${fullname}-javadoc.jar"/>
|
||||
</copy>
|
||||
</target>
|
||||
|
||||
<!-- maven: install msgpack into local m2 cache -->
|
||||
<target name="mvn-install" depends="jar, pom, source, javadoc-jar"
|
||||
description="Installs msgpack to local m2 cache">
|
||||
<typedef resource="org/apache/maven/artifact/ant/antlib.xml"
|
||||
uri="urn:maven-artifact-ant"
|
||||
classpathref="java.classpath"/>
|
||||
<mvn:pom file="${dist.dir}/${fullname}.pom" id="msgpack"/>
|
||||
<mvn:install file="${build.dir}/${fullname}.jar">
|
||||
<attach file="${build.dir}/${fullname}-sources.jar"
|
||||
classifier="sources" />
|
||||
<attach file="${build.dir}/${fullname}-javadoc.jar"
|
||||
classifier="javadoc" />
|
||||
<pom refid="msgpack"/>
|
||||
</mvn:install>
|
||||
</target>
|
||||
|
||||
<!-- maven: create local repository into ${basedir}/maven2 -->
|
||||
<target name="mvn-deploy" depends="jar, pom, source, javadoc-jar"
|
||||
description="Deploys MessagePack to Maven repo.">
|
||||
<typedef resource="org/apache/maven/artifact/ant/antlib.xml"
|
||||
uri="urn:maven-artifact-ant"
|
||||
classpathref="java.classpath"/>
|
||||
<mvn:pom file="${dist.dir}/${fullname}.pom" id="msgpack"/>
|
||||
<mvn:deploy file="${build.dir}/${fullname}.jar">
|
||||
<remoteRepository url="file://localhost/${basedir}/maven2/"/>
|
||||
<attach file="${build.dir}/${fullname}-sources.jar"
|
||||
classifier="sources" />
|
||||
<attach file="${build.dir}/${fullname}-javadoc.jar"
|
||||
classifier="javadoc" />
|
||||
<pom refid="msgpack"/>
|
||||
</mvn:deploy>
|
||||
</target>
|
||||
|
||||
</project>
|
19
java/ivy.xml
19
java/ivy.xml
@@ -1,19 +0,0 @@
|
||||
<ivy-module version="2.0"
|
||||
xmlns:e="http://ant.apache.org/ivy/extra">
|
||||
|
||||
<info organisation="org"
|
||||
module="${name}" revision="${version}">
|
||||
<ivyauthor name="MessagePack Project" url="http://msgpack.sourceforge.net/"/>
|
||||
<description>MessagePack</description>
|
||||
</info>
|
||||
|
||||
<configurations defaultconfmapping="default">
|
||||
<conf name="default"/> <!-- "runtime" configuration -->
|
||||
<conf name="test"/>
|
||||
<conf name="build" extends="default"/>
|
||||
</configurations>
|
||||
|
||||
<dependencies>
|
||||
<dependency org="junit" name="junit" rev="4.8.1" conf="test->default"/>
|
||||
</dependencies>
|
||||
</ivy-module>
|
144
java/pom.xml
144
java/pom.xml
@@ -1,144 +0,0 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.msgpack</groupId>
|
||||
<artifactId>msgpack</artifactId>
|
||||
<version>0.3</version>
|
||||
<description>MessagePack for Java</description>
|
||||
|
||||
<name>MessagePack for Java</name>
|
||||
<url>http://msgpack.sourceforge.net/</url>
|
||||
|
||||
<licenses>
|
||||
<license>
|
||||
<name>The Apache Software License, Version 2.0</name>
|
||||
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
</license>
|
||||
</licenses>
|
||||
|
||||
<scm>
|
||||
<connection>scm:git:git://github.com/msgpack/msgpack.git</connection>
|
||||
<url>scm:git:git://github.com/msgpack/msgpack.git</url>
|
||||
</scm>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
</resources>
|
||||
<testResources>
|
||||
<testResource>
|
||||
<directory>src/test/resources</directory>
|
||||
</testResource>
|
||||
</testResources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.6</source>
|
||||
<target>1.6</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-eclipse-plugin</artifactId>
|
||||
<version>2.5.1</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-release-plugin</artifactId>
|
||||
<configuration>
|
||||
<!-- do not run site-deploy goal, which is included in the default setting -->
|
||||
<goals>deploy</goals>
|
||||
<connectionUrl>scm:git://github.com/msgpack/msgpack.git</connectionUrl>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<reporting>
|
||||
<plugins>
|
||||
<!-- Generating JavaDoc -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-javadoc-plugin</artifactId>
|
||||
<configuration>
|
||||
<doctitle>${project.name} ${project.version} API</doctitle>
|
||||
<aggregate>true</aggregate>
|
||||
<locale>en_US</locale>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jxr-plugin</artifactId>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-report-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>msgpack.sourceforge.net</id>
|
||||
<name>MessagePack Maven2 Repository</name>
|
||||
<url>http://msgpack.sourceforge.net/maven2</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>msgpack.sourceforge.net</id>
|
||||
<name>MessagePack Maven2 Snapshot Repository</name>
|
||||
<url>http://msgpack.sourceforge.net/maven2-snapshot</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<distributionManagement>
|
||||
<repository>
|
||||
<uniqueVersion>false</uniqueVersion>
|
||||
<id>shell.sourceforge.net</id>
|
||||
<name>Repository at sourceforge.net</name>
|
||||
<url>scp://shell.sourceforge.net/home/groups/m/ms/msgpack/htdocs/maven2/</url>
|
||||
</repository>
|
||||
<snapshotRepository>
|
||||
<uniqueVersion>true</uniqueVersion>
|
||||
<id>shell.sourceforge.net</id>
|
||||
<name>Repository Name</name>
|
||||
<url>scp://shell.sourceforge.net/home/groups/m/ms/msgpack/htdocs/maven2-snapshot/</url>
|
||||
</snapshotRepository>
|
||||
</distributionManagement>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>release</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<inherited>true</inherited>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>2.4</version>
|
||||
<configuration>
|
||||
<updateReleaseInfo>true</updateReleaseInfo>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
@@ -1,426 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
//import java.math.BigInteger;
|
||||
|
||||
abstract class BufferedUnpackerImpl extends UnpackerImpl {
|
||||
int offset = 0;
|
||||
int filled = 0;
|
||||
byte[] buffer = null;
|
||||
private ByteBuffer castBuffer = ByteBuffer.allocate(8);
|
||||
|
||||
abstract boolean fill() throws IOException;
|
||||
|
||||
final boolean next(UnpackResult result) throws IOException, UnpackException {
|
||||
if(filled == 0) {
|
||||
if(!fill()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
int noffset = super.execute(buffer, offset, filled);
|
||||
if(noffset <= offset) {
|
||||
if(!fill()) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
offset = noffset;
|
||||
} while(!super.isFinished());
|
||||
|
||||
Object obj = super.getData();
|
||||
super.reset();
|
||||
result.done(obj);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private final void more(int require) throws IOException, UnpackException {
|
||||
while(filled - offset < require) {
|
||||
if(!fill()) {
|
||||
// FIXME
|
||||
throw new UnpackException("insufficient buffer");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final boolean tryMore(int require) throws IOException, UnpackException {
|
||||
while(filled - offset < require) {
|
||||
if(!fill()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private final void advance(int length) {
|
||||
offset += length;
|
||||
}
|
||||
|
||||
final byte unpackByte() throws IOException, MessageTypeException {
|
||||
int o = unpackInt();
|
||||
if(0x7f < o || o < -0x80) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (byte)o;
|
||||
}
|
||||
|
||||
final short unpackShort() throws IOException, MessageTypeException {
|
||||
int o = unpackInt();
|
||||
if(0x7fff < o || o < -0x8000) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (short)o;
|
||||
}
|
||||
|
||||
final int unpackInt() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset];
|
||||
if((b & 0x80) == 0 || (b & 0xe0) == 0xe0) { // Fixnum
|
||||
advance(1);
|
||||
return (int)b;
|
||||
}
|
||||
switch(b & 0xff) {
|
||||
case 0xcc: // unsigned int 8
|
||||
more(2);
|
||||
advance(2);
|
||||
return (int)((short)buffer[offset+1] & 0xff);
|
||||
case 0xcd: // unsigned int 16
|
||||
more(3);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 2);
|
||||
advance(3);
|
||||
return (int)((int)castBuffer.getShort(0) & 0xffff);
|
||||
case 0xce: // unsigned int 32
|
||||
more(5);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
{
|
||||
int o = castBuffer.getInt(0);
|
||||
if(o < 0) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
advance(5);
|
||||
return o;
|
||||
}
|
||||
case 0xcf: // unsigned int 64
|
||||
more(9);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 8);
|
||||
{
|
||||
long o = castBuffer.getLong(0);
|
||||
if(o < 0 || o > 0x7fffffffL) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
advance(9);
|
||||
return (int)o;
|
||||
}
|
||||
case 0xd0: // signed int 8
|
||||
more(2);
|
||||
advance(2);
|
||||
return (int)buffer[offset+1];
|
||||
case 0xd1: // signed int 16
|
||||
more(3);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 2);
|
||||
advance(3);
|
||||
return (int)castBuffer.getShort(0);
|
||||
case 0xd2: // signed int 32
|
||||
more(4);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
advance(4);
|
||||
return (int)castBuffer.getInt(0);
|
||||
case 0xd3: // signed int 64
|
||||
more(9);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 8);
|
||||
{
|
||||
long o = castBuffer.getLong(0);
|
||||
if(0x7fffffffL < o || o < -0x80000000L) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
advance(9);
|
||||
return (int)o;
|
||||
}
|
||||
default:
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
final long unpackLong() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset];
|
||||
if((b & 0x80) == 0 || (b & 0xe0) == 0xe0) { // Fixnum
|
||||
advance(1);
|
||||
return (long)b;
|
||||
}
|
||||
switch(b & 0xff) {
|
||||
case 0xcc: // unsigned int 8
|
||||
more(2);
|
||||
advance(2);
|
||||
return (long)((short)buffer[offset+1] & 0xff);
|
||||
case 0xcd: // unsigned int 16
|
||||
more(3);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 2);
|
||||
advance(3);
|
||||
return (long)((int)castBuffer.getShort(0) & 0xffff);
|
||||
case 0xce: // unsigned int 32
|
||||
more(5);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
advance(5);
|
||||
return ((long)castBuffer.getInt(0) & 0xffffffffL);
|
||||
case 0xcf: // unsigned int 64
|
||||
more(9);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 8);
|
||||
{
|
||||
long o = castBuffer.getLong(0);
|
||||
if(o < 0) {
|
||||
// FIXME
|
||||
throw new MessageTypeException("uint 64 bigger than 0x7fffffff is not supported");
|
||||
}
|
||||
advance(9);
|
||||
return o;
|
||||
}
|
||||
case 0xd0: // signed int 8
|
||||
more(2);
|
||||
advance(2);
|
||||
return (long)buffer[offset+1];
|
||||
case 0xd1: // signed int 16
|
||||
more(3);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 2);
|
||||
advance(3);
|
||||
return (long)castBuffer.getShort(0);
|
||||
case 0xd2: // signed int 32
|
||||
more(4);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
advance(4);
|
||||
return (long)castBuffer.getInt(0);
|
||||
case 0xd3: // signed int 64
|
||||
more(9);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 8);
|
||||
advance(9);
|
||||
return (long)castBuffer.getLong(0);
|
||||
default:
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
final float unpackFloat() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset];
|
||||
switch(b & 0xff) {
|
||||
case 0xca: // float
|
||||
more(5);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
advance(5);
|
||||
return castBuffer.getFloat(0);
|
||||
case 0xcb: // double
|
||||
more(9);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 8);
|
||||
advance(9);
|
||||
// FIXME overflow check
|
||||
return (float)castBuffer.getDouble(0);
|
||||
default:
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
final double unpackDouble() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset];
|
||||
switch(b & 0xff) {
|
||||
case 0xca: // float
|
||||
more(5);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
advance(5);
|
||||
return (double)castBuffer.getFloat(0);
|
||||
case 0xcb: // double
|
||||
more(9);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 8);
|
||||
advance(9);
|
||||
return castBuffer.getDouble(0);
|
||||
default:
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
final Object unpackNull() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset] & 0xff;
|
||||
if(b != 0xc0) { // nil
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
advance(1);
|
||||
return null;
|
||||
}
|
||||
|
||||
final boolean tryUnpackNull() throws IOException {
|
||||
if(!tryMore(1)) {
|
||||
return false;
|
||||
}
|
||||
int b = buffer[offset] & 0xff;
|
||||
if(b != 0xc0) { // nil
|
||||
return false;
|
||||
}
|
||||
advance(1);
|
||||
return true;
|
||||
}
|
||||
|
||||
final boolean unpackBoolean() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset] & 0xff;
|
||||
if(b == 0xc2) { // false
|
||||
advance(1);
|
||||
return false;
|
||||
} else if(b == 0xc3) { // true
|
||||
advance(1);
|
||||
return true;
|
||||
} else {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
final int unpackArray() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset];
|
||||
if((b & 0xf0) == 0x90) { // FixArray
|
||||
advance(1);
|
||||
return (int)(b & 0x0f);
|
||||
}
|
||||
switch(b & 0xff) {
|
||||
case 0xdc: // array 16
|
||||
more(3);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 2);
|
||||
advance(3);
|
||||
return (int)castBuffer.getShort(0) & 0xffff;
|
||||
case 0xdd: // array 32
|
||||
more(5);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
advance(5);
|
||||
// FIXME overflow check
|
||||
return castBuffer.getInt(0) & 0x7fffffff;
|
||||
default:
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
final int unpackMap() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset];
|
||||
if((b & 0xf0) == 0x80) { // FixMap
|
||||
advance(1);
|
||||
return (int)(b & 0x0f);
|
||||
}
|
||||
switch(b & 0xff) {
|
||||
case 0xde: // map 16
|
||||
more(3);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 2);
|
||||
advance(3);
|
||||
return (int)castBuffer.getShort(0) & 0xffff;
|
||||
case 0xdf: // map 32
|
||||
more(5);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
advance(5);
|
||||
// FIXME overflow check
|
||||
return castBuffer.getInt(0) & 0x7fffffff;
|
||||
default:
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
final int unpackRaw() throws IOException, MessageTypeException {
|
||||
more(1);
|
||||
int b = buffer[offset];
|
||||
if((b & 0xe0) == 0xa0) { // FixRaw
|
||||
advance(1);
|
||||
return (int)(b & 0x1f);
|
||||
}
|
||||
switch(b & 0xff) {
|
||||
case 0xda: // raw 16
|
||||
more(3);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 2);
|
||||
advance(3);
|
||||
return (int)castBuffer.getShort(0) & 0xffff;
|
||||
case 0xdb: // raw 32
|
||||
more(5);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(buffer, offset+1, 4);
|
||||
advance(5);
|
||||
// FIXME overflow check
|
||||
return castBuffer.getInt(0) & 0x7fffffff;
|
||||
default:
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
final byte[] unpackRawBody(int length) throws IOException {
|
||||
more(length);
|
||||
byte[] bytes = new byte[length];
|
||||
System.arraycopy(buffer, offset, bytes, 0, length);
|
||||
advance(length);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
final byte[] unpackByteArray() throws IOException, MessageTypeException {
|
||||
int length = unpackRaw();
|
||||
return unpackRawBody(length);
|
||||
}
|
||||
|
||||
final String unpackString() throws IOException, MessageTypeException {
|
||||
int length = unpackRaw();
|
||||
more(length);
|
||||
String s;
|
||||
try {
|
||||
s = new String(buffer, offset, length, "UTF-8");
|
||||
} catch (Exception e) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
advance(length);
|
||||
return s;
|
||||
}
|
||||
|
||||
final Object unpackObject() throws IOException {
|
||||
UnpackResult result = new UnpackResult();
|
||||
if(!next(result)) {
|
||||
super.reset();
|
||||
throw new UnpackException("insufficient buffer");
|
||||
}
|
||||
return result.getData();
|
||||
}
|
||||
}
|
||||
|
@@ -1,23 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
public interface MessageConvertable {
|
||||
public void messageConvert(Object obj) throws MessageTypeException;
|
||||
}
|
||||
|
@@ -1,25 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface MessagePackable {
|
||||
public void messagePack(Packer pk) throws IOException;
|
||||
}
|
||||
|
@@ -1,37 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
public class MessageTypeException extends RuntimeException {
|
||||
public MessageTypeException() { }
|
||||
|
||||
public MessageTypeException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
public static MessageTypeException invalidConvert(Object from, Schema to) {
|
||||
return new MessageTypeException(from.getClass().getName()+" cannot be convert to "+to.getExpression());
|
||||
}
|
||||
|
||||
/* FIXME
|
||||
public static MessageTypeException schemaMismatch(Schema to) {
|
||||
return new MessageTypeException("schema mismatch "+to.getExpression());
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
@@ -1,25 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface MessageUnpackable {
|
||||
public void messageUnpack(Unpacker pac) throws IOException, MessageTypeException;
|
||||
}
|
||||
|
@@ -1,428 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Packer enables you to serialize objects into OutputStream.
|
||||
*
|
||||
* <pre>
|
||||
* // create a packer with output stream
|
||||
* Packer pk = new Packer(System.out);
|
||||
*
|
||||
* // store an object with pack() method.
|
||||
* pk.pack(1);
|
||||
*
|
||||
* // you can store String, List, Map, byte[] and primitive types.
|
||||
* pk.pack(new ArrayList());
|
||||
* </pre>
|
||||
*
|
||||
* You can serialize objects that implements {@link MessagePackable} interface.
|
||||
*/
|
||||
public class Packer {
|
||||
protected byte[] castBytes = new byte[9];
|
||||
protected ByteBuffer castBuffer = ByteBuffer.wrap(castBytes);
|
||||
protected OutputStream out;
|
||||
|
||||
public Packer(OutputStream out) {
|
||||
this.out = out;
|
||||
}
|
||||
|
||||
public Packer packByte(byte d) throws IOException {
|
||||
if(d < -(1<<5)) {
|
||||
castBytes[0] = (byte)0xd0;
|
||||
castBytes[1] = d;
|
||||
out.write(castBytes, 0, 2);
|
||||
} else {
|
||||
out.write(d);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packShort(short d) throws IOException {
|
||||
if(d < -(1<<5)) {
|
||||
if(d < -(1<<7)) {
|
||||
// signed 16
|
||||
castBytes[0] = (byte)0xd1;
|
||||
castBuffer.putShort(1, d);
|
||||
out.write(castBytes, 0, 3);
|
||||
} else {
|
||||
// signed 8
|
||||
castBytes[0] = (byte)0xd0;
|
||||
castBytes[1] = (byte)d;
|
||||
out.write(castBytes, 0, 2);
|
||||
}
|
||||
} else if(d < (1<<7)) {
|
||||
// fixnum
|
||||
out.write((byte)d);
|
||||
} else {
|
||||
if(d < (1<<8)) {
|
||||
// unsigned 8
|
||||
castBytes[0] = (byte)0xcc;
|
||||
castBytes[1] = (byte)d;
|
||||
out.write(castBytes, 0, 2);
|
||||
} else {
|
||||
// unsigned 16
|
||||
castBytes[0] = (byte)0xcd;
|
||||
castBuffer.putShort(1, d);
|
||||
out.write(castBytes, 0, 3);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packInt(int d) throws IOException {
|
||||
if(d < -(1<<5)) {
|
||||
if(d < -(1<<15)) {
|
||||
// signed 32
|
||||
castBytes[0] = (byte)0xd2;
|
||||
castBuffer.putInt(1, d);
|
||||
out.write(castBytes, 0, 5);
|
||||
} else if(d < -(1<<7)) {
|
||||
// signed 16
|
||||
castBytes[0] = (byte)0xd1;
|
||||
castBuffer.putShort(1, (short)d);
|
||||
out.write(castBytes, 0, 3);
|
||||
} else {
|
||||
// signed 8
|
||||
castBytes[0] = (byte)0xd0;
|
||||
castBytes[1] = (byte)d;
|
||||
out.write(castBytes, 0, 2);
|
||||
}
|
||||
} else if(d < (1<<7)) {
|
||||
// fixnum
|
||||
out.write((byte)d);
|
||||
} else {
|
||||
if(d < (1<<8)) {
|
||||
// unsigned 8
|
||||
castBytes[0] = (byte)0xcc;
|
||||
castBytes[1] = (byte)d;
|
||||
out.write(castBytes, 0, 2);
|
||||
} else if(d < (1<<16)) {
|
||||
// unsigned 16
|
||||
castBytes[0] = (byte)0xcd;
|
||||
castBuffer.putShort(1, (short)d);
|
||||
out.write(castBytes, 0, 3);
|
||||
} else {
|
||||
// unsigned 32
|
||||
castBytes[0] = (byte)0xce;
|
||||
castBuffer.putInt(1, d);
|
||||
out.write(castBytes, 0, 5);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packLong(long d) throws IOException {
|
||||
if(d < -(1L<<5)) {
|
||||
if(d < -(1L<<15)) {
|
||||
if(d < -(1L<<31)) {
|
||||
// signed 64
|
||||
castBytes[0] = (byte)0xd3;
|
||||
castBuffer.putLong(1, d);
|
||||
out.write(castBytes, 0, 9);
|
||||
} else {
|
||||
// signed 32
|
||||
castBytes[0] = (byte)0xd2;
|
||||
castBuffer.putInt(1, (int)d);
|
||||
out.write(castBytes, 0, 5);
|
||||
}
|
||||
} else {
|
||||
if(d < -(1<<7)) {
|
||||
// signed 16
|
||||
castBytes[0] = (byte)0xd1;
|
||||
castBuffer.putShort(1, (short)d);
|
||||
out.write(castBytes, 0, 3);
|
||||
} else {
|
||||
// signed 8
|
||||
castBytes[0] = (byte)0xd0;
|
||||
castBytes[1] = (byte)d;
|
||||
out.write(castBytes, 0, 2);
|
||||
}
|
||||
}
|
||||
} else if(d < (1<<7)) {
|
||||
// fixnum
|
||||
out.write((byte)d);
|
||||
} else {
|
||||
if(d < (1L<<16)) {
|
||||
if(d < (1<<8)) {
|
||||
// unsigned 8
|
||||
castBytes[0] = (byte)0xcc;
|
||||
castBytes[1] = (byte)d;
|
||||
out.write(castBytes, 0, 2);
|
||||
} else {
|
||||
// unsigned 16
|
||||
castBytes[0] = (byte)0xcd;
|
||||
castBuffer.putShort(1, (short)d);
|
||||
out.write(castBytes, 0, 3);
|
||||
//System.out.println("pack uint 16 "+(short)d);
|
||||
}
|
||||
} else {
|
||||
if(d < (1L<<32)) {
|
||||
// unsigned 32
|
||||
castBytes[0] = (byte)0xce;
|
||||
castBuffer.putInt(1, (int)d);
|
||||
out.write(castBytes, 0, 5);
|
||||
} else {
|
||||
// unsigned 64
|
||||
castBytes[0] = (byte)0xcf;
|
||||
castBuffer.putLong(1, d);
|
||||
out.write(castBytes, 0, 9);
|
||||
}
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packFloat(float d) throws IOException {
|
||||
castBytes[0] = (byte)0xca;
|
||||
castBuffer.putFloat(1, d);
|
||||
out.write(castBytes, 0, 5);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packDouble(double d) throws IOException {
|
||||
castBytes[0] = (byte)0xcb;
|
||||
castBuffer.putDouble(1, d);
|
||||
out.write(castBytes, 0, 9);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packNil() throws IOException {
|
||||
out.write((byte)0xc0);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packTrue() throws IOException {
|
||||
out.write((byte)0xc3);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packFalse() throws IOException {
|
||||
out.write((byte)0xc2);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packBoolean(boolean d) throws IOException {
|
||||
return d ? packTrue() : packFalse();
|
||||
}
|
||||
|
||||
public Packer packArray(int n) throws IOException {
|
||||
if(n < 16) {
|
||||
final int d = 0x90 | n;
|
||||
out.write((byte)d);
|
||||
} else if(n < 65536) {
|
||||
castBytes[0] = (byte)0xdc;
|
||||
castBuffer.putShort(1, (short)n);
|
||||
out.write(castBytes, 0, 3);
|
||||
} else {
|
||||
castBytes[0] = (byte)0xdd;
|
||||
castBuffer.putInt(1, n);
|
||||
out.write(castBytes, 0, 5);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packMap(int n) throws IOException {
|
||||
if(n < 16) {
|
||||
final int d = 0x80 | n;
|
||||
out.write((byte)d);
|
||||
} else if(n < 65536) {
|
||||
castBytes[0] = (byte)0xde;
|
||||
castBuffer.putShort(1, (short)n);
|
||||
out.write(castBytes, 0, 3);
|
||||
} else {
|
||||
castBytes[0] = (byte)0xdf;
|
||||
castBuffer.putInt(1, n);
|
||||
out.write(castBytes, 0, 5);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packRaw(int n) throws IOException {
|
||||
if(n < 32) {
|
||||
final int d = 0xa0 | n;
|
||||
out.write((byte)d);
|
||||
} else if(n < 65536) {
|
||||
castBytes[0] = (byte)0xda;
|
||||
castBuffer.putShort(1, (short)n);
|
||||
out.write(castBytes, 0, 3);
|
||||
} else {
|
||||
castBytes[0] = (byte)0xdb;
|
||||
castBuffer.putInt(1, n);
|
||||
out.write(castBytes, 0, 5);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packRawBody(byte[] b) throws IOException {
|
||||
out.write(b);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer packRawBody(byte[] b, int off, int length) throws IOException {
|
||||
out.write(b, off, length);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public Packer packWithSchema(Object o, Schema s) throws IOException {
|
||||
s.pack(this, o);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public Packer packString(String s) throws IOException {
|
||||
byte[] b = ((String)s).getBytes("UTF-8");
|
||||
packRaw(b.length);
|
||||
return packRawBody(b);
|
||||
}
|
||||
|
||||
|
||||
public Packer pack(String o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
return packString(o);
|
||||
}
|
||||
|
||||
public Packer pack(MessagePackable o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
o.messagePack(this);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer pack(byte[] o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
packRaw(o.length);
|
||||
return packRawBody(o);
|
||||
}
|
||||
|
||||
public Packer pack(List o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
packArray(o.size());
|
||||
for(Object i : o) { pack(i); }
|
||||
return this;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Packer pack(Map o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
packMap(o.size());
|
||||
for(Map.Entry e : ((Map<Object,Object>)o).entrySet()) {
|
||||
pack(e.getKey());
|
||||
pack(e.getValue());
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Packer pack(Boolean o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
if(o) {
|
||||
return packTrue();
|
||||
} else {
|
||||
return packFalse();
|
||||
}
|
||||
}
|
||||
|
||||
public Packer pack(Byte o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
return packByte(o);
|
||||
}
|
||||
|
||||
public Packer pack(Short o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
return packShort(o);
|
||||
}
|
||||
|
||||
public Packer pack(Integer o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
return packInt(o);
|
||||
}
|
||||
|
||||
public Packer pack(Long o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
return packLong(o);
|
||||
}
|
||||
|
||||
public Packer pack(Float o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
return packFloat(o);
|
||||
}
|
||||
|
||||
public Packer pack(Double o) throws IOException {
|
||||
if(o == null) { return packNil(); }
|
||||
return packDouble(o);
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Packer pack(Object o) throws IOException {
|
||||
if(o == null) {
|
||||
return packNil();
|
||||
} else if(o instanceof String) {
|
||||
byte[] b = ((String)o).getBytes("UTF-8");
|
||||
packRaw(b.length);
|
||||
return packRawBody(b);
|
||||
} else if(o instanceof MessagePackable) {
|
||||
((MessagePackable)o).messagePack(this);
|
||||
return this;
|
||||
} else if(o instanceof byte[]) {
|
||||
byte[] b = (byte[])o;
|
||||
packRaw(b.length);
|
||||
return packRawBody(b);
|
||||
} else if(o instanceof List) {
|
||||
List<Object> l = (List<Object>)o;
|
||||
packArray(l.size());
|
||||
for(Object i : l) { pack(i); }
|
||||
return this;
|
||||
} else if(o instanceof Map) {
|
||||
Map<Object,Object> m = (Map<Object,Object>)o;
|
||||
packMap(m.size());
|
||||
for(Map.Entry e : m.entrySet()) {
|
||||
pack(e.getKey());
|
||||
pack(e.getValue());
|
||||
}
|
||||
return this;
|
||||
} else if(o instanceof Boolean) {
|
||||
if((Boolean)o) {
|
||||
return packTrue();
|
||||
} else {
|
||||
return packFalse();
|
||||
}
|
||||
} else if(o instanceof Integer) {
|
||||
return packInt((Integer)o);
|
||||
} else if(o instanceof Long) {
|
||||
return packLong((Long)o);
|
||||
} else if(o instanceof Short) {
|
||||
return packShort((Short)o);
|
||||
} else if(o instanceof Byte) {
|
||||
return packByte((Byte)o);
|
||||
} else if(o instanceof Float) {
|
||||
return packFloat((Float)o);
|
||||
} else if(o instanceof Double) {
|
||||
return packDouble((Double)o);
|
||||
} else {
|
||||
throw new MessageTypeException("unknown object "+o+" ("+o.getClass()+")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,78 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.io.Writer;
|
||||
import java.io.IOException;
|
||||
import org.msgpack.schema.SSchemaParser;
|
||||
//import org.msgpack.schema.ClassGenerator;
|
||||
|
||||
public abstract class Schema {
|
||||
public Schema() { }
|
||||
|
||||
public abstract String getClassName();
|
||||
public abstract String getExpression();
|
||||
|
||||
public static Schema parse(String source) {
|
||||
return SSchemaParser.parse(source);
|
||||
}
|
||||
|
||||
public static Schema load(String source) {
|
||||
return SSchemaParser.load(source);
|
||||
}
|
||||
|
||||
public abstract void pack(Packer pk, Object obj) throws IOException;
|
||||
public abstract Object convert(Object obj) throws MessageTypeException;
|
||||
|
||||
public Object createFromNil() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Object createFromBoolean(boolean v) {
|
||||
throw new MessageTypeException("type error");
|
||||
}
|
||||
|
||||
public Object createFromByte(byte v) {
|
||||
throw new MessageTypeException("type error");
|
||||
}
|
||||
|
||||
public Object createFromShort(short v) {
|
||||
throw new MessageTypeException("type error");
|
||||
}
|
||||
|
||||
public Object createFromInt(int v) {
|
||||
throw new MessageTypeException("type error");
|
||||
}
|
||||
|
||||
public Object createFromLong(long v) {
|
||||
throw new MessageTypeException("type error");
|
||||
}
|
||||
|
||||
public Object createFromFloat(float v) {
|
||||
throw new MessageTypeException("type error");
|
||||
}
|
||||
|
||||
public Object createFromDouble(double v) {
|
||||
throw new MessageTypeException("type error");
|
||||
}
|
||||
|
||||
public Object createFromRaw(byte[] b, int offset, int length) {
|
||||
throw new MessageTypeException("type error");
|
||||
}
|
||||
}
|
||||
|
@@ -1,29 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class UnpackException extends IOException {
|
||||
public UnpackException() { }
|
||||
|
||||
public UnpackException(String s) {
|
||||
super(s);
|
||||
}
|
||||
}
|
||||
|
@@ -1,53 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
public class UnpackIterator extends UnpackResult implements Iterator<Object> {
|
||||
private Unpacker pac;
|
||||
|
||||
UnpackIterator(Unpacker pac) {
|
||||
super();
|
||||
this.pac = pac;
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
if(finished) { return true; }
|
||||
try {
|
||||
return pac.next(this);
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Object next() {
|
||||
if(!finished && !hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
finished = false;
|
||||
return data;
|
||||
}
|
||||
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
@@ -1,572 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.lang.Iterable;
|
||||
import java.io.InputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Iterator;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
/**
|
||||
* Unpacker enables you to deserialize objects from stream.
|
||||
*
|
||||
* Unpacker provides Buffered API, Unbuffered API, Schema API
|
||||
* and Direct Conversion API.
|
||||
*
|
||||
* Buffered API uses the internal buffer of the Unpacker.
|
||||
* Following code uses Buffered API with an InputStream:
|
||||
* <pre>
|
||||
* // create an unpacker with input stream
|
||||
* Unpacker pac = new Unpacker(System.in);
|
||||
*
|
||||
* // take a object out using next() method, or ...
|
||||
* UnpackResult result = pac.next();
|
||||
*
|
||||
* // use an iterator.
|
||||
* for(Object obj : pac) {
|
||||
* // use MessageConvertable interface to convert the
|
||||
* // the generic object to the specific type.
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* Following code doesn't use the input stream and feeds buffer
|
||||
* using {@link feed(byte[])} method. This is useful to use
|
||||
* special stream like zlib or event-driven I/O library.
|
||||
* <pre>
|
||||
* // create an unpacker without input stream
|
||||
* Unpacker pac = new Unpacker();
|
||||
*
|
||||
* // feed buffer to the internal buffer.
|
||||
* pac.feed(input_bytes);
|
||||
*
|
||||
* // use next() method or iterators.
|
||||
* for(Object obj : pac) {
|
||||
* // ...
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* The combination of {@link reserveBuffer()}, {@link getBuffer()},
|
||||
* {@link getBufferOffset()}, {@link getBufferCapacity()} and
|
||||
* {@link bufferConsumed()} is useful to omit copying.
|
||||
* <pre>
|
||||
* // create an unpacker without input stream
|
||||
* Unpacker pac = new Unpacker();
|
||||
*
|
||||
* // reserve internal buffer at least 1024 bytes.
|
||||
* pac.reserveBuffer(1024);
|
||||
*
|
||||
* // feed buffer to the internal buffer upto pac.getBufferCapacity() bytes.
|
||||
* System.in.read(pac.getBuffer(), pac.getBufferOffset(), pac.getBufferCapacity());
|
||||
*
|
||||
* // use next() method or iterators.
|
||||
* for(Object obj : pac) {
|
||||
* // ...
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* Unbuffered API doesn't initialize the internal buffer.
|
||||
* You can manage the buffer manually.
|
||||
* <pre>
|
||||
* // create an unpacker with input stream
|
||||
* Unpacker pac = new Unpacker(System.in);
|
||||
*
|
||||
* // manage the buffer manually.
|
||||
* byte[] buffer = new byte[1024];
|
||||
* int filled = System.in.read(buffer);
|
||||
* int offset = 0;
|
||||
*
|
||||
* // deserialize objects using execute() method.
|
||||
* int nextOffset = pac.execute(buffer, offset, filled);
|
||||
*
|
||||
* // take out object if deserialized object is ready.
|
||||
* if(pac.isFinished()) {
|
||||
* Object obj = pac.getData();
|
||||
* // ...
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
public class Unpacker implements Iterable<Object> {
|
||||
|
||||
// buffer:
|
||||
// +---------------------------------------------+
|
||||
// | [object] | [obje| unparsed ... | unused ...|
|
||||
// +---------------------------------------------+
|
||||
// ^ parsed
|
||||
// ^ offset
|
||||
// ^ filled
|
||||
// ^ buffer.length
|
||||
|
||||
private static final int DEFAULT_BUFFER_SIZE = 32*1024;
|
||||
|
||||
protected int parsed;
|
||||
protected int bufferReserveSize;
|
||||
protected InputStream stream;
|
||||
|
||||
final class BufferedUnpackerMixin extends BufferedUnpackerImpl {
|
||||
boolean fill() throws IOException {
|
||||
if(stream == null) {
|
||||
return false;
|
||||
}
|
||||
reserveBuffer(bufferReserveSize);
|
||||
int rl = stream.read(buffer, filled, buffer.length - filled);
|
||||
// equals: stream.read(getBuffer(), getBufferOffset(), getBufferCapacity());
|
||||
if(rl <= 0) {
|
||||
return false;
|
||||
}
|
||||
bufferConsumed(rl);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
final BufferedUnpackerMixin impl = new BufferedUnpackerMixin();
|
||||
|
||||
|
||||
/**
|
||||
* Calls {@link Unpacker(DEFAULT_BUFFER_SIZE)}
|
||||
*/
|
||||
public Unpacker() {
|
||||
this(DEFAULT_BUFFER_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls {@link Unpacker(null, bufferReserveSize)}
|
||||
*/
|
||||
public Unpacker(int bufferReserveSize) {
|
||||
this(null, bufferReserveSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls {@link Unpacker(stream, DEFAULT_BUFFER_SIZE)}
|
||||
*/
|
||||
public Unpacker(InputStream stream) {
|
||||
this(stream, DEFAULT_BUFFER_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs the unpacker.
|
||||
* The stream is used to fill the buffer when more buffer is required by {@link next()} or {@link UnpackIterator#hasNext()} method.
|
||||
* @param stream input stream to fill the buffer
|
||||
* @param bufferReserveSize threshold size to expand the size of buffer
|
||||
*/
|
||||
public Unpacker(InputStream stream, int bufferReserveSize) {
|
||||
this.parsed = 0;
|
||||
this.bufferReserveSize = bufferReserveSize/2;
|
||||
this.stream = stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets schema to convert deserialized object into specific type.
|
||||
* Default schema is {@link GenericSchema} that leaves objects for generic type. Use {@link MessageConvertable#messageConvert(Object)} method to convert the generic object.
|
||||
* @param s schem to use
|
||||
*/
|
||||
public Unpacker useSchema(Schema s) {
|
||||
impl.setSchema(s);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the input stream.
|
||||
* @return the input stream. it may be null.
|
||||
*/
|
||||
public InputStream getStream() {
|
||||
return this.stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the input stream.
|
||||
* @param stream the input stream to set.
|
||||
*/
|
||||
public void setStream(InputStream stream) {
|
||||
this.stream = stream;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fills the buffer with the specified buffer.
|
||||
*/
|
||||
public void feed(byte[] buffer) {
|
||||
feed(buffer, 0, buffer.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills the buffer with the specified buffer.
|
||||
*/
|
||||
public void feed(byte[] buffer, int offset, int length) {
|
||||
reserveBuffer(length);
|
||||
System.arraycopy(buffer, offset, impl.buffer, impl.offset, length);
|
||||
bufferConsumed(length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills the buffer with the specified buffer.
|
||||
*/
|
||||
public void feed(ByteBuffer buffer) {
|
||||
int length = buffer.remaining();
|
||||
if (length == 0) return;
|
||||
reserveBuffer(length);
|
||||
buffer.get(impl.buffer, impl.offset, length);
|
||||
bufferConsumed(length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps the internal buffer with the specified buffer.
|
||||
* This method doesn't copy the buffer and the its contents will be rewritten by {@link fill()} or {@link feed(byte[])} method.
|
||||
*/
|
||||
public void wrap(byte[] buffer) {
|
||||
wrap(buffer, 0, buffer.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps the internal buffer with the specified buffer.
|
||||
* This method doesn't copy the buffer and the its contents will be rewritten by {@link fill()} or {@link feed(byte[])} method.
|
||||
*/
|
||||
public void wrap(byte[] buffer, int offset, int length) {
|
||||
impl.buffer = buffer;
|
||||
impl.offset = offset;
|
||||
impl.filled = length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills the internal using the input stream.
|
||||
* @return false if the stream is null or stream.read returns <= 0.
|
||||
*/
|
||||
public boolean fill() throws IOException {
|
||||
return impl.fill();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the iterator that calls {@link next()} method repeatedly.
|
||||
*/
|
||||
public Iterator<Object> iterator() {
|
||||
return new UnpackIterator(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes one object and returns it.
|
||||
* @return {@link UnpackResult#isFinished()} returns false if the buffer is insufficient to deserialize one object.
|
||||
*/
|
||||
public UnpackResult next() throws IOException, UnpackException {
|
||||
UnpackResult result = new UnpackResult();
|
||||
impl.next(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes one object and returns it.
|
||||
* @return false if the buffer is insufficient to deserialize one object.
|
||||
*/
|
||||
public boolean next(UnpackResult result) throws IOException, UnpackException {
|
||||
return impl.next(result);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Reserve free space of the internal buffer at least specified size and expands {@link getBufferCapacity()}.
|
||||
*/
|
||||
public void reserveBuffer(int require) {
|
||||
if(impl.buffer == null) {
|
||||
int nextSize = (bufferReserveSize < require) ? require : bufferReserveSize;
|
||||
impl.buffer = new byte[nextSize];
|
||||
return;
|
||||
}
|
||||
|
||||
if(impl.filled <= impl.offset) {
|
||||
// rewind the buffer
|
||||
impl.filled = 0;
|
||||
impl.offset = 0;
|
||||
}
|
||||
|
||||
if(impl.buffer.length - impl.filled >= require) {
|
||||
return;
|
||||
}
|
||||
|
||||
int nextSize = impl.buffer.length * 2;
|
||||
int notParsed = impl.filled - impl.offset;
|
||||
while(nextSize < require + notParsed) {
|
||||
nextSize *= 2;
|
||||
}
|
||||
|
||||
byte[] tmp = new byte[nextSize];
|
||||
System.arraycopy(impl.buffer, impl.offset, tmp, 0, impl.filled - impl.offset);
|
||||
|
||||
impl.buffer = tmp;
|
||||
impl.filled = notParsed;
|
||||
impl.offset = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the internal buffer.
|
||||
*/
|
||||
public byte[] getBuffer() {
|
||||
return impl.buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the size of free space of the internal buffer.
|
||||
*/
|
||||
public int getBufferCapacity() {
|
||||
return impl.buffer.length - impl.filled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the offset of free space in the internal buffer.
|
||||
*/
|
||||
public int getBufferOffset() {
|
||||
return impl.filled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves front the offset of the free space in the internal buffer.
|
||||
* Call this method after fill the buffer manually using {@link reserveBuffer()}, {@link getBuffer()}, {@link getBufferOffset()} and {@link getBufferCapacity()} methods.
|
||||
*/
|
||||
public void bufferConsumed(int size) {
|
||||
impl.filled += size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes one object upto the offset of the internal buffer.
|
||||
* Call {@link reset()} method before calling this method again.
|
||||
* @return true if one object is deserialized. Use {@link getData()} to get the deserialized object.
|
||||
*/
|
||||
public boolean execute() throws UnpackException {
|
||||
int noffset = impl.execute(impl.buffer, impl.offset, impl.filled);
|
||||
if(noffset <= impl.offset) {
|
||||
return false;
|
||||
}
|
||||
parsed += noffset - impl.offset;
|
||||
impl.offset = noffset;
|
||||
return impl.isFinished();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Deserializes one object over the specified buffer.
|
||||
* This method doesn't use the internal buffer.
|
||||
* Use {@link isFinished()} method to known a object is ready to get.
|
||||
* Call {@link reset()} method before calling this method again.
|
||||
* @return offset position that is parsed.
|
||||
*/
|
||||
public int execute(byte[] buffer) throws UnpackException {
|
||||
return execute(buffer, 0, buffer.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserializes one object over the specified buffer.
|
||||
* This method doesn't use the internal buffer.
|
||||
* Use {@link isFinished()} method to known a object is ready to get.
|
||||
* Call {@link reset()} method before calling this method again.
|
||||
* @return offset position that is parsed.
|
||||
*/
|
||||
public int execute(byte[] buffer, int offset, int length) throws UnpackException {
|
||||
int noffset = impl.execute(buffer, offset + impl.offset, length);
|
||||
impl.offset = noffset - offset;
|
||||
if(impl.isFinished()) {
|
||||
impl.resetState();
|
||||
}
|
||||
return noffset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the object deserialized by {@link execute(byte[])} method.
|
||||
*/
|
||||
public Object getData() {
|
||||
return impl.getData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an object is ready to get with {@link getData()} method.
|
||||
*/
|
||||
public boolean isFinished() {
|
||||
return impl.isFinished();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the internal state of the unpacker.
|
||||
*/
|
||||
public void reset() {
|
||||
impl.reset();
|
||||
}
|
||||
|
||||
public int getMessageSize() {
|
||||
return parsed - impl.offset + impl.filled;
|
||||
}
|
||||
|
||||
public int getParsedSize() {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
public int getNonParsedSize() {
|
||||
return impl.filled - impl.offset;
|
||||
}
|
||||
|
||||
public void skipNonparsedBuffer(int size) {
|
||||
impl.offset += size;
|
||||
}
|
||||
|
||||
public void removeNonparsedBuffer() {
|
||||
impl.filled = impl.offset;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets one {@code byte} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code byte}.
|
||||
*/
|
||||
public byte unpackByte() throws IOException, MessageTypeException {
|
||||
return impl.unpackByte();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code short} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code short}.
|
||||
*/
|
||||
public short unpackShort() throws IOException, MessageTypeException {
|
||||
return impl.unpackShort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code int} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code int}.
|
||||
*/
|
||||
public int unpackInt() throws IOException, MessageTypeException {
|
||||
return impl.unpackInt();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code long} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code long}.
|
||||
*/
|
||||
public long unpackLong() throws IOException, MessageTypeException {
|
||||
return impl.unpackLong();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code float} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code float}.
|
||||
*/
|
||||
public float unpackFloat() throws IOException, MessageTypeException {
|
||||
return impl.unpackFloat();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code double} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code double}.
|
||||
*/
|
||||
public double unpackDouble() throws IOException, MessageTypeException {
|
||||
return impl.unpackDouble();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code null} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code null}.
|
||||
*/
|
||||
public Object unpackNull() throws IOException, MessageTypeException {
|
||||
return impl.unpackNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code boolean} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code boolean}.
|
||||
*/
|
||||
public boolean unpackBoolean() throws IOException, MessageTypeException {
|
||||
return impl.unpackBoolean();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one array header from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @return the length of the map. There are {@code retval} objects to get.
|
||||
* @throws MessageTypeException the first value of the buffer is not a array.
|
||||
*/
|
||||
public int unpackArray() throws IOException, MessageTypeException {
|
||||
return impl.unpackArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one map header from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @return the length of the map. There are {@code retval * 2} objects to get.
|
||||
* @throws MessageTypeException the first value of the buffer is not a map.
|
||||
*/
|
||||
public int unpackMap() throws IOException, MessageTypeException {
|
||||
return impl.unpackMap();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one raw header from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @return the length of the raw bytes. There are {@code retval} bytes to get.
|
||||
* @throws MessageTypeException the first value of the buffer is not a raw bytes.
|
||||
*/
|
||||
public int unpackRaw() throws IOException, MessageTypeException {
|
||||
return impl.unpackRaw();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one raw body from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
*/
|
||||
public byte[] unpackRawBody(int length) throws IOException {
|
||||
return impl.unpackRawBody(length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one raw bytes from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
*/
|
||||
public byte[] unpackByteArray() throws IOException {
|
||||
return impl.unpackByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code String} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
* @throws MessageTypeException the first value of the buffer is not a {@code String}.
|
||||
*/
|
||||
final public String unpackString() throws IOException, MessageTypeException {
|
||||
return impl.unpackString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets one {@code Object} value from the buffer.
|
||||
* This method calls {@link fill()} method if needed.
|
||||
*/
|
||||
final public Object unpackObject() throws IOException {
|
||||
return impl.unpackObject();
|
||||
}
|
||||
|
||||
final public void unpack(MessageUnpackable obj) throws IOException, MessageTypeException {
|
||||
obj.messageUnpack(this);
|
||||
}
|
||||
|
||||
final public boolean tryUnpackNull() throws IOException {
|
||||
return impl.tryUnpackNull();
|
||||
}
|
||||
}
|
||||
|
@@ -1,522 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
//import java.math.BigInteger;
|
||||
import org.msgpack.*;
|
||||
import org.msgpack.schema.GenericSchema;
|
||||
import org.msgpack.schema.IMapSchema;
|
||||
import org.msgpack.schema.IArraySchema;
|
||||
|
||||
public class UnpackerImpl {
|
||||
static final int CS_HEADER = 0x00;
|
||||
static final int CS_FLOAT = 0x0a;
|
||||
static final int CS_DOUBLE = 0x0b;
|
||||
static final int CS_UINT_8 = 0x0c;
|
||||
static final int CS_UINT_16 = 0x0d;
|
||||
static final int CS_UINT_32 = 0x0e;
|
||||
static final int CS_UINT_64 = 0x0f;
|
||||
static final int CS_INT_8 = 0x10;
|
||||
static final int CS_INT_16 = 0x11;
|
||||
static final int CS_INT_32 = 0x12;
|
||||
static final int CS_INT_64 = 0x13;
|
||||
static final int CS_RAW_16 = 0x1a;
|
||||
static final int CS_RAW_32 = 0x1b;
|
||||
static final int CS_ARRAY_16 = 0x1c;
|
||||
static final int CS_ARRAY_32 = 0x1d;
|
||||
static final int CS_MAP_16 = 0x1e;
|
||||
static final int CS_MAP_32 = 0x1f;
|
||||
static final int ACS_RAW_VALUE = 0x20;
|
||||
static final int CT_ARRAY_ITEM = 0x00;
|
||||
static final int CT_MAP_KEY = 0x01;
|
||||
static final int CT_MAP_VALUE = 0x02;
|
||||
|
||||
static final int MAX_STACK_SIZE = 32;
|
||||
|
||||
private int cs;
|
||||
private int trail;
|
||||
private int top;
|
||||
private int[] stack_ct = new int[MAX_STACK_SIZE];
|
||||
private int[] stack_count = new int[MAX_STACK_SIZE];
|
||||
private Object[] stack_obj = new Object[MAX_STACK_SIZE];
|
||||
private Schema[] stack_schema = new Schema[MAX_STACK_SIZE];
|
||||
private int top_ct;
|
||||
private int top_count;
|
||||
private Object top_obj;
|
||||
private Schema top_schema;
|
||||
private ByteBuffer castBuffer = ByteBuffer.allocate(8);
|
||||
private boolean finished = false;
|
||||
private Object data = null;
|
||||
|
||||
private static final Schema GENERIC_SCHEMA = new GenericSchema();
|
||||
private Schema rootSchema;
|
||||
|
||||
public UnpackerImpl()
|
||||
{
|
||||
setSchema(GENERIC_SCHEMA);
|
||||
}
|
||||
|
||||
public void setSchema(Schema schema)
|
||||
{
|
||||
this.rootSchema = schema;
|
||||
reset();
|
||||
}
|
||||
|
||||
public final Object getData()
|
||||
{
|
||||
return data;
|
||||
}
|
||||
|
||||
public final boolean isFinished()
|
||||
{
|
||||
return finished;
|
||||
}
|
||||
|
||||
public final void resetState() {
|
||||
cs = CS_HEADER;
|
||||
top = -1;
|
||||
top_ct = 0;
|
||||
top_count = 0;
|
||||
top_obj = null;
|
||||
top_schema = rootSchema;
|
||||
}
|
||||
|
||||
public final void reset()
|
||||
{
|
||||
resetState();
|
||||
finished = false;
|
||||
data = null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final int execute(byte[] src, int off, int length) throws UnpackException
|
||||
{
|
||||
if(off >= length) { return off; }
|
||||
|
||||
int limit = length;
|
||||
int i = off;
|
||||
int count;
|
||||
|
||||
Object obj = null;
|
||||
|
||||
_out: do {
|
||||
_header_again: {
|
||||
//System.out.println("while i:"+i+" limit:"+limit);
|
||||
|
||||
int b = src[i];
|
||||
|
||||
_push: {
|
||||
_fixed_trail_again:
|
||||
if(cs == CS_HEADER) {
|
||||
|
||||
if((b & 0x80) == 0) { // Positive Fixnum
|
||||
//System.out.println("positive fixnum "+b);
|
||||
obj = top_schema.createFromByte((byte)b);
|
||||
break _push;
|
||||
}
|
||||
|
||||
if((b & 0xe0) == 0xe0) { // Negative Fixnum
|
||||
//System.out.println("negative fixnum "+b);
|
||||
obj = top_schema.createFromByte((byte)b);
|
||||
break _push;
|
||||
}
|
||||
|
||||
if((b & 0xe0) == 0xa0) { // FixRaw
|
||||
trail = b & 0x1f;
|
||||
if(trail == 0) {
|
||||
obj = top_schema.createFromRaw(new byte[0], 0, 0);
|
||||
break _push;
|
||||
}
|
||||
cs = ACS_RAW_VALUE;
|
||||
break _fixed_trail_again;
|
||||
}
|
||||
|
||||
if((b & 0xf0) == 0x90) { // FixArray
|
||||
if(top >= MAX_STACK_SIZE) {
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
if(!(top_schema instanceof IArraySchema)) {
|
||||
throw new RuntimeException("type error");
|
||||
}
|
||||
count = b & 0x0f;
|
||||
//System.out.println("fixarray count:"+count);
|
||||
obj = new Object[count];
|
||||
if(count == 0) {
|
||||
obj = ((IArraySchema)top_schema).createFromArray((Object[])obj);
|
||||
break _push;
|
||||
}
|
||||
++top;
|
||||
stack_obj[top] = top_obj;
|
||||
stack_ct[top] = top_ct;
|
||||
stack_count[top] = top_count;
|
||||
stack_schema[top] = top_schema;
|
||||
top_obj = obj;
|
||||
top_ct = CT_ARRAY_ITEM;
|
||||
top_count = count;
|
||||
top_schema = ((IArraySchema)top_schema).getElementSchema(0);
|
||||
break _header_again;
|
||||
}
|
||||
|
||||
if((b & 0xf0) == 0x80) { // FixMap
|
||||
if(top >= MAX_STACK_SIZE) {
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
if(!(top_schema instanceof IMapSchema)) {
|
||||
throw new RuntimeException("type error");
|
||||
}
|
||||
count = b & 0x0f;
|
||||
obj = new Object[count*2];
|
||||
if(count == 0) {
|
||||
obj = ((IMapSchema)top_schema).createFromMap((Object[])obj);
|
||||
break _push;
|
||||
}
|
||||
//System.out.println("fixmap count:"+count);
|
||||
++top;
|
||||
stack_obj[top] = top_obj;
|
||||
stack_ct[top] = top_ct;
|
||||
stack_count[top] = top_count;
|
||||
stack_schema[top] = top_schema;
|
||||
top_obj = obj;
|
||||
top_ct = CT_MAP_KEY;
|
||||
top_count = count;
|
||||
top_schema = ((IMapSchema)top_schema).getKeySchema();
|
||||
break _header_again;
|
||||
}
|
||||
|
||||
switch(b & 0xff) { // FIXME
|
||||
case 0xc0: // nil
|
||||
obj = top_schema.createFromNil();
|
||||
break _push;
|
||||
case 0xc2: // false
|
||||
obj = top_schema.createFromBoolean(false);
|
||||
break _push;
|
||||
case 0xc3: // true
|
||||
obj = top_schema.createFromBoolean(true);
|
||||
break _push;
|
||||
case 0xca: // float
|
||||
case 0xcb: // double
|
||||
case 0xcc: // unsigned int 8
|
||||
case 0xcd: // unsigned int 16
|
||||
case 0xce: // unsigned int 32
|
||||
case 0xcf: // unsigned int 64
|
||||
case 0xd0: // signed int 8
|
||||
case 0xd1: // signed int 16
|
||||
case 0xd2: // signed int 32
|
||||
case 0xd3: // signed int 64
|
||||
trail = 1 << (b & 0x03);
|
||||
cs = b & 0x1f;
|
||||
//System.out.println("a trail "+trail+" cs:"+cs);
|
||||
break _fixed_trail_again;
|
||||
case 0xda: // raw 16
|
||||
case 0xdb: // raw 32
|
||||
case 0xdc: // array 16
|
||||
case 0xdd: // array 32
|
||||
case 0xde: // map 16
|
||||
case 0xdf: // map 32
|
||||
trail = 2 << (b & 0x01);
|
||||
cs = b & 0x1f;
|
||||
//System.out.println("b trail "+trail+" cs:"+cs);
|
||||
break _fixed_trail_again;
|
||||
default:
|
||||
//System.out.println("unknown b "+(b&0xff));
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
|
||||
} // _fixed_trail_again
|
||||
|
||||
do {
|
||||
_fixed_trail_again: {
|
||||
|
||||
if(limit - i <= trail) { break _out; }
|
||||
int n = i + 1;
|
||||
i += trail;
|
||||
|
||||
switch(cs) {
|
||||
case CS_FLOAT:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 4);
|
||||
obj = top_schema.createFromFloat( castBuffer.getFloat(0) );
|
||||
//System.out.println("float "+obj);
|
||||
break _push;
|
||||
case CS_DOUBLE:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 8);
|
||||
obj = top_schema.createFromDouble( castBuffer.getDouble(0) );
|
||||
//System.out.println("double "+obj);
|
||||
break _push;
|
||||
case CS_UINT_8:
|
||||
//System.out.println(n);
|
||||
//System.out.println(src[n]);
|
||||
//System.out.println(src[n+1]);
|
||||
//System.out.println(src[n-1]);
|
||||
obj = top_schema.createFromShort( (short)((src[n]) & 0xff) );
|
||||
//System.out.println("uint8 "+obj);
|
||||
break _push;
|
||||
case CS_UINT_16:
|
||||
//System.out.println(src[n]);
|
||||
//System.out.println(src[n+1]);
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 2);
|
||||
obj = top_schema.createFromInt( ((int)castBuffer.getShort(0)) & 0xffff );
|
||||
//System.out.println("uint 16 "+obj);
|
||||
break _push;
|
||||
case CS_UINT_32:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 4);
|
||||
obj = top_schema.createFromLong( ((long)castBuffer.getInt(0)) & 0xffffffffL );
|
||||
//System.out.println("uint 32 "+obj);
|
||||
break _push;
|
||||
case CS_UINT_64:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 8);
|
||||
{
|
||||
long o = castBuffer.getLong(0);
|
||||
if(o < 0) {
|
||||
// FIXME
|
||||
//obj = GenericBigInteger.valueOf(o & 0x7fffffffL).setBit(31);
|
||||
throw new UnpackException("uint 64 bigger than 0x7fffffff is not supported");
|
||||
} else {
|
||||
obj = top_schema.createFromLong( o );
|
||||
}
|
||||
}
|
||||
break _push;
|
||||
case CS_INT_8:
|
||||
obj = top_schema.createFromByte( src[n] );
|
||||
break _push;
|
||||
case CS_INT_16:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 2);
|
||||
obj = top_schema.createFromShort( castBuffer.getShort(0) );
|
||||
break _push;
|
||||
case CS_INT_32:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 4);
|
||||
obj = top_schema.createFromInt( castBuffer.getInt(0) );
|
||||
break _push;
|
||||
case CS_INT_64:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 8);
|
||||
obj = top_schema.createFromLong( castBuffer.getLong(0) );
|
||||
break _push;
|
||||
case CS_RAW_16:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 2);
|
||||
trail = ((int)castBuffer.getShort(0)) & 0xffff;
|
||||
if(trail == 0) {
|
||||
obj = top_schema.createFromRaw(new byte[0], 0, 0);
|
||||
break _push;
|
||||
}
|
||||
cs = ACS_RAW_VALUE;
|
||||
break _fixed_trail_again;
|
||||
case CS_RAW_32:
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 4);
|
||||
// FIXME overflow check
|
||||
trail = castBuffer.getInt(0) & 0x7fffffff;
|
||||
if(trail == 0) {
|
||||
obj = top_schema.createFromRaw(new byte[0], 0, 0);
|
||||
break _push;
|
||||
}
|
||||
cs = ACS_RAW_VALUE;
|
||||
case ACS_RAW_VALUE:
|
||||
obj = top_schema.createFromRaw(src, n, trail);
|
||||
break _push;
|
||||
case CS_ARRAY_16:
|
||||
if(top >= MAX_STACK_SIZE) {
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
if(!(top_schema instanceof IArraySchema)) {
|
||||
throw new RuntimeException("type error");
|
||||
}
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 2);
|
||||
count = ((int)castBuffer.getShort(0)) & 0xffff;
|
||||
obj = new Object[count];
|
||||
if(count == 0) {
|
||||
obj = ((IArraySchema)top_schema).createFromArray((Object[])obj);
|
||||
break _push;
|
||||
}
|
||||
++top;
|
||||
stack_obj[top] = top_obj;
|
||||
stack_ct[top] = top_ct;
|
||||
stack_count[top] = top_count;
|
||||
stack_schema[top] = top_schema;
|
||||
top_obj = obj;
|
||||
top_ct = CT_ARRAY_ITEM;
|
||||
top_count = count;
|
||||
top_schema = ((IArraySchema)top_schema).getElementSchema(0);
|
||||
break _header_again;
|
||||
case CS_ARRAY_32:
|
||||
if(top >= MAX_STACK_SIZE) {
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
if(!(top_schema instanceof IArraySchema)) {
|
||||
throw new RuntimeException("type error");
|
||||
}
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 4);
|
||||
// FIXME overflow check
|
||||
count = castBuffer.getInt(0) & 0x7fffffff;
|
||||
obj = new Object[count];
|
||||
if(count == 0) {
|
||||
obj = ((IArraySchema)top_schema).createFromArray((Object[])obj);
|
||||
break _push;
|
||||
}
|
||||
++top;
|
||||
stack_obj[top] = top_obj;
|
||||
stack_ct[top] = top_ct;
|
||||
stack_count[top] = top_count;
|
||||
stack_schema[top] = top_schema;
|
||||
top_obj = obj;
|
||||
top_ct = CT_ARRAY_ITEM;
|
||||
top_count = count;
|
||||
top_schema = ((IArraySchema)top_schema).getElementSchema(0);
|
||||
break _header_again;
|
||||
case CS_MAP_16:
|
||||
if(top >= MAX_STACK_SIZE) {
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
if(!(top_schema instanceof IMapSchema)) {
|
||||
throw new RuntimeException("type error");
|
||||
}
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 2);
|
||||
count = ((int)castBuffer.getShort(0)) & 0xffff;
|
||||
obj = new Object[count*2];
|
||||
if(count == 0) {
|
||||
obj = ((IMapSchema)top_schema).createFromMap((Object[])obj);
|
||||
break _push;
|
||||
}
|
||||
//System.out.println("fixmap count:"+count);
|
||||
++top;
|
||||
stack_obj[top] = top_obj;
|
||||
stack_ct[top] = top_ct;
|
||||
stack_count[top] = top_count;
|
||||
stack_schema[top] = top_schema;
|
||||
top_obj = obj;
|
||||
top_ct = CT_MAP_KEY;
|
||||
top_count = count;
|
||||
top_schema = ((IMapSchema)top_schema).getKeySchema();
|
||||
break _header_again;
|
||||
case CS_MAP_32:
|
||||
if(top >= MAX_STACK_SIZE) {
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
if(!(top_schema instanceof IMapSchema)) {
|
||||
throw new RuntimeException("type error");
|
||||
}
|
||||
castBuffer.rewind();
|
||||
castBuffer.put(src, n, 4);
|
||||
// FIXME overflow check
|
||||
count = castBuffer.getInt(0) & 0x7fffffff;
|
||||
obj = new Object[count*2];
|
||||
if(count == 0) {
|
||||
obj = ((IMapSchema)top_schema).createFromMap((Object[])obj);
|
||||
break _push;
|
||||
}
|
||||
//System.out.println("fixmap count:"+count);
|
||||
++top;
|
||||
stack_obj[top] = top_obj;
|
||||
stack_ct[top] = top_ct;
|
||||
stack_count[top] = top_count;
|
||||
stack_schema[top] = top_schema;
|
||||
top_obj = obj;
|
||||
top_ct = CT_MAP_KEY;
|
||||
top_count = count;
|
||||
top_schema = ((IMapSchema)top_schema).getKeySchema();
|
||||
break _header_again;
|
||||
default:
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
|
||||
} // _fixed_trail_again
|
||||
} while(true);
|
||||
} // _push
|
||||
|
||||
do {
|
||||
_push: {
|
||||
//System.out.println("push top:"+top);
|
||||
if(top == -1) {
|
||||
++i;
|
||||
data = obj;
|
||||
finished = true;
|
||||
break _out;
|
||||
}
|
||||
|
||||
switch(top_ct) {
|
||||
case CT_ARRAY_ITEM: {
|
||||
//System.out.println("array item "+obj);
|
||||
Object[] ar = (Object[])top_obj;
|
||||
ar[ar.length - top_count] = obj;
|
||||
if(--top_count == 0) {
|
||||
top_obj = stack_obj[top];
|
||||
top_ct = stack_ct[top];
|
||||
top_count = stack_count[top];
|
||||
top_schema = stack_schema[top];
|
||||
obj = ((IArraySchema)top_schema).createFromArray(ar);
|
||||
stack_obj[top] = null;
|
||||
stack_schema[top] = null;
|
||||
--top;
|
||||
break _push;
|
||||
} else {
|
||||
top_schema = ((IArraySchema)stack_schema[top]).getElementSchema(ar.length - top_count);
|
||||
}
|
||||
break _header_again;
|
||||
}
|
||||
case CT_MAP_KEY: {
|
||||
//System.out.println("map key:"+top+" "+obj);
|
||||
Object[] mp = (Object[])top_obj;
|
||||
mp[mp.length - top_count*2] = obj;
|
||||
top_ct = CT_MAP_VALUE;
|
||||
top_schema = ((IMapSchema)stack_schema[top]).getValueSchema();
|
||||
break _header_again;
|
||||
}
|
||||
case CT_MAP_VALUE: {
|
||||
//System.out.println("map value:"+top+" "+obj);
|
||||
Object[] mp = (Object[])top_obj;
|
||||
mp[mp.length - top_count*2 + 1] = obj;
|
||||
if(--top_count == 0) {
|
||||
top_obj = stack_obj[top];
|
||||
top_ct = stack_ct[top];
|
||||
top_count = stack_count[top];
|
||||
top_schema = stack_schema[top];
|
||||
obj = ((IMapSchema)top_schema).createFromMap(mp);
|
||||
stack_obj[top] = null;
|
||||
stack_schema[top] = null;
|
||||
--top;
|
||||
break _push;
|
||||
}
|
||||
top_ct = CT_MAP_KEY;
|
||||
break _header_again;
|
||||
}
|
||||
default:
|
||||
throw new UnpackException("parse error");
|
||||
}
|
||||
} // _push
|
||||
} while(true);
|
||||
|
||||
} // _header_again
|
||||
cs = CS_HEADER;
|
||||
++i;
|
||||
} while(i < limit); // _out
|
||||
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
@@ -1,8 +0,0 @@
|
||||
/**
|
||||
* MessagePack is a binary-based efficient object serialization library.
|
||||
* It enables to exchange structured objects between many languages like JSON.
|
||||
* But unlike JSON, it is very fast and small.
|
||||
*
|
||||
* Use {@link Packer} to serialize and {@link Unpacker} to deserialize.
|
||||
*/
|
||||
package org.msgpack;
|
@@ -1,64 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class BooleanSchema extends Schema {
|
||||
public BooleanSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Boolean";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "boolean";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Boolean) {
|
||||
pk.packBoolean((Boolean)obj);
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final boolean convertBoolean(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Boolean) {
|
||||
return (Boolean)obj;
|
||||
}
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertBoolean(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromBoolean(boolean v) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
@@ -1,97 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class ByteArraySchema extends Schema {
|
||||
public ByteArraySchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "byte[]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "raw";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof byte[]) {
|
||||
byte[] b = (byte[])obj;
|
||||
pk.packRaw(b.length);
|
||||
pk.packRawBody(b);
|
||||
} else if(obj instanceof String) {
|
||||
try {
|
||||
byte[] b = ((String)obj).getBytes("UTF-8");
|
||||
pk.packRaw(b.length);
|
||||
pk.packRawBody(b);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final byte[] convertByteArray(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof byte[]) {
|
||||
// FIXME copy?
|
||||
//byte[] d = (byte[])obj;
|
||||
//byte[] v = new byte[d.length];
|
||||
//System.arraycopy(d, 0, v, 0, d.length);
|
||||
//return v;
|
||||
return (byte[])obj;
|
||||
} else if(obj instanceof ByteBuffer) {
|
||||
ByteBuffer d = (ByteBuffer)obj;
|
||||
byte[] v = new byte[d.capacity()];
|
||||
int pos = d.position();
|
||||
d.get(v);
|
||||
d.position(pos);
|
||||
return v;
|
||||
} else if(obj instanceof String) {
|
||||
try {
|
||||
return ((String)obj).getBytes("UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
} else {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertByteArray(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromRaw(byte[] b, int offset, int length) {
|
||||
byte[] d = new byte[length];
|
||||
System.arraycopy(b, offset, d, 0, length);
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
@@ -1,96 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class ByteSchema extends Schema {
|
||||
public ByteSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Byte";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "byte";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Number) {
|
||||
short value = ((Number)obj).shortValue();
|
||||
if(value > Byte.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
pk.packByte((byte)value);
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final byte convertByte(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Number) {
|
||||
short value = ((Number)obj).shortValue();
|
||||
if(value > Byte.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (byte)value;
|
||||
}
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertByte(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromByte(byte v) {
|
||||
return (byte)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromShort(short v) {
|
||||
if(v > Byte.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (byte)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromInt(int v) {
|
||||
if(v > Byte.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (byte)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromLong(long v) {
|
||||
if(v > Byte.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (byte)v;
|
||||
}
|
||||
}
|
||||
|
@@ -1,244 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.io.IOException;
|
||||
import java.io.File;
|
||||
import java.io.Writer;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class ClassGenerator {
|
||||
private ClassSchema schema;
|
||||
private Writer writer;
|
||||
private int indent;
|
||||
|
||||
private ClassGenerator(Writer writer) {
|
||||
this.writer = writer;
|
||||
this.indent = 0;
|
||||
}
|
||||
|
||||
public static void write(Schema schema, Writer dest) throws IOException {
|
||||
if(!(schema instanceof ClassSchema)) {
|
||||
throw new RuntimeException("schema is not class schema");
|
||||
}
|
||||
ClassSchema cs = (ClassSchema)schema;
|
||||
new ClassGenerator(dest).run(cs);
|
||||
}
|
||||
|
||||
private void run(ClassSchema cs) throws IOException {
|
||||
List<ClassSchema> subclasses = new ArrayList<ClassSchema>();
|
||||
for(FieldSchema f : cs.getFields()) {
|
||||
findSubclassSchema(subclasses, f.getSchema());
|
||||
}
|
||||
|
||||
for(ClassSchema sub : subclasses) {
|
||||
sub.setNamespace(cs.getNamespace());
|
||||
sub.setImports(cs.getImports());
|
||||
}
|
||||
|
||||
this.schema = cs;
|
||||
|
||||
writeHeader();
|
||||
|
||||
writeClass();
|
||||
|
||||
for(ClassSchema sub : subclasses) {
|
||||
this.schema = sub;
|
||||
writeSubclass();
|
||||
}
|
||||
|
||||
writeFooter();
|
||||
|
||||
this.schema = null;
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
private void findSubclassSchema(List<ClassSchema> dst, Schema s) {
|
||||
if(s instanceof ClassSchema) {
|
||||
ClassSchema cs = (ClassSchema)s;
|
||||
if(!dst.contains(cs)) { dst.add(cs); }
|
||||
for(FieldSchema f : cs.getFields()) {
|
||||
findSubclassSchema(dst, f.getSchema());
|
||||
}
|
||||
} else if(s instanceof ListSchema) {
|
||||
ListSchema as = (ListSchema)s;
|
||||
findSubclassSchema(dst, as.getElementSchema(0));
|
||||
} else if(s instanceof SetSchema) {
|
||||
SetSchema as = (SetSchema)s;
|
||||
findSubclassSchema(dst, as.getElementSchema(0));
|
||||
} else if(s instanceof MapSchema) {
|
||||
MapSchema as = (MapSchema)s;
|
||||
findSubclassSchema(dst, as.getKeySchema());
|
||||
findSubclassSchema(dst, as.getValueSchema());
|
||||
}
|
||||
}
|
||||
|
||||
private void writeHeader() throws IOException {
|
||||
if(schema.getNamespace() != null) {
|
||||
line("package "+schema.getNamespace()+";");
|
||||
line();
|
||||
}
|
||||
line("import java.util.*;");
|
||||
line("import java.io.*;");
|
||||
line("import org.msgpack.*;");
|
||||
line("import org.msgpack.schema.ClassSchema;");
|
||||
line("import org.msgpack.schema.FieldSchema;");
|
||||
}
|
||||
|
||||
private void writeFooter() throws IOException {
|
||||
line();
|
||||
}
|
||||
|
||||
private void writeClass() throws IOException {
|
||||
line();
|
||||
line("public final class "+schema.getClassName()+" implements MessagePackable, MessageConvertable");
|
||||
line("{");
|
||||
pushIndent();
|
||||
writeSchema();
|
||||
writeMemberVariables();
|
||||
writeMemberFunctions();
|
||||
popIndent();
|
||||
line("}");
|
||||
}
|
||||
|
||||
private void writeSubclass() throws IOException {
|
||||
line();
|
||||
line("final class "+schema.getClassName()+" implements MessagePackable, MessageConvertable");
|
||||
line("{");
|
||||
pushIndent();
|
||||
writeSchema();
|
||||
writeMemberVariables();
|
||||
writeMemberFunctions();
|
||||
popIndent();
|
||||
line("}");
|
||||
}
|
||||
|
||||
private void writeSchema() throws IOException {
|
||||
line("private static final ClassSchema _SCHEMA = (ClassSchema)Schema.load(\""+schema.getExpression()+"\");");
|
||||
line("public static ClassSchema getSchema() { return _SCHEMA; }");
|
||||
}
|
||||
|
||||
private void writeMemberVariables() throws IOException {
|
||||
line();
|
||||
for(FieldSchema f : schema.getFields()) {
|
||||
line("public "+f.getSchema().getClassName()+" "+f.getName()+";");
|
||||
}
|
||||
}
|
||||
|
||||
private void writeMemberFunctions() throws IOException {
|
||||
// void messagePack(Packer pk)
|
||||
// boolean equals(Object obj)
|
||||
// int hashCode()
|
||||
// void set(int _index, Object _value)
|
||||
// Object get(int _index);
|
||||
// getXxx()
|
||||
// setXxx(Xxx xxx)
|
||||
writeConstructors();
|
||||
writeAccessors();
|
||||
writePackFunction();
|
||||
writeConvertFunction();
|
||||
writeFactoryFunction();
|
||||
}
|
||||
|
||||
private void writeConstructors() throws IOException {
|
||||
line();
|
||||
line("public "+schema.getClassName()+"() { }");
|
||||
}
|
||||
|
||||
private void writeAccessors() throws IOException {
|
||||
// FIXME
|
||||
//line();
|
||||
//for(FieldSchema f : schema.getFields()) {
|
||||
// line("");
|
||||
//}
|
||||
}
|
||||
|
||||
private void writePackFunction() throws IOException {
|
||||
line();
|
||||
line("@Override");
|
||||
line("public void messagePack(Packer _pk) throws IOException");
|
||||
line("{");
|
||||
pushIndent();
|
||||
line("_pk.packArray("+schema.getFields().length+");");
|
||||
line("FieldSchema[] _fields = _SCHEMA.getFields();");
|
||||
int i = 0;
|
||||
for(FieldSchema f : schema.getFields()) {
|
||||
line("_fields["+i+"].getSchema().pack(_pk, "+f.getName()+");");
|
||||
++i;
|
||||
}
|
||||
popIndent();
|
||||
line("}");
|
||||
}
|
||||
|
||||
private void writeConvertFunction() throws IOException {
|
||||
line();
|
||||
line("@Override");
|
||||
line("@SuppressWarnings(\"unchecked\")");
|
||||
line("public void messageConvert(Object obj) throws MessageTypeException");
|
||||
line("{");
|
||||
pushIndent();
|
||||
line("Object[] _source = ((List)obj).toArray();");
|
||||
line("FieldSchema[] _fields = _SCHEMA.getFields();");
|
||||
int i = 0;
|
||||
for(FieldSchema f : schema.getFields()) {
|
||||
line("if(_source.length <= "+i+") { return; } this."+f.getName()+" = ("+f.getSchema().getClassName()+")_fields["+i+"].getSchema().convert(_source["+i+"]);");
|
||||
++i;
|
||||
}
|
||||
popIndent();
|
||||
line("}");
|
||||
}
|
||||
|
||||
private void writeFactoryFunction() throws IOException {
|
||||
line();
|
||||
line("@SuppressWarnings(\"unchecked\")");
|
||||
line("public static "+schema.getClassName()+" createFromMessage(Object[] _message)");
|
||||
line("{");
|
||||
pushIndent();
|
||||
line(schema.getClassName()+" _self = new "+schema.getClassName()+"();");
|
||||
int i = 0;
|
||||
for(FieldSchema f : schema.getFields()) {
|
||||
line("if(_message.length <= "+i+") { return _self; } _self."+f.getName()+" = ("+f.getSchema().getClassName()+")_message["+i+"];");
|
||||
++i;
|
||||
}
|
||||
line("return _self;");
|
||||
popIndent();
|
||||
line("}");
|
||||
}
|
||||
|
||||
private void line(String str) throws IOException {
|
||||
for(int i=0; i < indent; ++i) {
|
||||
writer.write("\t");
|
||||
}
|
||||
writer.write(str+"\n");
|
||||
}
|
||||
|
||||
private void line() throws IOException {
|
||||
writer.write("\n");
|
||||
}
|
||||
|
||||
private void pushIndent() {
|
||||
indent += 1;
|
||||
}
|
||||
|
||||
private void popIndent() {
|
||||
indent -= 1;
|
||||
}
|
||||
}
|
||||
|
@@ -1,91 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.msgpack.*;
|
||||
|
||||
public abstract class ClassSchema extends Schema implements IArraySchema {
|
||||
protected String name;
|
||||
protected FieldSchema[] fields;
|
||||
protected List<String> imports;
|
||||
protected String namespace;
|
||||
protected String fqdn;
|
||||
|
||||
public ClassSchema(
|
||||
String name, String namespace,
|
||||
List<String> imports, List<FieldSchema> fields) {
|
||||
this.name = name;
|
||||
this.namespace = namespace;
|
||||
this.imports = imports; // FIXME clone?
|
||||
this.fields = new FieldSchema[fields.size()];
|
||||
System.arraycopy(fields.toArray(), 0, this.fields, 0, fields.size());
|
||||
if(namespace == null) {
|
||||
this.fqdn = name;
|
||||
} else {
|
||||
this.fqdn = namespace+"."+name;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
StringBuffer b = new StringBuffer();
|
||||
b.append("(class ");
|
||||
b.append(name);
|
||||
if(namespace != null) {
|
||||
b.append(" (package "+namespace+")");
|
||||
}
|
||||
for(FieldSchema f : fields) {
|
||||
b.append(" "+f.getExpression());
|
||||
}
|
||||
b.append(")");
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
public boolean equals(ClassSchema o) {
|
||||
return (namespace != null ? namespace.equals(o.getNamespace()) : o.getNamespace() == null) &&
|
||||
name.equals(o.name);
|
||||
}
|
||||
|
||||
public final FieldSchema[] getFields() {
|
||||
return fields;
|
||||
}
|
||||
|
||||
String getNamespace() {
|
||||
return namespace;
|
||||
}
|
||||
|
||||
List<String> getImports() {
|
||||
return imports;
|
||||
}
|
||||
|
||||
void setNamespace(String namespace) {
|
||||
this.namespace = namespace;
|
||||
}
|
||||
|
||||
void setImports(List<String> imports) {
|
||||
this.imports = imports; // FIXME clone?
|
||||
}
|
||||
}
|
||||
|
@@ -1,74 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class DoubleSchema extends Schema {
|
||||
public DoubleSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Double";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "double";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Double) {
|
||||
pk.packDouble((Double)obj);
|
||||
} else if(obj instanceof Float) {
|
||||
pk.packFloat((Float)obj);
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final double convertDouble(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Double) {
|
||||
return (Double)obj;
|
||||
} else if(obj instanceof Float) {
|
||||
return ((Float)obj).doubleValue();
|
||||
} else {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertDouble(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromFloat(float v) {
|
||||
return (double)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromDouble(double v) {
|
||||
return (double)v;
|
||||
}
|
||||
}
|
||||
|
@@ -1,43 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import org.msgpack.Schema;
|
||||
|
||||
public class FieldSchema {
|
||||
private String name;
|
||||
private Schema schema;
|
||||
|
||||
public FieldSchema(String name, Schema schema) {
|
||||
this.name = name;
|
||||
this.schema = schema;
|
||||
}
|
||||
|
||||
public final String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public final Schema getSchema() {
|
||||
return schema;
|
||||
}
|
||||
|
||||
public String getExpression() {
|
||||
return "(field "+name+" "+schema.getExpression()+")";
|
||||
}
|
||||
}
|
||||
|
@@ -1,74 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class FloatSchema extends Schema {
|
||||
public FloatSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Float";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "float";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Double) {
|
||||
pk.packDouble((Double)obj);
|
||||
} else if(obj instanceof Float) {
|
||||
pk.packFloat((Float)obj);
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final float convertFloat(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Double) {
|
||||
return ((Double)obj).floatValue();
|
||||
} else if(obj instanceof Float) {
|
||||
return (Float)obj;
|
||||
} else {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertFloat(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromFloat(float v) {
|
||||
return (float)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromDouble(double v) {
|
||||
return (float)v;
|
||||
}
|
||||
}
|
||||
|
@@ -1,87 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class GenericClassSchema extends ClassSchema {
|
||||
public GenericClassSchema(
|
||||
String name, String namespace,
|
||||
List<String> imports, List<FieldSchema> fields) {
|
||||
super(name, namespace, imports, fields);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Map) {
|
||||
Map d = (Map)obj;
|
||||
pk.packArray(fields.length);
|
||||
for(int i=0; i < fields.length; ++i) {
|
||||
FieldSchema f = fields[i];
|
||||
f.getSchema().pack(pk, d.get(f.getName()));
|
||||
}
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Collection) {
|
||||
// FIXME optimize
|
||||
return createFromArray( ((Collection)obj).toArray() );
|
||||
} else if(obj instanceof Map) {
|
||||
HashMap<String,Object> m = new HashMap<String,Object>(fields.length);
|
||||
Map d = (Map)obj;
|
||||
for(int i=0; i < fields.length; ++i) {
|
||||
FieldSchema f = fields[i];
|
||||
String fieldName = f.getName();
|
||||
m.put(fieldName, f.getSchema().convert(d.get(fieldName)));
|
||||
}
|
||||
return m;
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public Schema getElementSchema(int index) {
|
||||
// FIXME check index < fields.length
|
||||
return fields[index].getSchema();
|
||||
}
|
||||
|
||||
public Object createFromArray(Object[] obj) {
|
||||
HashMap<String,Object> m = new HashMap<String,Object>(fields.length);
|
||||
int i=0;
|
||||
for(; i < obj.length; ++i) {
|
||||
m.put(fields[i].getName(), obj[i]);
|
||||
}
|
||||
for(; i < fields.length; ++i) {
|
||||
m.put(fields[i].getName(), null);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
@@ -1,129 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.HashMap;
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class GenericSchema extends Schema implements IArraySchema, IMapSchema {
|
||||
public GenericSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Object";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "object";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
pk.pack(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return obj;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Schema getElementSchema(int index) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Schema getKeySchema() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Schema getValueSchema() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromNil() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromBoolean(boolean v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromByte(byte v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromShort(short v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromInt(int v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromLong(long v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromFloat(float v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromDouble(double v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromRaw(byte[] b, int offset, int length) {
|
||||
byte[] bytes = new byte[length];
|
||||
System.arraycopy(b, offset, bytes, 0, length);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromArray(Object[] obj) {
|
||||
return Arrays.asList(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Object createFromMap(Object[] obj) {
|
||||
HashMap m = new HashMap(obj.length / 2);
|
||||
int i = 0;
|
||||
while(i < obj.length) {
|
||||
Object k = obj[i++];
|
||||
Object v = obj[i++];
|
||||
m.put(k, v);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
@@ -1,26 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import org.msgpack.Schema;
|
||||
|
||||
public interface IArraySchema {
|
||||
public Schema getElementSchema(int index);
|
||||
public Object createFromArray(Object[] obj);
|
||||
}
|
||||
|
@@ -1,27 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import org.msgpack.Schema;
|
||||
|
||||
public interface IMapSchema {
|
||||
public Schema getKeySchema();
|
||||
public Schema getValueSchema();
|
||||
public Object createFromMap(Object[] obj);
|
||||
}
|
||||
|
@@ -1,96 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class IntSchema extends Schema {
|
||||
public IntSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Integer";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "int";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Number) {
|
||||
int value = ((Number)obj).intValue();
|
||||
if(value >= Short.MAX_VALUE) {
|
||||
long lvalue = ((Number)obj).longValue();
|
||||
if(lvalue > Integer.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
pk.packInt(value);
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final int convertInt(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Number) {
|
||||
int value = ((Number)obj).intValue();
|
||||
if(value >= Integer.MAX_VALUE) {
|
||||
long lvalue = ((Number)obj).longValue();
|
||||
if(lvalue > Integer.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertInt(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromByte(byte v) {
|
||||
return (int)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromShort(short v) {
|
||||
return (int)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromInt(int v) {
|
||||
return (int)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromLong(long v) {
|
||||
if(v > Integer.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (int)v;
|
||||
}
|
||||
}
|
||||
|
@@ -1,111 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.RandomAccess;
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class ListSchema extends Schema implements IArraySchema {
|
||||
private Schema elementSchema;
|
||||
|
||||
public ListSchema(Schema elementSchema) {
|
||||
this.elementSchema = elementSchema;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "List<"+elementSchema.getClassName()+">";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "(array "+elementSchema.getExpression()+")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof List) {
|
||||
List<Object> d = (List<Object>)obj;
|
||||
pk.packArray(d.size());
|
||||
if(obj instanceof RandomAccess) {
|
||||
for(int i=0; i < d.size(); ++i) {
|
||||
elementSchema.pack(pk, d.get(i));
|
||||
}
|
||||
} else {
|
||||
for(Object e : d) {
|
||||
elementSchema.pack(pk, e);
|
||||
}
|
||||
}
|
||||
} else if(obj instanceof Set) {
|
||||
Set<Object> d = (Set<Object>)obj;
|
||||
pk.packArray(d.size());
|
||||
for(Object e : d) {
|
||||
elementSchema.pack(pk, e);
|
||||
}
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> List<T> convertList(Object obj,
|
||||
Schema elementSchema, List<T> dest) throws MessageTypeException {
|
||||
if(!(obj instanceof List)) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
List<Object> d = (List<Object>)obj;
|
||||
if(dest == null) {
|
||||
dest = new ArrayList<T>(d.size());
|
||||
}
|
||||
if(obj instanceof RandomAccess) {
|
||||
for(int i=0; i < d.size(); ++i) {
|
||||
dest.add( (T)elementSchema.convert(d.get(i)) );
|
||||
}
|
||||
} else {
|
||||
for(Object e : d) {
|
||||
dest.add( (T)elementSchema.convert(e) );
|
||||
}
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertList(obj, elementSchema, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Schema getElementSchema(int index) {
|
||||
return elementSchema;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromArray(Object[] obj) {
|
||||
return Arrays.asList(obj);
|
||||
}
|
||||
}
|
||||
|
@@ -1,80 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class LongSchema extends Schema {
|
||||
public LongSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Long";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "long";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Number) {
|
||||
long value = ((Number)obj).longValue();
|
||||
pk.packLong(value);
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final long convertLong(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Number) {
|
||||
return ((Number)obj).longValue();
|
||||
}
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertLong(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromByte(byte v) {
|
||||
return (long)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromShort(short v) {
|
||||
return (long)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromInt(int v) {
|
||||
return (long)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromLong(long v) {
|
||||
return (long)v;
|
||||
}
|
||||
}
|
||||
|
@@ -1,106 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class MapSchema extends Schema implements IMapSchema {
|
||||
private Schema keySchema;
|
||||
private Schema valueSchema;
|
||||
|
||||
public MapSchema(Schema keySchema, Schema valueSchema) {
|
||||
this.keySchema = keySchema;
|
||||
this.valueSchema = valueSchema;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Map<"+keySchema.getClassName()+", "+valueSchema.getClassName()+">";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "(map "+keySchema.getExpression()+" "+valueSchema.getExpression()+")";
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Map) {
|
||||
Map<Object,Object> d = (Map<Object,Object>)obj;
|
||||
pk.packMap(d.size());
|
||||
for(Map.Entry<Object,Object> e : d.entrySet()) {
|
||||
keySchema.pack(pk, e.getKey());
|
||||
valueSchema.pack(pk, e.getValue());
|
||||
}
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <K,V> Map<K,V> convertMap(Object obj,
|
||||
Schema keySchema, Schema valueSchema, Map<K,V> dest) throws MessageTypeException {
|
||||
if(!(obj instanceof Map)) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
Map<Object,Object> d = (Map<Object,Object>)obj;
|
||||
if(dest == null) {
|
||||
dest = new HashMap<K,V>(d.size());
|
||||
}
|
||||
for(Map.Entry<Object,Object> e : d.entrySet()) {
|
||||
dest.put((K)keySchema.convert(e.getKey()),
|
||||
(V)valueSchema.convert(e.getValue()));
|
||||
}
|
||||
return (Map<K,V>)d;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertMap(obj, keySchema, valueSchema, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Schema getKeySchema() {
|
||||
return keySchema;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Schema getValueSchema() {
|
||||
return valueSchema;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Object createFromMap(Object[] obj) {
|
||||
HashMap dest = new HashMap(obj.length / 2);
|
||||
int i = 0;
|
||||
while(i < obj.length) {
|
||||
Object k = obj[i++];
|
||||
Object v = obj[i++];
|
||||
dest.put(k, v);
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
}
|
||||
|
@@ -1,64 +0,0 @@
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.lang.reflect.*;
|
||||
import org.msgpack.*;
|
||||
|
||||
// FIXME
|
||||
public abstract class ReflectionClassSchema extends ClassSchema {
|
||||
private Constructor constructorCache;
|
||||
|
||||
public ReflectionClassSchema(String name, List<FieldSchema> fields, String namespace, List<String> imports) {
|
||||
super(name, namespace, imports, fields);
|
||||
}
|
||||
|
||||
/*
|
||||
Schema getElementSchema(int index)
|
||||
{
|
||||
// FIXME check index < fields.length
|
||||
fields[index].getSchema();
|
||||
}
|
||||
|
||||
Object createFromArray(Object[] obj)
|
||||
{
|
||||
Object o = newInstance();
|
||||
((MessageConvertable)o).messageConvert(obj);
|
||||
return o;
|
||||
}
|
||||
|
||||
Object newInstance()
|
||||
{
|
||||
if(constructorCache == null) {
|
||||
cacheConstructor();
|
||||
}
|
||||
try {
|
||||
return constructorCache.newInstance((Object[])null);
|
||||
} catch (InvocationTargetException e) {
|
||||
throw new RuntimeException("can't instantiate "+fqdn+": "+e.getMessage());
|
||||
} catch (InstantiationException e) {
|
||||
throw new RuntimeException("can't instantiate "+fqdn+": "+e.getMessage());
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException("can't instantiate "+fqdn+": "+e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void cacheConstructor()
|
||||
{
|
||||
try {
|
||||
Class c = Class.forName(fqdn);
|
||||
int index = 0;
|
||||
for(SpecificFieldSchema f : fields) {
|
||||
f.cacheField(c, index++);
|
||||
}
|
||||
constructorCache = c.getDeclaredConstructor((Class[])null);
|
||||
constructorCache.setAccessible(true);
|
||||
} catch(ClassNotFoundException e) {
|
||||
throw new RuntimeException("class not found: "+fqdn);
|
||||
} catch (NoSuchMethodException e) {
|
||||
throw new RuntimeException("class not found: "+fqdn+": "+e.getMessage());
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
@@ -1,264 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.Matcher;
|
||||
import org.msgpack.*;
|
||||
|
||||
// FIXME exception class
|
||||
|
||||
public class SSchemaParser {
|
||||
public static Schema parse(String source) {
|
||||
return new SSchemaParser(false).run(source);
|
||||
}
|
||||
|
||||
public static Schema load(String source) {
|
||||
return new SSchemaParser(true).run(source);
|
||||
}
|
||||
|
||||
private static abstract class SExp {
|
||||
boolean isAtom() { return false; }
|
||||
public String getAtom() { return null; }
|
||||
|
||||
boolean isTuple() { return false; }
|
||||
public SExp getTuple(int i) { return null; }
|
||||
public int size() { return 0; }
|
||||
public boolean empty() { return size() == 0; }
|
||||
Iterator<SExp> iterator(int offset) { return null; }
|
||||
}
|
||||
|
||||
private static class SAtom extends SExp {
|
||||
private String atom;
|
||||
|
||||
SAtom(String atom) { this.atom = atom; }
|
||||
|
||||
boolean isAtom() { return true; }
|
||||
public String getAtom() { return atom; }
|
||||
|
||||
public String toString() { return atom; }
|
||||
}
|
||||
|
||||
private static class STuple extends SExp {
|
||||
private List<SExp> tuple;
|
||||
|
||||
STuple() { this.tuple = new ArrayList<SExp>(); }
|
||||
|
||||
public void add(SExp e) { tuple.add(e); }
|
||||
|
||||
boolean isTuple() { return true; }
|
||||
public SExp getTuple(int i) { return tuple.get(i); }
|
||||
public int size() { return tuple.size(); }
|
||||
|
||||
Iterator<SExp> iterator(int skip) {
|
||||
Iterator<SExp> i = tuple.iterator();
|
||||
for(int s=0; s < skip; ++s) { i.next(); }
|
||||
return i;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
if(tuple.isEmpty()) { return "()"; }
|
||||
Iterator<SExp> i = tuple.iterator();
|
||||
StringBuffer o = new StringBuffer();
|
||||
o.append("(").append(i.next());
|
||||
while(i.hasNext()) { o.append(" ").append(i.next()); }
|
||||
o.append(")");
|
||||
return o.toString();
|
||||
}
|
||||
}
|
||||
|
||||
boolean specificClass;
|
||||
|
||||
private SSchemaParser(boolean specificClass) {
|
||||
this.specificClass = specificClass;
|
||||
}
|
||||
|
||||
private static Pattern pattern = Pattern.compile(
|
||||
"(?:\\s+)|([\\(\\)]|[\\d\\w\\.]+)");
|
||||
|
||||
private Schema run(String source) {
|
||||
Matcher m = pattern.matcher(source);
|
||||
|
||||
Stack<STuple> stack = new Stack<STuple>();
|
||||
String token;
|
||||
|
||||
while(true) {
|
||||
while(true) {
|
||||
if(!m.find()) { throw new RuntimeException("unexpected end of file"); }
|
||||
token = m.group(1);
|
||||
if(token != null) { break; }
|
||||
}
|
||||
|
||||
if(token.equals("(")) {
|
||||
stack.push(new STuple());
|
||||
} else if(token.equals(")")) {
|
||||
STuple top = stack.pop();
|
||||
if(stack.empty()) {
|
||||
stack.push(top);
|
||||
break;
|
||||
}
|
||||
stack.peek().add(top);
|
||||
} else {
|
||||
if(stack.empty()) {
|
||||
throw new RuntimeException("unexpected token '"+token+"'");
|
||||
}
|
||||
stack.peek().add(new SAtom(token));
|
||||
}
|
||||
}
|
||||
|
||||
while(true) {
|
||||
if(!m.find()) { break; }
|
||||
token = m.group(1);
|
||||
if(token != null) { throw new RuntimeException("unexpected token '"+token+"'"); }
|
||||
}
|
||||
|
||||
return readType( stack.pop() );
|
||||
}
|
||||
|
||||
private Schema readType(SExp exp) {
|
||||
if(exp.isAtom()) {
|
||||
String type = exp.getAtom();
|
||||
if(type.equals("string")) {
|
||||
return new StringSchema();
|
||||
} else if(type.equals("raw")) {
|
||||
return new ByteArraySchema();
|
||||
} else if(type.equals("byte")) {
|
||||
return new ByteSchema();
|
||||
} else if(type.equals("short")) {
|
||||
return new ShortSchema();
|
||||
} else if(type.equals("int")) {
|
||||
return new IntSchema();
|
||||
} else if(type.equals("long")) {
|
||||
return new LongSchema();
|
||||
} else if(type.equals("float")) {
|
||||
return new FloatSchema();
|
||||
} else if(type.equals("double")) {
|
||||
return new DoubleSchema();
|
||||
} else if(type.equals("object")) {
|
||||
return new GenericSchema();
|
||||
} else {
|
||||
throw new RuntimeException("byte, short, int, long, float, double, raw, string or object is expected but got '"+type+"': "+exp);
|
||||
}
|
||||
} else {
|
||||
String type = exp.getTuple(0).getAtom();
|
||||
if(type.equals("class")) {
|
||||
return parseClass(exp);
|
||||
} else if(type.equals("array")) {
|
||||
return parseList(exp);
|
||||
} else if(type.equals("set")) {
|
||||
return parseSet(exp);
|
||||
} else if(type.equals("map")) {
|
||||
return parseMap(exp);
|
||||
} else {
|
||||
throw new RuntimeException("class, list, set or map is expected but got '"+type+"': "+exp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ClassSchema parseClass(SExp exp) {
|
||||
if(exp.size() < 3 || !exp.getTuple(1).isAtom()) {
|
||||
throw new RuntimeException("class is (class NAME CLASS_BODY): "+exp);
|
||||
}
|
||||
|
||||
String namespace = null;
|
||||
List<String> imports = new ArrayList<String>();
|
||||
String name = exp.getTuple(1).getAtom();
|
||||
List<FieldSchema> fields = new ArrayList<FieldSchema>();
|
||||
|
||||
for(Iterator<SExp> i=exp.iterator(2); i.hasNext();) {
|
||||
SExp subexp = i.next();
|
||||
if(!subexp.isTuple() || subexp.empty() || !subexp.getTuple(0).isAtom()) {
|
||||
throw new RuntimeException("field, package or import is expected: "+subexp);
|
||||
}
|
||||
String type = subexp.getTuple(0).getAtom();
|
||||
if(type.equals("field")) {
|
||||
fields.add( parseField(subexp) );
|
||||
} else if(type.equals("package")) {
|
||||
if(namespace != null) {
|
||||
throw new RuntimeException("duplicated package definition: "+subexp);
|
||||
}
|
||||
namespace = parseNamespace(subexp);
|
||||
} else if(type.equals("import")) {
|
||||
imports.add( parseImport(subexp) );
|
||||
} else {
|
||||
throw new RuntimeException("field, package or import is expected but got '"+type+"': "+subexp);
|
||||
}
|
||||
}
|
||||
|
||||
if(specificClass) {
|
||||
return new SpecificClassSchema(name, namespace, imports, fields);
|
||||
} else {
|
||||
return new GenericClassSchema(name, namespace, imports, fields);
|
||||
}
|
||||
}
|
||||
|
||||
private ListSchema parseList(SExp exp) {
|
||||
if(exp.size() != 2) {
|
||||
throw new RuntimeException("list is (list ELEMENT_TYPE): "+exp);
|
||||
}
|
||||
Schema elementType = readType(exp.getTuple(1));
|
||||
return new ListSchema(elementType);
|
||||
}
|
||||
|
||||
private SetSchema parseSet(SExp exp) {
|
||||
if(exp.size() != 2) {
|
||||
throw new RuntimeException("list is (list ELEMENT_TYPE): "+exp);
|
||||
}
|
||||
Schema elementType = readType(exp.getTuple(1));
|
||||
return new SetSchema(elementType);
|
||||
}
|
||||
|
||||
private MapSchema parseMap(SExp exp) {
|
||||
if(exp.size() != 3 || !exp.getTuple(1).isAtom()) {
|
||||
throw new RuntimeException("map is (map KEY_TYPE VALUE_TYPE): "+exp);
|
||||
}
|
||||
Schema keyType = readType(exp.getTuple(1));
|
||||
Schema valueType = readType(exp.getTuple(2));
|
||||
return new MapSchema(keyType, valueType);
|
||||
}
|
||||
|
||||
private String parseNamespace(SExp exp) {
|
||||
if(exp.size() != 2 || !exp.getTuple(1).isAtom()) {
|
||||
throw new RuntimeException("package is (package NAME): "+exp);
|
||||
}
|
||||
String name = exp.getTuple(1).getAtom();
|
||||
return name;
|
||||
}
|
||||
|
||||
private String parseImport(SExp exp) {
|
||||
if(exp.size() != 2 || !exp.getTuple(1).isAtom()) {
|
||||
throw new RuntimeException("import is (import NAME): "+exp);
|
||||
}
|
||||
String name = exp.getTuple(1).getAtom();
|
||||
return name;
|
||||
}
|
||||
|
||||
private FieldSchema parseField(SExp exp) {
|
||||
if(exp.size() != 3 || !exp.getTuple(1).isAtom()) {
|
||||
throw new RuntimeException("field is (field NAME TYPE): "+exp);
|
||||
}
|
||||
String name = exp.getTuple(1).getAtom();
|
||||
Schema type = readType(exp.getTuple(2));
|
||||
return new FieldSchema(name, type);
|
||||
}
|
||||
}
|
||||
|
@@ -1,115 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.RandomAccess;
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class SetSchema extends Schema implements IArraySchema {
|
||||
private Schema elementSchema;
|
||||
|
||||
public SetSchema(Schema elementSchema) {
|
||||
this.elementSchema = elementSchema;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Set<"+elementSchema.getClassName()+">";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "(set "+elementSchema.getExpression()+")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof List) {
|
||||
List<Object> d = (List<Object>)obj;
|
||||
pk.packArray(d.size());
|
||||
if(obj instanceof RandomAccess) {
|
||||
for(int i=0; i < d.size(); ++i) {
|
||||
elementSchema.pack(pk, d.get(i));
|
||||
}
|
||||
} else {
|
||||
for(Object e : d) {
|
||||
elementSchema.pack(pk, e);
|
||||
}
|
||||
}
|
||||
} else if(obj instanceof Set) {
|
||||
Set<Object> d = (Set<Object>)obj;
|
||||
pk.packArray(d.size());
|
||||
for(Object e : d) {
|
||||
elementSchema.pack(pk, e);
|
||||
}
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static final <T> Set<T> convertSet(Object obj,
|
||||
Schema elementSchema, Set<T> dest) throws MessageTypeException {
|
||||
if(!(obj instanceof List)) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
List<Object> d = (List<Object>)obj;
|
||||
if(dest == null) {
|
||||
dest = new HashSet<T>(d.size());
|
||||
}
|
||||
if(obj instanceof RandomAccess) {
|
||||
for(int i=0; i < d.size(); ++i) {
|
||||
dest.add( (T)elementSchema.convert(d.get(i)) );
|
||||
}
|
||||
} else {
|
||||
for(Object e : d) {
|
||||
dest.add( (T)elementSchema.convert(e) );
|
||||
}
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertSet(obj, elementSchema, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Schema getElementSchema(int index) {
|
||||
return elementSchema;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromArray(Object[] obj) {
|
||||
Set m = new HashSet(obj.length);
|
||||
for(int i=0; i < obj.length; i++) {
|
||||
m.add(obj[i]);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
@@ -1,93 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class ShortSchema extends Schema {
|
||||
public ShortSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "Short";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "short";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof Number) {
|
||||
int value = ((Number)obj).intValue();
|
||||
if(value > Short.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
pk.packShort((short)value);
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final short convertShort(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Number) {
|
||||
int value = ((Number)obj).intValue();
|
||||
if(value > Short.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (short)value;
|
||||
}
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertShort(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromByte(byte v) {
|
||||
return (short)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromShort(short v) {
|
||||
return (short)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromInt(int v) {
|
||||
if(v > Short.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (short)v;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromLong(long v) {
|
||||
if(v > Short.MAX_VALUE) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
return (short)v;
|
||||
}
|
||||
}
|
||||
|
@@ -1,122 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.lang.reflect.*;
|
||||
import java.io.IOException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class SpecificClassSchema extends ClassSchema {
|
||||
private Class classCache;
|
||||
private Method factoryCache;
|
||||
private Constructor constructorCache;
|
||||
|
||||
public SpecificClassSchema(
|
||||
String name, String namespace,
|
||||
List<String> imports, List<FieldSchema> fields) {
|
||||
super(name, namespace, imports, fields);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj == null) {
|
||||
pk.packNil();
|
||||
return;
|
||||
}
|
||||
if(classCache == null) {
|
||||
cacheFactory();
|
||||
}
|
||||
if(classCache.isInstance(obj)) {
|
||||
((MessagePackable)obj).messagePack(pk);
|
||||
} else {
|
||||
// FIXME Map<String,Object>
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof Collection) {
|
||||
if(constructorCache == null) {
|
||||
cacheConstructor();
|
||||
}
|
||||
try {
|
||||
MessageConvertable o = (MessageConvertable)constructorCache.newInstance((Object[])null);
|
||||
o.messageConvert(obj);
|
||||
return o;
|
||||
} catch (InvocationTargetException e) {
|
||||
throw new RuntimeException("can't instantiate "+fqdn+": "+e.getMessage());
|
||||
} catch (InstantiationException e) {
|
||||
throw new RuntimeException("can't instantiate "+fqdn+": "+e.getMessage());
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException("can't instantiate "+fqdn+": "+e.getMessage());
|
||||
}
|
||||
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public Schema getElementSchema(int index) {
|
||||
// FIXME check index < fields.length
|
||||
return fields[index].getSchema();
|
||||
}
|
||||
|
||||
public Object createFromArray(Object[] obj) {
|
||||
if(factoryCache == null) {
|
||||
cacheFactory();
|
||||
}
|
||||
try {
|
||||
return factoryCache.invoke(null, new Object[]{obj});
|
||||
} catch (InvocationTargetException e) {
|
||||
throw new RuntimeException("can't instantiate "+fqdn+": "+e.getCause());
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new RuntimeException("can't instantiate "+fqdn+": "+e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void cacheFactory() {
|
||||
try {
|
||||
classCache = Class.forName(fqdn);
|
||||
factoryCache = classCache.getDeclaredMethod("createFromMessage", new Class[]{Object[].class});
|
||||
factoryCache.setAccessible(true);
|
||||
} catch(ClassNotFoundException e) {
|
||||
throw new RuntimeException("class not found: "+fqdn);
|
||||
} catch (NoSuchMethodException e) {
|
||||
throw new RuntimeException("class not found: "+fqdn+": "+e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void cacheConstructor() {
|
||||
try {
|
||||
classCache = Class.forName(fqdn);
|
||||
constructorCache = classCache.getDeclaredConstructor((Class[])null);
|
||||
constructorCache.setAccessible(true);
|
||||
} catch(ClassNotFoundException e) {
|
||||
throw new RuntimeException("class not found: "+fqdn);
|
||||
} catch (NoSuchMethodException e) {
|
||||
throw new RuntimeException("class not found: "+fqdn+": "+e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,102 +0,0 @@
|
||||
//
|
||||
// MessagePack for Java
|
||||
//
|
||||
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
package org.msgpack.schema;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import org.msgpack.*;
|
||||
|
||||
public class StringSchema extends Schema {
|
||||
public StringSchema() { }
|
||||
|
||||
@Override
|
||||
public String getClassName() {
|
||||
return "String";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExpression() {
|
||||
return "string";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pack(Packer pk, Object obj) throws IOException {
|
||||
if(obj instanceof byte[]) {
|
||||
byte[] b = (byte[])obj;
|
||||
pk.packRaw(b.length);
|
||||
pk.packRawBody(b);
|
||||
} else if(obj instanceof String) {
|
||||
try {
|
||||
byte[] b = ((String)obj).getBytes("UTF-8");
|
||||
pk.packRaw(b.length);
|
||||
pk.packRawBody(b);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
} else if(obj == null) {
|
||||
pk.packNil();
|
||||
} else {
|
||||
throw MessageTypeException.invalidConvert(obj, this);
|
||||
}
|
||||
}
|
||||
|
||||
public static final String convertString(Object obj) throws MessageTypeException {
|
||||
if(obj instanceof byte[]) {
|
||||
try {
|
||||
return new String((byte[])obj, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
} else if(obj instanceof String) {
|
||||
return (String)obj;
|
||||
} else if(obj instanceof ByteBuffer) {
|
||||
ByteBuffer d = (ByteBuffer)obj;
|
||||
try {
|
||||
if(d.hasArray()) {
|
||||
return new String(d.array(), d.position(), d.capacity(), "UTF-8");
|
||||
} else {
|
||||
byte[] v = new byte[d.capacity()];
|
||||
int pos = d.position();
|
||||
d.get(v);
|
||||
d.position(pos);
|
||||
return new String(v, "UTF-8");
|
||||
}
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
} else {
|
||||
throw new MessageTypeException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object convert(Object obj) throws MessageTypeException {
|
||||
return convertString(obj);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object createFromRaw(byte[] b, int offset, int length) {
|
||||
try {
|
||||
return new String(b, offset, length, "UTF-8");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,148 +0,0 @@
|
||||
package org.msgpack;
|
||||
|
||||
import org.msgpack.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class TestDirectConversion {
|
||||
@Test
|
||||
public void testInt() throws Exception {
|
||||
testInt(0);
|
||||
testInt(-1);
|
||||
testInt(1);
|
||||
testInt(Integer.MIN_VALUE);
|
||||
testInt(Integer.MAX_VALUE);
|
||||
Random rand = new Random();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
testInt(rand.nextInt());
|
||||
}
|
||||
public void testInt(int val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
|
||||
Unpacker upk = new Unpacker(in);
|
||||
assertEquals(val, upk.unpackInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFloat() throws Exception {
|
||||
testFloat((float)0.0);
|
||||
testFloat((float)-0.0);
|
||||
testFloat((float)1.0);
|
||||
testFloat((float)-1.0);
|
||||
testFloat((float)Float.MAX_VALUE);
|
||||
testFloat((float)Float.MIN_VALUE);
|
||||
testFloat((float)Float.NaN);
|
||||
testFloat((float)Float.NEGATIVE_INFINITY);
|
||||
testFloat((float)Float.POSITIVE_INFINITY);
|
||||
Random rand = new Random();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
testFloat(rand.nextFloat());
|
||||
}
|
||||
public void testFloat(float val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
|
||||
Unpacker upk = new Unpacker(in);
|
||||
float f = upk.unpackFloat();
|
||||
if(Float.isNaN(val)) {
|
||||
assertTrue(Float.isNaN(f));
|
||||
} else {
|
||||
assertEquals(val, f, 10e-10);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDouble() throws Exception {
|
||||
testDouble((double)0.0);
|
||||
testDouble((double)-0.0);
|
||||
testDouble((double)1.0);
|
||||
testDouble((double)-1.0);
|
||||
testDouble((double)Double.MAX_VALUE);
|
||||
testDouble((double)Double.MIN_VALUE);
|
||||
testDouble((double)Double.NaN);
|
||||
testDouble((double)Double.NEGATIVE_INFINITY);
|
||||
testDouble((double)Double.POSITIVE_INFINITY);
|
||||
Random rand = new Random();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
testDouble(rand.nextDouble());
|
||||
}
|
||||
public void testDouble(double val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
|
||||
Unpacker upk = new Unpacker(in);
|
||||
double f = upk.unpackDouble();
|
||||
if(Double.isNaN(val)) {
|
||||
assertTrue(Double.isNaN(f));
|
||||
} else {
|
||||
assertEquals(val, f, 10e-10);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNil() throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).packNil();
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
|
||||
Unpacker upk = new Unpacker(in);
|
||||
assertEquals(null, upk.unpackNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBoolean() throws Exception {
|
||||
testBoolean(false);
|
||||
testBoolean(true);
|
||||
}
|
||||
public void testBoolean(boolean val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
|
||||
Unpacker upk = new Unpacker(in);
|
||||
assertEquals(val, upk.unpackBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testString() throws Exception {
|
||||
testString("");
|
||||
testString("a");
|
||||
testString("ab");
|
||||
testString("abc");
|
||||
// small size string
|
||||
for (int i = 0; i < 100; i++) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int len = (int)Math.random() % 31 + 1;
|
||||
for (int j = 0; j < len; j++)
|
||||
sb.append('a' + ((int)Math.random()) & 26);
|
||||
testString(sb.toString());
|
||||
}
|
||||
// medium size string
|
||||
for (int i = 0; i < 100; i++) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int len = (int)Math.random() % 100 + (1 << 15);
|
||||
for (int j = 0; j < len; j++)
|
||||
sb.append('a' + ((int)Math.random()) & 26);
|
||||
testString(sb.toString());
|
||||
}
|
||||
// large size string
|
||||
for (int i = 0; i < 10; i++) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int len = (int)Math.random() % 100 + (1 << 31);
|
||||
for (int j = 0; j < len; j++)
|
||||
sb.append('a' + ((int)Math.random()) & 26);
|
||||
testString(sb.toString());
|
||||
}
|
||||
}
|
||||
public void testString(String val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
|
||||
Unpacker upk = new Unpacker(in);
|
||||
assertEquals(val, upk.unpackString());
|
||||
}
|
||||
|
||||
// FIXME container types
|
||||
};
|
@@ -1,247 +0,0 @@
|
||||
package org.msgpack;
|
||||
|
||||
import org.msgpack.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class TestPackUnpack {
|
||||
protected Object unpackOne(ByteArrayOutputStream out) {
|
||||
return unpackOne(out, null);
|
||||
}
|
||||
protected Object unpackOne(ByteArrayOutputStream out, Schema schema) {
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
|
||||
Unpacker upk = new Unpacker(in);
|
||||
if (schema != null)
|
||||
upk = upk.useSchema(schema);
|
||||
Iterator<Object> it = upk.iterator();
|
||||
assertEquals(true, it.hasNext());
|
||||
Object obj = it.next();
|
||||
assertEquals(false, it.hasNext());
|
||||
return obj;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInt() throws Exception {
|
||||
testInt(0);
|
||||
testInt(-1);
|
||||
testInt(1);
|
||||
testInt(Integer.MIN_VALUE);
|
||||
testInt(Integer.MAX_VALUE);
|
||||
Random rand = new Random();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
testInt(rand.nextInt());
|
||||
}
|
||||
public void testInt(int val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
Object obj = unpackOne(out);
|
||||
if (obj instanceof Byte)
|
||||
assertEquals(val, ((Byte)obj).intValue());
|
||||
else if (obj instanceof Integer)
|
||||
assertEquals(val, ((Integer)obj).intValue());
|
||||
else if (obj instanceof Short)
|
||||
assertEquals(val, ((Short)obj).intValue());
|
||||
else if (obj instanceof Long)
|
||||
assertEquals(val, ((Long)obj).intValue());
|
||||
else {
|
||||
System.out.println("Got unexpected class: " + obj.getClass());
|
||||
assertTrue(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFloat() throws Exception {
|
||||
testFloat((float)0.0);
|
||||
testFloat((float)-0.0);
|
||||
testFloat((float)1.0);
|
||||
testFloat((float)-1.0);
|
||||
testFloat((float)Float.MAX_VALUE);
|
||||
testFloat((float)Float.MIN_VALUE);
|
||||
testFloat((float)Float.NaN);
|
||||
testFloat((float)Float.NEGATIVE_INFINITY);
|
||||
testFloat((float)Float.POSITIVE_INFINITY);
|
||||
Random rand = new Random();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
testFloat(rand.nextFloat());
|
||||
}
|
||||
public void testFloat(float val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
Object obj = unpackOne(out);
|
||||
if (obj instanceof Float)
|
||||
assertEquals(val, ((Float)obj).floatValue(), 10e-10);
|
||||
else {
|
||||
System.out.println("Got unexpected class: " + obj.getClass());
|
||||
assertTrue(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDouble() throws Exception {
|
||||
testDouble((double)0.0);
|
||||
testDouble((double)-0.0);
|
||||
testDouble((double)1.0);
|
||||
testDouble((double)-1.0);
|
||||
testDouble((double)Double.MAX_VALUE);
|
||||
testDouble((double)Double.MIN_VALUE);
|
||||
testDouble((double)Double.NaN);
|
||||
testDouble((double)Double.NEGATIVE_INFINITY);
|
||||
testDouble((double)Double.POSITIVE_INFINITY);
|
||||
Random rand = new Random();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
testDouble(rand.nextDouble());
|
||||
}
|
||||
public void testDouble(double val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
Object obj = unpackOne(out);
|
||||
if (obj instanceof Double)
|
||||
assertEquals(val, ((Double)obj).doubleValue(), 10e-10);
|
||||
else {
|
||||
System.out.println("Got unexpected class: " + obj.getClass());
|
||||
assertTrue(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNil() throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).packNil();
|
||||
Object obj = unpackOne(out);
|
||||
assertEquals(null, obj);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBoolean() throws Exception {
|
||||
testBoolean(false);
|
||||
testBoolean(true);
|
||||
}
|
||||
public void testBoolean(boolean val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
Object obj = unpackOne(out);
|
||||
if (obj instanceof Boolean)
|
||||
assertEquals(val, ((Boolean)obj).booleanValue());
|
||||
else {
|
||||
System.out.println("Got unexpected class: " + obj.getClass());
|
||||
assertTrue(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testString() throws Exception {
|
||||
testString("");
|
||||
testString("a");
|
||||
testString("ab");
|
||||
testString("abc");
|
||||
// small size string
|
||||
for (int i = 0; i < 100; i++) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int len = (int)Math.random() % 31 + 1;
|
||||
for (int j = 0; j < len; j++)
|
||||
sb.append('a' + ((int)Math.random()) & 26);
|
||||
testString(sb.toString());
|
||||
}
|
||||
// medium size string
|
||||
for (int i = 0; i < 100; i++) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int len = (int)Math.random() % 100 + (1 << 15);
|
||||
for (int j = 0; j < len; j++)
|
||||
sb.append('a' + ((int)Math.random()) & 26);
|
||||
testString(sb.toString());
|
||||
}
|
||||
// large size string
|
||||
for (int i = 0; i < 10; i++) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int len = (int)Math.random() % 100 + (1 << 31);
|
||||
for (int j = 0; j < len; j++)
|
||||
sb.append('a' + ((int)Math.random()) & 26);
|
||||
testString(sb.toString());
|
||||
}
|
||||
}
|
||||
public void testString(String val) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
Object obj = unpackOne(out);
|
||||
if (obj instanceof byte[])
|
||||
assertEquals(val, new String((byte[])obj));
|
||||
else {
|
||||
System.out.println("obj=" + obj);
|
||||
System.out.println("Got unexpected class: " + obj.getClass());
|
||||
assertTrue(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testArray() throws Exception {
|
||||
List<Integer> emptyList = new ArrayList<Integer>();
|
||||
testArray(emptyList, Schema.parse("(array int)"));
|
||||
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
Schema schema = Schema.parse("(array int)");
|
||||
List<Integer> l = new ArrayList<Integer>();
|
||||
int len = (int)Math.random() % 1000 + 1;
|
||||
for (int j = 0; j < len; j++)
|
||||
l.add(j);
|
||||
testArray(l, schema);
|
||||
}
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
Schema schema = Schema.parse("(array string)");
|
||||
List<String> l = new ArrayList<String>();
|
||||
int len = (int)Math.random() % 1000 + 1;
|
||||
for (int j = 0; j < len; j++)
|
||||
l.add(Integer.toString(j));
|
||||
testArray(l, schema);
|
||||
}
|
||||
}
|
||||
public void testArray(List val, Schema schema) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
Object obj = unpackOne(out, schema);
|
||||
if (obj instanceof List)
|
||||
assertTrue(val.equals(obj));
|
||||
else {
|
||||
System.out.println("obj=" + obj);
|
||||
System.out.println("Got unexpected class: " + obj.getClass());
|
||||
assertTrue(false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMap() throws Exception {
|
||||
Map<Integer, Integer> emptyMap = new HashMap<Integer, Integer>();
|
||||
testMap(emptyMap, Schema.parse("(map int int)"));
|
||||
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
Schema schema = Schema.parse("(map int int)");
|
||||
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
|
||||
int len = (int)Math.random() % 1000 + 1;
|
||||
for (int j = 0; j < len; j++)
|
||||
m.put(j, j);
|
||||
testMap(m, schema);
|
||||
}
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
Schema schema = Schema.parse("(map string int)");
|
||||
Map<String, Integer> m = new HashMap<String, Integer>();
|
||||
int len = (int)Math.random() % 1000 + 1;
|
||||
for (int j = 0; j < len; j++)
|
||||
m.put(Integer.toString(j), j);
|
||||
testMap(m, schema);
|
||||
}
|
||||
}
|
||||
public void testMap(Map val, Schema schema) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
new Packer(out).pack(val);
|
||||
Object obj = unpackOne(out, schema);
|
||||
if (obj instanceof Map)
|
||||
assertTrue(val.equals(obj));
|
||||
else {
|
||||
System.out.println("obj=" + obj);
|
||||
System.out.println("Got unexpected class: " + obj.getClass());
|
||||
assertTrue(false);
|
||||
}
|
||||
}
|
||||
};
|
@@ -1,11 +0,0 @@
|
||||
package org.msgpack;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class TestSample {
|
||||
@Test
|
||||
public void testNull() throws Exception {
|
||||
assertEquals("aiueo", 0, 0);
|
||||
}
|
||||
};
|
@@ -1,38 +0,0 @@
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import org.msgpack.*;
|
||||
import org.msgpack.schema.*;
|
||||
|
||||
public class Generate {
|
||||
public static void main(String[] args) throws IOException
|
||||
{
|
||||
String source =
|
||||
"(class MediaContent"+
|
||||
" (package serializers.msgpack)"+
|
||||
" (field image (array (class Image"+
|
||||
" (field uri string)"+
|
||||
" (field title string)"+
|
||||
" (field width int)"+
|
||||
" (field height int)"+
|
||||
" (field size int))))"+
|
||||
" (field media (class Media"+
|
||||
" (field uri string)"+
|
||||
" (field title string)"+
|
||||
" (field width int)"+
|
||||
" (field height int)"+
|
||||
" (field format string)"+
|
||||
" (field duration long)"+
|
||||
" (field size long)"+
|
||||
" (field bitrate int)"+
|
||||
" (field person (array string))"+
|
||||
" (field player int)"+
|
||||
" (field copyright string)))"+
|
||||
" )";
|
||||
|
||||
Schema schema = Schema.parse(source);
|
||||
|
||||
Writer output = new OutputStreamWriter(System.out);
|
||||
ClassGenerator.write(schema, output);
|
||||
}
|
||||
}
|
||||
|
@@ -1,7 +0,0 @@
|
||||
#!/bin/sh
|
||||
svn checkout -r114 http://thrift-protobuf-compare.googlecode.com/svn/trunk/ thrift-protobuf-compare-base
|
||||
cp -rf thrift-protobuf-compare/tpc thrift-protobuf-compare-base
|
||||
cp ../target/msgpack*.jar thrift-protobuf-compare-base/tpc/lib/msgpack.jar
|
||||
cd thrift-protobuf-compare-base/tpc/
|
||||
ant compile
|
||||
./run-benchmark.sh
|
@@ -1,436 +0,0 @@
|
||||
package serializers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import serializers.msgpack.MessagePackDirectSerializer;
|
||||
import serializers.msgpack.MessagePackSpecificSerializer;
|
||||
import serializers.msgpack.MessagePackIndirectSerializer;
|
||||
import serializers.msgpack.MessagePackDynamicSerializer;
|
||||
import serializers.msgpack.MessagePackGenericSerializer;
|
||||
import serializers.avro.AvroGenericSerializer;
|
||||
import serializers.avro.specific.AvroSpecificSerializer;
|
||||
import serializers.kryo.KryoOptimizedSerializer;
|
||||
import serializers.kryo.KryoSerializer;
|
||||
|
||||
public class BenchmarkRunner
|
||||
{
|
||||
public final static int ITERATIONS = 2000;
|
||||
public final static int TRIALS = 20;
|
||||
|
||||
/**
|
||||
* Number of milliseconds to warm up for each operation type for each serializer. Let's
|
||||
* start with 3 seconds.
|
||||
*/
|
||||
final static long WARMUP_MSECS = 3000;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Set<ObjectSerializer> _serializers = new LinkedHashSet<ObjectSerializer>();
|
||||
|
||||
public static void main(String... args) throws Exception
|
||||
{
|
||||
BenchmarkRunner runner = new BenchmarkRunner();
|
||||
|
||||
// binary codecs first
|
||||
runner.addObjectSerializer(new MessagePackDirectSerializer());
|
||||
runner.addObjectSerializer(new MessagePackSpecificSerializer());
|
||||
runner.addObjectSerializer(new MessagePackIndirectSerializer());
|
||||
runner.addObjectSerializer(new MessagePackDynamicSerializer());
|
||||
runner.addObjectSerializer(new MessagePackGenericSerializer());
|
||||
runner.addObjectSerializer(new AvroGenericSerializer());
|
||||
runner.addObjectSerializer(new AvroSpecificSerializer());
|
||||
runner.addObjectSerializer(new ActiveMQProtobufSerializer());
|
||||
runner.addObjectSerializer(new ProtobufSerializer());
|
||||
runner.addObjectSerializer(new ThriftSerializer());
|
||||
runner.addObjectSerializer(new HessianSerializer());
|
||||
runner.addObjectSerializer(new KryoSerializer());
|
||||
runner.addObjectSerializer(new KryoOptimizedSerializer());
|
||||
|
||||
// None of the other serializers use compression, so we'll leave this out.
|
||||
// runner.addObjectSerializer(new KryoCompressedSerializer());
|
||||
|
||||
// then language default serializers
|
||||
runner.addObjectSerializer(new JavaSerializer());
|
||||
|
||||
runner.addObjectSerializer(new JavaExtSerializer());
|
||||
runner.addObjectSerializer(new ScalaSerializer());
|
||||
|
||||
// then Json
|
||||
runner.addObjectSerializer(new JsonSerializer());
|
||||
runner.addObjectSerializer(new JsonDataBindingSerializer());
|
||||
runner.addObjectSerializer(new JsonMarshallerSerializer());
|
||||
runner.addObjectSerializer(new ProtostuffJsonSerializer());
|
||||
runner.addObjectSerializer(new ProtostuffNumericJsonSerializer());
|
||||
// this is pretty slow; so slow that it's almost not worth keeping but:
|
||||
runner.addObjectSerializer(new GsonSerializer());
|
||||
|
||||
// then xml via stax, textual and binary
|
||||
runner.addObjectSerializer(new StaxSerializer("stax/woodstox",
|
||||
new com.ctc.wstx.stax.WstxInputFactory(),
|
||||
new com.ctc.wstx.stax.WstxOutputFactory()));
|
||||
runner.addObjectSerializer(new StaxSerializer("stax/aalto",
|
||||
new com.fasterxml.aalto.stax.InputFactoryImpl(),
|
||||
new com.fasterxml.aalto.stax.OutputFactoryImpl()));
|
||||
|
||||
runner.addObjectSerializer(new StaxSerializer("binaryxml/FI",
|
||||
new com.sun.xml.fastinfoset.stax.factory.StAXInputFactory(),
|
||||
new com.sun.xml.fastinfoset.stax.factory.StAXOutputFactory()));
|
||||
|
||||
// No point in running all 4 variants: let's just use fastest one:
|
||||
//runner.addObjectSerializer(new XStreamSerializer("xstream (xpp)", false, null, null));
|
||||
//runner.addObjectSerializer(new XStreamSerializer("xstream (xpp with conv)", true, null, null));
|
||||
//runner.addObjectSerializer(new XStreamSerializer("xstream (stax)", false, new com.ctc.wstx.stax.WstxInputFactory(), new com.ctc.wstx.stax.WstxOutputFactory()));
|
||||
runner.addObjectSerializer(new XStreamSerializer("xstream (stax with conv)",
|
||||
true,
|
||||
new com.ctc.wstx.stax.WstxInputFactory(),
|
||||
new com.ctc.wstx.stax.WstxOutputFactory()));
|
||||
runner.addObjectSerializer(new JavolutionXMLFormatSerializer());
|
||||
|
||||
runner.addObjectSerializer(new SbinarySerializer());
|
||||
// broken? Does not correctly round-trip:
|
||||
// runner.addObjectSerializer(new YamlSerializer());
|
||||
|
||||
System.out.println("Starting");
|
||||
|
||||
runner.start();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void addObjectSerializer(ObjectSerializer serializer)
|
||||
{
|
||||
_serializers.add(serializer);
|
||||
}
|
||||
|
||||
private <T> double createObjects(ObjectSerializer<T> serializer, int iterations) throws Exception
|
||||
{
|
||||
long start = System.nanoTime();
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
serializer.create();
|
||||
}
|
||||
return iterationTime(System.nanoTime() - start, iterations);
|
||||
}
|
||||
|
||||
private double iterationTime(long delta, int iterations)
|
||||
{
|
||||
return (double) delta / (double) (iterations);
|
||||
}
|
||||
|
||||
private <T> double serializeDifferentObjects(ObjectSerializer<T> serializer, int iterations) throws Exception
|
||||
{
|
||||
long start = System.nanoTime();
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
T obj = serializer.create();
|
||||
serializer.serialize(obj);
|
||||
}
|
||||
return iterationTime(System.nanoTime()-start, iterations);
|
||||
}
|
||||
|
||||
|
||||
private <T> double serializeSameObject(ObjectSerializer<T> serializer, int iterations) throws Exception
|
||||
{
|
||||
// let's reuse same instance to reduce overhead
|
||||
T obj = serializer.create();
|
||||
long delta = 0;
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
long start = System.nanoTime();
|
||||
serializer.serialize(obj);
|
||||
delta += System.nanoTime() - start;
|
||||
if (i % 1000 == 0)
|
||||
doGc();
|
||||
}
|
||||
return iterationTime(delta, iterations);
|
||||
}
|
||||
|
||||
private <T> double deserializeNoFieldAccess(ObjectSerializer<T> serializer, int iterations) throws Exception
|
||||
{
|
||||
byte[] array = serializer.serialize(serializer.create());
|
||||
long start = System.nanoTime();
|
||||
T result = null;
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
result = serializer.deserialize(array);
|
||||
}
|
||||
return iterationTime(System.nanoTime()-start, iterations);
|
||||
}
|
||||
|
||||
private <T> double deserializeAndCheckAllFields(CheckingObjectSerializer<T> serializer, int iterations) throws Exception
|
||||
{
|
||||
byte[] array = serializer.serialize(serializer.create());
|
||||
long delta = 0;
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
long start = System.nanoTime();
|
||||
T obj = serializer.deserialize(array);
|
||||
serializer.checkAllFields(obj);
|
||||
delta += System.nanoTime() - start;
|
||||
}
|
||||
return iterationTime(delta, iterations);
|
||||
}
|
||||
|
||||
private <T> double deserializeAndCheckMediaField(CheckingObjectSerializer<T> serializer, int iterations) throws Exception
|
||||
{
|
||||
byte[] array = serializer.serialize(serializer.create());
|
||||
long delta = 0;
|
||||
for (int i = 0; i < iterations; i++)
|
||||
{
|
||||
long start = System.nanoTime();
|
||||
T obj = serializer.deserialize(array);
|
||||
serializer.checkMediaField(obj);
|
||||
delta += System.nanoTime() - start;
|
||||
}
|
||||
return iterationTime(delta, iterations);
|
||||
}
|
||||
|
||||
/**
|
||||
* JVM is not required to honor GC requests, but adding bit of sleep around request is
|
||||
* most likely to give it a chance to do it.
|
||||
*/
|
||||
private void doGc()
|
||||
{
|
||||
try {
|
||||
Thread.sleep(50L);
|
||||
} catch (InterruptedException ie) { }
|
||||
System.gc();
|
||||
try { // longer sleep afterwards (not needed by GC, but may help with scheduling)
|
||||
Thread.sleep(200L);
|
||||
} catch (InterruptedException ie) { }
|
||||
}
|
||||
|
||||
enum measurements
|
||||
{
|
||||
timeCreate, timeSerializeDifferentObjects, timeSerializeSameObject, timeDeserializeNoFieldAccess, timeDeserializeAndCheckMediaField, timeDeserializeAndCheckAllFields, totalTime, length
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void start() throws Exception
|
||||
{
|
||||
System.out.printf("%-24s, %15s, %15s, %15s, %15s, %15s, %15s, %15s, %10s\n",
|
||||
" ",
|
||||
"Object create",
|
||||
"Serialize",
|
||||
"/w Same Object",
|
||||
"Deserialize",
|
||||
"and Check Media",
|
||||
"and Check All",
|
||||
"Total Time",
|
||||
"Serialized Size");
|
||||
EnumMap<measurements, Map<String, Double>> values = new EnumMap<measurements, Map<String, Double>>(measurements.class);
|
||||
for (measurements m : measurements.values())
|
||||
values.put(m, new HashMap<String, Double>());
|
||||
|
||||
for (ObjectSerializer serializer : _serializers)
|
||||
{
|
||||
/*
|
||||
* Should only warm things for the serializer that we test next: HotSpot JIT will
|
||||
* otherwise spent most of its time optimizing slower ones... Use
|
||||
* -XX:CompileThreshold=1 to hint the JIT to start immediately
|
||||
*
|
||||
* Actually: 1 is often not a good value -- threshold is the number
|
||||
* of samples needed to trigger inlining, and there's no point in
|
||||
* inlining everything. Default value is in thousands, so lowering
|
||||
* it to, say, 1000 is usually better.
|
||||
*/
|
||||
warmCreation(serializer);
|
||||
doGc();
|
||||
double timeCreate = Double.MAX_VALUE;
|
||||
// do more iteration for object creation because of its short time
|
||||
for (int i = 0; i < TRIALS; i++)
|
||||
timeCreate = Math.min(timeCreate, createObjects(serializer, ITERATIONS * 100));
|
||||
|
||||
warmSerialization(serializer);
|
||||
|
||||
// actually: let's verify serializer actually works now:
|
||||
checkCorrectness(serializer);
|
||||
|
||||
doGc();
|
||||
double timeSerializeDifferentObjects = Double.MAX_VALUE;
|
||||
for (int i = 0; i < TRIALS; i++)
|
||||
timeSerializeDifferentObjects = Math.min(timeSerializeDifferentObjects, serializeDifferentObjects(serializer, ITERATIONS));
|
||||
|
||||
doGc();
|
||||
double timeSerializeSameObject = Double.MAX_VALUE;
|
||||
for (int i = 0; i < TRIALS; i++)
|
||||
timeSerializeSameObject = Math.min(timeSerializeSameObject, serializeSameObject(serializer, ITERATIONS));
|
||||
|
||||
warmDeserialization(serializer);
|
||||
|
||||
doGc();
|
||||
double timeDeserializeNoFieldAccess = Double.MAX_VALUE;
|
||||
for (int i = 0; i < TRIALS; i++)
|
||||
timeDeserializeNoFieldAccess = Math.min(timeDeserializeNoFieldAccess, deserializeNoFieldAccess(serializer, ITERATIONS));
|
||||
|
||||
double timeDeserializeAndCheckAllFields = Double.NaN;
|
||||
double timeDeserializeAndCheckMediaField = Double.NaN;
|
||||
|
||||
double totalTime = timeSerializeDifferentObjects + timeDeserializeNoFieldAccess;
|
||||
|
||||
if( serializer instanceof CheckingObjectSerializer) {
|
||||
CheckingObjectSerializer checkingSerializer = (CheckingObjectSerializer)serializer;
|
||||
|
||||
timeDeserializeAndCheckMediaField = Double.MAX_VALUE;
|
||||
doGc();
|
||||
for (int i = 0; i < TRIALS; i++)
|
||||
timeDeserializeAndCheckMediaField = Math.min(timeDeserializeAndCheckMediaField, deserializeAndCheckMediaField(checkingSerializer, ITERATIONS));
|
||||
|
||||
timeDeserializeAndCheckAllFields = Double.MAX_VALUE;
|
||||
doGc();
|
||||
for (int i = 0; i < TRIALS; i++)
|
||||
timeDeserializeAndCheckAllFields = Math.min(timeDeserializeAndCheckAllFields, deserializeAndCheckAllFields(checkingSerializer, ITERATIONS));
|
||||
|
||||
totalTime = timeSerializeDifferentObjects + timeDeserializeAndCheckAllFields;
|
||||
}
|
||||
|
||||
|
||||
byte[] array = serializer.serialize(serializer.create());
|
||||
System.out.printf("%-24s, %15.5f, %15.5f, %15.5f, %15.5f, %15.5f, %15.5f, %15.5f, %10d\n",
|
||||
serializer.getName(),
|
||||
timeCreate,
|
||||
timeSerializeDifferentObjects,
|
||||
timeSerializeSameObject,
|
||||
timeDeserializeNoFieldAccess,
|
||||
timeDeserializeAndCheckMediaField,
|
||||
timeDeserializeAndCheckAllFields,
|
||||
totalTime,
|
||||
array.length);
|
||||
|
||||
addValue(values, serializer.getName(), timeCreate, timeSerializeDifferentObjects, timeSerializeSameObject,
|
||||
timeDeserializeNoFieldAccess, timeDeserializeAndCheckMediaField, timeDeserializeAndCheckAllFields, totalTime, array.length);
|
||||
}
|
||||
printImages(values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Method that tries to validate correctness of serializer, using
|
||||
* round-trip (construct, serializer, deserialize; compare objects
|
||||
* after steps 1 and 3).
|
||||
* Currently only done for StdMediaDeserializer...
|
||||
*/
|
||||
private void checkCorrectness(ObjectSerializer serializer)
|
||||
throws Exception
|
||||
{
|
||||
Object input = serializer.create();
|
||||
byte[] array = serializer.serialize(input);
|
||||
Object output = serializer.deserialize(array);
|
||||
|
||||
if (!input.equals(output)) {
|
||||
/* Should throw an exception; but for now (that we have a few
|
||||
* failures) let's just whine...
|
||||
*/
|
||||
String msg = "serializer '"+serializer.getName()+"' failed round-trip test (ser+deser produces Object different from input), input="+input+", output="+output;
|
||||
//throw new Exception("Error: "+msg);
|
||||
System.err.println("WARN: "+msg);
|
||||
}
|
||||
}
|
||||
|
||||
private void printImages(EnumMap<measurements, Map<String, Double>> values)
|
||||
{
|
||||
for (measurements m : values.keySet()) {
|
||||
Map<String, Double> map = values.get(m);
|
||||
ArrayList<Entry> list = new ArrayList(map.entrySet());
|
||||
Collections.sort(list, new Comparator<Entry>() {
|
||||
public int compare (Entry o1, Entry o2) {
|
||||
double diff = (Double)o1.getValue() - (Double)o2.getValue();
|
||||
return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
|
||||
}
|
||||
});
|
||||
LinkedHashMap<String, Double> sortedMap = new LinkedHashMap<String, Double>();
|
||||
for (Entry<String, Double> entry : list) {
|
||||
if( !entry.getValue().isNaN() ) {
|
||||
sortedMap.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
printImage(sortedMap, m);
|
||||
}
|
||||
}
|
||||
|
||||
private void printImage(Map<String, Double> map, measurements m)
|
||||
{
|
||||
StringBuilder valSb = new StringBuilder();
|
||||
String names = "";
|
||||
double max = Double.MIN_NORMAL;
|
||||
for (Entry<String, Double> entry : map.entrySet())
|
||||
{
|
||||
valSb.append(entry.getValue()).append(',');
|
||||
max = Math.max(max, entry.getValue());
|
||||
names = entry.getKey() + '|' + names;
|
||||
}
|
||||
|
||||
int height = Math.min(30+map.size()*20, 430);
|
||||
double scale = max * 1.1;
|
||||
System.out.println("<img src='http://chart.apis.google.com/chart?chtt="
|
||||
+ m.name()
|
||||
+ "&chf=c||lg||0||FFFFFF||1||76A4FB||0|bg||s||EFEFEF&chs=689x"+height+"&chd=t:"
|
||||
+ valSb.toString().substring(0, valSb.length() - 1)
|
||||
+ "&chds=0,"+ scale
|
||||
+ "&chxt=y"
|
||||
+ "&chxl=0:|" + names.substring(0, names.length() - 1)
|
||||
+ "&chm=N *f*,000000,0,-1,10&lklk&chdlp=t&chco=660000|660033|660066|660099|6600CC|6600FF|663300|663333|663366|663399|6633CC|6633FF|666600|666633|666666&cht=bhg&chbh=10&nonsense=aaa.png'/>");
|
||||
|
||||
}
|
||||
|
||||
private void addValue(EnumMap<measurements, Map<String, Double>> values,
|
||||
String name,
|
||||
double timeCreate,
|
||||
double timeSerializeDifferentObjects,
|
||||
double timeSerializeSameObject,
|
||||
double timeDeserializeNoFieldAccess,
|
||||
double timeDeserializeAndCheckMediaField,
|
||||
double timeDeserializeAndCheckAllFields,
|
||||
double totalTime,
|
||||
double length)
|
||||
{
|
||||
|
||||
values.get(measurements.timeCreate).put(name, timeCreate);
|
||||
values.get(measurements.timeSerializeDifferentObjects).put(name, timeSerializeDifferentObjects);
|
||||
values.get(measurements.timeSerializeSameObject).put(name, timeSerializeSameObject);
|
||||
values.get(measurements.timeDeserializeNoFieldAccess).put(name, timeDeserializeNoFieldAccess);
|
||||
values.get(measurements.timeDeserializeAndCheckMediaField).put(name, timeDeserializeAndCheckMediaField);
|
||||
values.get(measurements.timeDeserializeAndCheckAllFields).put(name, timeDeserializeAndCheckAllFields);
|
||||
values.get(measurements.totalTime).put(name, totalTime);
|
||||
values.get(measurements.length).put(name, length);
|
||||
}
|
||||
|
||||
private <T> void warmCreation(ObjectSerializer<T> serializer) throws Exception
|
||||
{
|
||||
// Instead of fixed counts, let's try to prime by running for N seconds
|
||||
long endTime = System.currentTimeMillis() + WARMUP_MSECS;
|
||||
do
|
||||
{
|
||||
createObjects(serializer, 1);
|
||||
}
|
||||
while (System.currentTimeMillis() < endTime);
|
||||
}
|
||||
|
||||
private <T> void warmSerialization(ObjectSerializer<T> serializer) throws Exception
|
||||
{
|
||||
// Instead of fixed counts, let's try to prime by running for N seconds
|
||||
long endTime = System.currentTimeMillis() + WARMUP_MSECS;
|
||||
do
|
||||
{
|
||||
serializeDifferentObjects(serializer, 1);
|
||||
}
|
||||
while (System.currentTimeMillis() < endTime);
|
||||
}
|
||||
|
||||
private <T> void warmDeserialization(ObjectSerializer<T> serializer) throws Exception
|
||||
{
|
||||
// Instead of fixed counts, let's try to prime by running for N seconds
|
||||
long endTime = System.currentTimeMillis() + WARMUP_MSECS;
|
||||
do
|
||||
{
|
||||
deserializeNoFieldAccess(serializer, 1);
|
||||
}
|
||||
while (System.currentTimeMillis() < endTime);
|
||||
}
|
||||
}
|
@@ -1,239 +0,0 @@
|
||||
package serializers.msgpack;
|
||||
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
import org.msgpack.*;
|
||||
import org.msgpack.schema.ClassSchema;
|
||||
import org.msgpack.schema.FieldSchema;
|
||||
|
||||
public final class MediaContent implements MessagePackable, MessageConvertable, MessageUnpackable
|
||||
{
|
||||
private static final ClassSchema _SCHEMA = (ClassSchema)Schema.load("(class MediaContent (package serializers.msgpack) (field image (array (class Image (package serializers.msgpack) (field uri string) (field title string) (field width int) (field height int) (field size int)))) (field media (class Media (package serializers.msgpack) (field uri string) (field title string) (field width int) (field height int) (field format string) (field duration long) (field size long) (field bitrate int) (field person (array string)) (field player int) (field copyright string))))");
|
||||
public static ClassSchema getSchema() { return _SCHEMA; }
|
||||
|
||||
public List<Image> image;
|
||||
public Media media;
|
||||
|
||||
public MediaContent() { }
|
||||
|
||||
@Override
|
||||
public void messagePack(Packer _pk) throws IOException
|
||||
{
|
||||
_pk.packArray(2);
|
||||
FieldSchema[] _fields = _SCHEMA.getFields();
|
||||
_fields[0].getSchema().pack(_pk, image);
|
||||
_fields[1].getSchema().pack(_pk, media);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public void messageConvert(Object obj) throws MessageTypeException
|
||||
{
|
||||
Object[] _source = ((List)obj).toArray();
|
||||
FieldSchema[] _fields = _SCHEMA.getFields();
|
||||
if(_source.length <= 0) { return; } this.image = (List<Image>)_fields[0].getSchema().convert(_source[0]);
|
||||
if(_source.length <= 1) { return; } this.media = (Media)_fields[1].getSchema().convert(_source[1]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void messageUnpack(Unpacker _pac) throws IOException, MessageTypeException {
|
||||
int _length = _pac.unpackArray();
|
||||
if(_length <= 0) { return; }
|
||||
int _image_length = _pac.unpackArray();
|
||||
this.image = new ArrayList(_image_length);
|
||||
for(int _i=0; _i < _image_length; ++_i) {
|
||||
Image _image_i = new Image();
|
||||
_image_i.messageUnpack(_pac);
|
||||
this.image.add(_image_i);
|
||||
}
|
||||
if(_length <= 1) { return; }
|
||||
this.media = new Media();
|
||||
this.media.messageUnpack(_pac);
|
||||
for(int _i=2; _i < _length; ++_i) { _pac.unpackObject(); }
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static MediaContent createFromMessage(Object[] _message)
|
||||
{
|
||||
MediaContent _self = new MediaContent();
|
||||
if(_message.length <= 0) { return _self; } _self.image = (List<Image>)_message[0];
|
||||
if(_message.length <= 1) { return _self; } _self.media = (Media)_message[1];
|
||||
return _self;
|
||||
}
|
||||
}
|
||||
|
||||
final class Image implements MessagePackable, MessageConvertable, MessageUnpackable
|
||||
{
|
||||
private static final ClassSchema _SCHEMA = (ClassSchema)Schema.load("(class Image (package serializers.msgpack) (field uri string) (field title string) (field width int) (field height int) (field size int))");
|
||||
public static ClassSchema getSchema() { return _SCHEMA; }
|
||||
|
||||
public String uri;
|
||||
public String title;
|
||||
public Integer width;
|
||||
public Integer height;
|
||||
public Integer size;
|
||||
|
||||
public Image() { }
|
||||
|
||||
@Override
|
||||
public void messagePack(Packer _pk) throws IOException
|
||||
{
|
||||
_pk.packArray(5);
|
||||
FieldSchema[] _fields = _SCHEMA.getFields();
|
||||
_fields[0].getSchema().pack(_pk, uri);
|
||||
_fields[1].getSchema().pack(_pk, title);
|
||||
_fields[2].getSchema().pack(_pk, width);
|
||||
_fields[3].getSchema().pack(_pk, height);
|
||||
_fields[4].getSchema().pack(_pk, size);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public void messageConvert(Object obj) throws MessageTypeException
|
||||
{
|
||||
Object[] _source = ((List)obj).toArray();
|
||||
FieldSchema[] _fields = _SCHEMA.getFields();
|
||||
if(_source.length <= 0) { return; } this.uri = (String)_fields[0].getSchema().convert(_source[0]);
|
||||
if(_source.length <= 1) { return; } this.title = (String)_fields[1].getSchema().convert(_source[1]);
|
||||
if(_source.length <= 2) { return; } this.width = (Integer)_fields[2].getSchema().convert(_source[2]);
|
||||
if(_source.length <= 3) { return; } this.height = (Integer)_fields[3].getSchema().convert(_source[3]);
|
||||
if(_source.length <= 4) { return; } this.size = (Integer)_fields[4].getSchema().convert(_source[4]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void messageUnpack(Unpacker _pac) throws IOException, MessageTypeException {
|
||||
int _length = _pac.unpackArray();
|
||||
if(_length <= 0) { return; }
|
||||
this.uri = _pac.unpackString();
|
||||
if(_length <= 1) { return; }
|
||||
this.title = _pac.unpackString();
|
||||
if(_length <= 2) { return; }
|
||||
this.width = _pac.unpackInt();
|
||||
if(_length <= 3) { return; }
|
||||
this.height = _pac.unpackInt();
|
||||
if(_length <= 4) { return; }
|
||||
this.size = _pac.unpackInt();
|
||||
for(int _i=5; _i < _length; ++_i) { _pac.unpackObject(); }
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Image createFromMessage(Object[] _message)
|
||||
{
|
||||
Image _self = new Image();
|
||||
if(_message.length <= 0) { return _self; } _self.uri = (String)_message[0];
|
||||
if(_message.length <= 1) { return _self; } _self.title = (String)_message[1];
|
||||
if(_message.length <= 2) { return _self; } _self.width = (Integer)_message[2];
|
||||
if(_message.length <= 3) { return _self; } _self.height = (Integer)_message[3];
|
||||
if(_message.length <= 4) { return _self; } _self.size = (Integer)_message[4];
|
||||
return _self;
|
||||
}
|
||||
}
|
||||
|
||||
final class Media implements MessagePackable, MessageConvertable, MessageUnpackable
|
||||
{
|
||||
private static final ClassSchema _SCHEMA = (ClassSchema)Schema.load("(class Media (package serializers.msgpack) (field uri string) (field title string) (field width int) (field height int) (field format string) (field duration long) (field size long) (field bitrate int) (field person (array string)) (field player int) (field copyright string))");
|
||||
public static ClassSchema getSchema() { return _SCHEMA; }
|
||||
|
||||
public String uri;
|
||||
public String title;
|
||||
public Integer width;
|
||||
public Integer height;
|
||||
public String format;
|
||||
public Long duration;
|
||||
public Long size;
|
||||
public Integer bitrate;
|
||||
public List<String> person;
|
||||
public Integer player;
|
||||
public String copyright;
|
||||
|
||||
public Media() { }
|
||||
|
||||
@Override
|
||||
public void messagePack(Packer _pk) throws IOException
|
||||
{
|
||||
_pk.packArray(11);
|
||||
FieldSchema[] _fields = _SCHEMA.getFields();
|
||||
_fields[0].getSchema().pack(_pk, uri);
|
||||
_fields[1].getSchema().pack(_pk, title);
|
||||
_fields[2].getSchema().pack(_pk, width);
|
||||
_fields[3].getSchema().pack(_pk, height);
|
||||
_fields[4].getSchema().pack(_pk, format);
|
||||
_fields[5].getSchema().pack(_pk, duration);
|
||||
_fields[6].getSchema().pack(_pk, size);
|
||||
_fields[7].getSchema().pack(_pk, bitrate);
|
||||
_fields[8].getSchema().pack(_pk, person);
|
||||
_fields[9].getSchema().pack(_pk, player);
|
||||
_fields[10].getSchema().pack(_pk, copyright);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public void messageConvert(Object obj) throws MessageTypeException
|
||||
{
|
||||
Object[] _source = ((List)obj).toArray();
|
||||
FieldSchema[] _fields = _SCHEMA.getFields();
|
||||
if(_source.length <= 0) { return; } this.uri = (String)_fields[0].getSchema().convert(_source[0]);
|
||||
if(_source.length <= 1) { return; } this.title = (String)_fields[1].getSchema().convert(_source[1]);
|
||||
if(_source.length <= 2) { return; } this.width = (Integer)_fields[2].getSchema().convert(_source[2]);
|
||||
if(_source.length <= 3) { return; } this.height = (Integer)_fields[3].getSchema().convert(_source[3]);
|
||||
if(_source.length <= 4) { return; } this.format = (String)_fields[4].getSchema().convert(_source[4]);
|
||||
if(_source.length <= 5) { return; } this.duration = (Long)_fields[5].getSchema().convert(_source[5]);
|
||||
if(_source.length <= 6) { return; } this.size = (Long)_fields[6].getSchema().convert(_source[6]);
|
||||
if(_source.length <= 7) { return; } this.bitrate = (Integer)_fields[7].getSchema().convert(_source[7]);
|
||||
if(_source.length <= 8) { return; } this.person = (List<String>)_fields[8].getSchema().convert(_source[8]);
|
||||
if(_source.length <= 9) { return; } this.player = (Integer)_fields[9].getSchema().convert(_source[9]);
|
||||
if(_source.length <= 10) { return; } this.copyright = (String)_fields[10].getSchema().convert(_source[10]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void messageUnpack(Unpacker _pac) throws IOException, MessageTypeException {
|
||||
int _length = _pac.unpackArray();
|
||||
if(_length <= 0) { return; }
|
||||
this.uri = _pac.unpackString();
|
||||
if(_length <= 1) { return; }
|
||||
this.title = _pac.unpackString();
|
||||
if(_length <= 2) { return; }
|
||||
this.width = _pac.unpackInt();
|
||||
if(_length <= 3) { return; }
|
||||
this.height = _pac.unpackInt();
|
||||
if(_length <= 4) { return; }
|
||||
this.format = _pac.unpackString();
|
||||
if(_length <= 5) { return; }
|
||||
this.duration = _pac.unpackLong();
|
||||
if(_length <= 6) { return; }
|
||||
this.size = _pac.unpackLong();
|
||||
if(_length <= 7) { return; }
|
||||
this.bitrate = _pac.unpackInt();
|
||||
if(_length <= 8) { return; }
|
||||
int _person_length = _pac.unpackArray();
|
||||
this.person = new ArrayList(_person_length);
|
||||
for(int _i=0; _i < _person_length; ++_i) {
|
||||
String _person_i = _pac.unpackString();
|
||||
this.person.add(_person_i);
|
||||
}
|
||||
if(_length <= 9) { return; }
|
||||
this.player = _pac.unpackInt();
|
||||
if(_length <= 10) { return; }
|
||||
this.copyright = _pac.unpackString();
|
||||
for(int _i=11; _i < _length; ++_i) { _pac.unpackObject(); }
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Media createFromMessage(Object[] _message)
|
||||
{
|
||||
Media _self = new Media();
|
||||
if(_message.length <= 0) { return _self; } _self.uri = (String)_message[0];
|
||||
if(_message.length <= 1) { return _self; } _self.title = (String)_message[1];
|
||||
if(_message.length <= 2) { return _self; } _self.width = (Integer)_message[2];
|
||||
if(_message.length <= 3) { return _self; } _self.height = (Integer)_message[3];
|
||||
if(_message.length <= 4) { return _self; } _self.format = (String)_message[4];
|
||||
if(_message.length <= 5) { return _self; } _self.duration = (Long)_message[5];
|
||||
if(_message.length <= 6) { return _self; } _self.size = (Long)_message[6];
|
||||
if(_message.length <= 7) { return _self; } _self.bitrate = (Integer)_message[7];
|
||||
if(_message.length <= 8) { return _self; } _self.person = (List<String>)_message[8];
|
||||
if(_message.length <= 9) { return _self; } _self.player = (Integer)_message[9];
|
||||
if(_message.length <= 10) { return _self; } _self.copyright = (String)_message[10];
|
||||
return _self;
|
||||
}
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user