Compare commits

..

516 Commits

Author SHA1 Message Date
frsyuki
076bd07f39 cpp: version 0.5.6 2011-04-24 00:23:08 +09:00
FURUHASHI Sadayuki
00e897503b java: fixes typo on CHANGES.txt 2011-04-24 00:11:34 +09:00
FURUHASHI Sadayuki
2f3c47f385 java: version 0.5.2-devel 2011-04-23 23:57:27 +09:00
Muga Nishizawa
2b28211701 MSGPACK-6 added new TemplatePrecompiler function 2011-04-23 22:47:44 +09:00
Muga Nishizawa
46c794fc2e java: added test program for TemplatePrecompiler 2011-04-23 22:37:08 +09:00
Muga Nishizawa
0408738b48 java: write test program for TemplatePrecompiler 2011-04-23 19:19:05 +09:00
frsyuki
eb8a338a0e cpp: unpacker::release_zone() calls msgpack_unpacker_release_zone() #42 2011-04-17 08:25:55 +09:00
frsyuki
23480bfe8a cpp: fixed missing ctx.user.z = z and release_zone uses pointer swapp instead of copying #42 2011-04-17 08:24:33 +09:00
frsyuki
3384dbc92d cpp: fixes test/streaming_c.cc #42 2011-04-17 08:21:52 +09:00
frsyuki
8446549ed8 Merge branch 'master' of github.com:msgpack/msgpack 2011-04-17 06:49:36 +09:00
frsyuki
6a9f3ae71d c: fixed a double-free problem on msgpack_unpacker_release_zone #42 (aikar++) 2011-04-17 06:48:36 +09:00
FURUHASHI Sadayuki
c58ce1a975 MSGPACK-7 added -source 1.5 -target 1.5 options to javac 2011-04-12 18:41:08 +09:00
FURUHASHI Sadayuki
c6d9bbd7b0 MSGPACK-7 fixed test cases; iteration order of HashMap is not defined by JDK 5/6 specification 2011-04-12 18:39:54 +09:00
Muga Nishizawa
65ddd1a455 java: add test program for TemplatePrecompiler 2011-04-10 02:33:46 +09:00
Muga Nishizawa
58c0fe0f91 java: Refactored template builders again 2011-04-09 21:10:15 +09:00
Muga Nishizawa
b96b62f2ac scala: deleted the AUTHORS file 2011-04-08 16:20:28 +09:00
Muga Nishizawa
43fc0a52a6 scala: added a new AUTHORS file and edited pom.xml 2011-04-08 16:17:25 +09:00
Muga Nishizawa
4f3d9a1ded Refactored programs related to TemplateBuilder.java 2011-04-08 16:13:29 +09:00
FURUHASHI Sadayuki
b50ff920f0 MSGPACK-5 added test cases for Unpacker.unpackXxx() methods 2011-04-07 23:21:56 +09:00
FURUHASHI Sadayuki
983ae0c5a2 MSGPACK-4 BufferedUnapckerImpl.unpackInt: more(4)+advance(4) -> more(5)+advance(5) 2011-04-07 23:21:30 +09:00
FURUHASHI Sadayuki
9d4db84987 MSGPACK-4 BufferedUnpackerImpl.unpackLong: more(4)+advance(4) -> more(5)+advance(5) 2011-04-07 22:32:59 +09:00
Muga Nishizawa
dfaa281476 java: Fixed TemplateClassWriter.java but, it doesn't work. 2011-04-07 00:38:21 +09:00
Muga Nishizawa
c1c25c455c scala: Modified pom.xml. I changed version of 'MessagePack for Java' from 0.5.1-devel to 0.5.2-SNAPSHOT 2011-04-06 08:52:14 +09:00
Muga Nishizawa
e65197f386 Merge branch 'master' of https://github.com/watabiki/msgpack 2011-04-06 01:18:12 +09:00
Muga Nishizawa
ecbb8f8711 java: Merged takezoux2's branch for 'MessagePack for Scala' 2011-04-06 00:50:58 +09:00
Watabiki Naoya
03aa736199 java: update BigDecimalTemplate, TestPackConvert and TestPackUnpack 2011-04-05 23:26:53 +09:00
Muga Nishizawa
821b1f0384 Merge branch 'master' of git@github.com:msgpack/msgpack 2011-04-05 03:35:08 +09:00
Muga Nishizawa
233ad3aaff java: Updated several property files in .settings 2011-04-05 03:34:11 +09:00
Muga Nishizawa
9c4812f4d4 java: Fixed RawType's bug that hash values of same byte arrays (raw data) are different 2011-04-05 03:30:43 +09:00
Muga Nishizawa
337cc9fa78 java: Fixed a bug that NullPointerException occurs within DefaultTemplate.java 2011-04-05 01:27:51 +09:00
Muga Nishizawa
dfe29a0329 Merge branch 'master' of git@github.com:msgpack/msgpack 2011-04-05 00:52:30 +09:00
Muga Nishizawa
85e90aa81e java: Improved DefaultTemplate.java. It allows displaying details of exception messages 2011-04-05 00:51:53 +09:00
Hideyuki Tanaka
86d30fe571 haskell: reduce dependency of template-haskell 2011-04-04 23:33:02 +09:00
mzp
173302267f ocaml: upadte build file 2011-04-04 18:28:37 +09:00
Muga Nishizawa
8e3ea8d26c java: edit TemplateRegistry.java 2011-04-04 02:28:24 +09:00
Muga Nishizawa
cb065563c2 Merge branch 'master' of git@github.com:msgpack/msgpack 2011-04-04 01:59:34 +09:00
Muga Nishizawa
27b89b237b java: prototyped TemplateClassWriter, which is program for writing class file of generated tmplate class 2011-04-04 01:59:13 +09:00
takeshita
21f0d0bfc4 Delete moved class.
(TemplateBuilder.java is moved to org.msgpack.template.builder)
2011-04-04 01:46:29 +09:00
takeshita
d5e583b09e Implement Scala MessagePack.
Change Java MessagePack to fit Scala's.
Minor version up for Java's MessagePack.
2011-04-04 01:37:24 +09:00
UENISHI Kota
15fb9bbcb2 Merge branch 'master' of https://github.com/moriyoshi/msgpack 2011-04-03 19:52:34 +09:00
Muga Nishizawa
a03418ab12 java: edit BuiltInTemplateLoader.java 2011-04-03 19:42:43 +09:00
Muga Nishizawa
035513844d Merge branch 'master' of git@github.com:msgpack/msgpack 2011-04-03 19:11:56 +09:00
Muga Nishizawa
193906b8ce java: insert codes for initializing BigDecimalTemplate and DateTemplate instances to Templates.java 2011-04-03 19:10:34 +09:00
Moriyoshi Koizumi
d354f2e8c2 Documentation. 2011-04-03 19:09:14 +09:00
Watabiki Naoya
24a8ee436f add DateTemplate and BigDecimalTemplate 2011-04-03 18:39:41 +09:00
mzp
6e5f9404b7 ocaml: initial commit 2011-04-03 17:11:53 +09:00
Moriyoshi Koizumi
64fe90aabb Add TestUnpackFloat(). 2011-04-03 15:34:37 +09:00
Moriyoshi Koizumi
7e31d487e0 float type was gone from go language at some time I don't know. 2011-04-03 14:06:08 +09:00
moriyoshi
ee16e2eb30 Handle unsupported typecode 2011-04-03 11:14:49 +09:00
moriyoshi
003fb3392f Byte arrays in Go should not be serialized as arrays. 2011-04-03 11:14:49 +09:00
moriyoshi
0e82278cd5 Fix: InterfaceValue wasnt' correctly unwrapped when passed to PackValue() 2011-04-03 11:14:49 +09:00
moriyoshi
5b544248bc Add new API function UnpackReflected() that returns multiple reflect.Value for unpacked elements of arrays or maps. 2011-04-03 11:14:49 +09:00
moriyoshi
d4d7495c0a Forgot to support map16 / map32 2011-04-03 11:14:48 +09:00
moriyoshi
8325cce44c Adapt to new reflection API (notified by mattn. thanks) 2011-04-03 11:14:48 +09:00
moriyoshi
ee0debc5b3 Add .gitignore 2011-04-03 11:14:48 +09:00
moriyoshi
8f1bd12a17 Improve testsuite. 2011-04-03 11:14:10 +09:00
moriyoshi
fccf1016e4 Fix bugs in unpacker. 2011-04-03 11:14:10 +09:00
moriyoshi
1b010a082b Add go binding. 2011-04-03 11:14:10 +09:00
Hideyuki Tanaka
324f215316 haskell: version bump 2011-03-29 16:17:46 +09:00
Hideyuki Tanaka
ace4f1e7f0 fix encoding unicode strings, and Text support 2011-03-29 16:15:29 +09:00
Hideyuki Tanaka
5c5f16f148 haskell: version bump 2011-03-18 00:46:43 +09:00
Hideyuki Tanaka
f50855d5c0 fix for packing and unpacking Object 2011-03-18 00:44:15 +09:00
Muga Nishizawa
86917b0ba7 improved constructor in JavassistTemplateBuilder class. This improvement is based on https://github.com/msgpack/msgpack-rpc/issues#issue/13. 2011-03-11 12:24:09 +09:00
Hideyuki Tanaka
7201fcbe0f remove Iteratee dependency 2011-03-10 22:17:15 +09:00
Hideyuki Tanaka
83f1735fbb fix description 2011-03-09 18:06:57 +09:00
Hideyuki Tanaka
80fd8e70f0 update library version. 2011-03-09 17:02:01 +09:00
Hideyuki Tanaka
698c1c2b7a Merge git://github.com/xanxys/msgpack into pull-master 2011-03-09 16:19:19 +09:00
Yuto Hayamizu
5d3287f5aa gtest requires pthread 2011-03-03 06:42:14 +09:00
Yuto Hayamizu
6990fe6f51 remove duplicated code 2011-03-03 06:38:09 +09:00
Yuto Hayamizu
0b81068368 /cpp/preprocess: fix string comp. operator 2011-03-03 06:27:31 +09:00
FURUHASHI Sadayuki
5b1851ae22 cpp: version 0.5.5 2011-02-24 00:35:00 +09:00
FURUHASHI Sadayuki
0d5708a01d cpp: fixes problem that InterlockedIncrement/Decrement are not found on _WIN32 platform 2011-02-24 00:21:54 +09:00
FURUHASHI Sadayuki
67ab510b5d cpp: fixes some implicit cast warnings 2011-02-23 23:48:26 +09:00
FURUHASHI Sadayuki
d1264a1289 cpp: fixes msgpack_vc.postbuild.bat 2011-02-23 23:47:33 +09:00
FURUHASHI Sadayuki
3b973021a1 sysdep.h: eliminated #include <winsock2.h> 2011-02-23 23:46:39 +09:00
INADA Naoki
182624895f python: Remove UnpackIterator. Unpacker is iterator of itself. 2011-01-30 10:45:39 +09:00
INADA Naoki
548de3739c python: Disable gc while deserializing. 2011-01-29 23:23:56 +09:00
INADA Naoki
718a3efd64 python: Fix segmentation fault when default returns it's argument. 2011-01-29 23:22:41 +09:00
INADA Naoki
76b8c3250b Merge branch 'master' of github.com:msgpack/msgpack 2011-01-29 07:31:59 +09:00
INADA Naoki
dafaa8bd8c python: 0.1.9 2011-01-29 07:31:06 +09:00
INADA Naoki
9c9b2c25ea python: refactoring. 2011-01-29 07:27:10 +09:00
INADA Naoki
e89cd81022 Add use_list option to unpack and unpackb 2011-01-28 18:59:05 +09:00
advect
5debbd2be8 php: added unpack of class object converter 2011-01-16 17:35:10 +09:00
INADA Naoki
fe26df5355 python: Add memory error check. 2011-01-10 20:47:23 +09:00
INADA Naoki
85778494e4 python: Check if (m|re)alloc's return value is NULL. (Thanks to Mateusz) 2011-01-10 05:07:07 +09:00
INADA Naoki
a94ce3c715 python: Fix typo in docstring. (thanks to Mateusz.) 2011-01-10 05:05:14 +09:00
INADA Naoki
a440ff1117 python: Change URL in setup.py from sf.net to msgpack.org 2011-01-10 00:10:29 +09:00
INADA Naoki
8195137bc5 python: msgpack-python-0.1.8 2011-01-09 23:58:26 +09:00
INADA Naoki
3e2bd25e4e python: Fix another segv. 2011-01-09 23:54:06 +09:00
INADA Naoki
ffd0c2f624 python: Fix segv on unpacking from stream. 2011-01-09 23:40:09 +09:00
INADA Naoki
23333c98d7 python: Add test for issue29. 2011-01-09 23:29:18 +09:00
INADA Naoki
5a12ab98c4 python: Make aliases for API compatibility to pickle.
``dumps`` is alias of ``packb`` and ``loads`` is alias of ``unpacks``.
2011-01-09 23:17:20 +09:00
INADA Naoki
0b327a63fc python: Don't use `from __future__ import unicode_literals`.
Python 2.5 or older doesn't support it.
2011-01-09 23:13:35 +09:00
INADA Naoki
15b28a245c python: Update ChangeLog. 2011-01-09 23:06:56 +09:00
INADA Naoki
6ef5684797 Merge branch 'master' of github.com:msgpack/msgpack 2011-01-08 17:45:13 +09:00
xanxys
d439b1495b haskell: add ObjectFloat to send floats, and Assoc to make map (un)packing explicit 2010-12-28 19:22:37 +09:00
advect
9e096a3f0e php: version 0.3.4: supported Windows building 2010-12-28 16:09:13 +09:00
advect
0acf6ec150 php: version 0.3.3 2010-12-27 11:09:14 +09:00
Muga Nishizawa
4b36340474 java: refactor JavassistTemplateBuilder.java 2010-12-23 15:51:04 +09:00
FURUHASHI Sadayuki
910e642a8b java: version 0.5.1 2010-12-14 18:21:53 +09:00
FURUHASHI Sadayuki
9f571146fb java: fixes cast error on GenericArrayType 2010-12-14 17:47:45 +09:00
FURUHASHI Sadayuki
339725f73d java: throws MessagePackException if target==null on *ArrayTemplate 2010-12-13 18:52:25 +09:00
Muga Nishizawa
aff964c58b java: fixed a bug within CollectionTemplate.java 2010-12-12 00:48:31 +09:00
Muga Nishizawa
0c07e745f8 java: change spec. of pack methods in ListTemplate and MapTemplate as follow: If user passes null object to the pack method, MessageTypeException is thrown. 2010-12-12 00:47:20 +09:00
Muga Nishizawa
419d2e9564 java: change spec. of pack methods in several template classes as follow: If user passes null object to the pack method, MessageTypeException is thrown. 2010-12-12 00:46:05 +09:00
Muga Nishizawa
f936a307c6 java: add test methods for CollectionTemplate and change spec. of several test methods 2010-12-12 00:38:13 +09:00
Muga Nishizawa
4e4678edfa java: add packByteBuffer method in Packer.java because I needed non-nullcheck pack(ByteBuffer) for refining ByteBufferTemplate.java 2010-12-12 00:35:43 +09:00
FURUHASHI Sadayuki
cb7a4b3116 java: version 0.5.0 2010-12-09 23:36:27 +09:00
FURUHASHI Sadayuki
5ca4c42a74 Merge branch 'master' of github.com:msgpack/msgpack 2010-12-09 23:28:23 +09:00
FURUHASHI Sadayuki
1238a7ca07 java: adds AUTHORS file 2010-12-09 23:28:16 +09:00
Muga Nishizawa
a9db60a73d java: replace reflective method calls with base-level method calls in JavassistTemplateBuilder.java 2010-12-09 23:25:11 +09:00
FURUHASHI Sadayuki
bd32ac19d4 java: removes old benchmark codes 2010-12-09 23:01:04 +09:00
FURUHASHI Sadayuki
eaf9944e43 java: added ElementType.PARAMETER to the target of @Ignore, @Index, @Nulable, @Optional and @Required annotations for RPC 2010-12-09 17:31:29 +09:00
FURUHASHI Sadayuki
703fdbc01d java: array type support 2010-12-08 19:38:12 +09:00
FURUHASHI Sadayuki
2daa08b0e7 java: disabled ObjectArrayTempalte - it doesn't work 2010-12-06 00:13:05 +09:00
FURUHASHI Sadayuki
05d9d22d9e java: fixes native zero-copy unpacking routines of ByteBuffer 2010-12-03 22:56:04 +09:00
FURUHASHI Sadayuki
8b7894f9bd java: fixes comments in TemplateBuffer.java 2010-12-03 22:54:20 +09:00
Muga Nishizawa
a71439607f java: performance improvement for ByteBufferTemplate 2010-12-03 21:53:29 +09:00
Muga Nishizawa
aca0d7f969 java: refactor ByteBufferTemplate.java 2010-12-02 01:11:55 +09:00
Muga Nishizawa
310a8e4342 Merge branch 'master' of git@github.com:msgpack/msgpack
Conflicts:
	java/src/main/java/org/msgpack/MessagePack.java
2010-12-02 00:54:28 +09:00
FURUHASHI Sadayuki
24fbe1ef5b java: uses ReflectionTemplateBuilder instead of JavassistTempalteBuilder where System.getProperty("java.vm.name") == "Dalvik" 2010-12-01 23:27:36 +09:00
FURUHASHI Sadayuki
33d8faa35d java: JavassistTemplateBuilder: fixes comments 2010-12-01 23:15:55 +09:00
FURUHASHI Sadayuki
44be714f65 java: adds JavassistTemplateBuilder.addClassLoader method 2010-12-01 22:59:33 +09:00
FURUHASHI Sadayuki
0df3da6b10 java: adds TemplateRegistry.setTemplateBuilder method 2010-12-01 22:59:20 +09:00
FURUHASHI Sadayuki
79197b6ec7 java: more test cases of TemplateBuilder 2010-12-01 22:44:38 +09:00
FURUHASHI Sadayuki
353b6b51cb java: adds TemplateBuildException 2010-12-01 22:44:24 +09:00
FURUHASHI Sadayuki
bd9a2c0d3a java: migrates from util.codegen to TemplateBuilder 2010-12-01 22:42:55 +09:00
Muga Nishizawa
53b0ee6536 Merge branch 'master' of git@github.com:msgpack/msgpack 2010-12-01 21:20:10 +09:00
FURUHASHI Sadayuki
78daac0f1b java: adds type.RawTemplate 2010-12-01 20:49:41 +09:00
FURUHASHI Sadayuki
b970b9b9a8 java: adds JavassistTemplateBuilder 2010-12-01 20:39:11 +09:00
FURUHASHI Sadayuki
0339db57f1 java: adds TemplateBuilder and ReflectionTemplateBUilder 2010-12-01 20:38:58 +09:00
FURUHASHI Sadayuki
461b147897 java: uses TemplateRepostry as default 2010-12-01 20:37:32 +09:00
FURUHASHI Sadayuki
a3cd13b399 java: adds actual generic templates 2010-12-01 20:36:52 +09:00
FURUHASHI Sadayuki
eb5d326a1e java: adds GenericTemplates 2010-12-01 20:34:33 +09:00
FURUHASHI Sadayuki
cce6eb94e2 java: adds DefaultTemplate 2010-12-01 20:34:23 +09:00
FURUHASHI Sadayuki
8311c72c69 java: adds BultInTemplateLoader 2010-12-01 20:33:38 +09:00
FURUHASHI Sadayuki
9a059285d9 java: registers buit-in templates to TemplateRegistry 2010-12-01 20:32:22 +09:00
FURUHASHI Sadayuki
469ac7891d java adds TemplateRegistry that replaces CustomMessage 2010-12-01 20:25:06 +09:00
FURUHASHI Sadayuki
16264a5693 java: adds array templates 2010-12-01 20:24:36 +09:00
FURUHASHI Sadayuki
6eedb50f56 java: adds TemplateBuilder and ReflectionTemplateBuilder 2010-11-30 21:59:07 +09:00
FURUHASHI Sadayuki
5f07215662 java: adds @Requred, @Ignore and @Index annotations 2010-11-30 21:58:24 +09:00
FURUHASHI Sadayuki
d3a02fb2ca java: @MessagePackMessage(default field option) 2010-11-30 21:57:12 +09:00
FURUHASHI Sadayuki
2c823f1aaa java: uses bit shift operations instead of ByteBuffer.putXxx 2010-11-30 21:55:45 +09:00
FURUHASHI Sadayuki
706293aadc java: adds type.Raw 2010-11-30 15:34:32 +09:00
FURUHASHI Sadayuki
dfdceb4258 java: updates VectoredByteBuffer 2010-11-29 18:37:47 +09:00
FURUHASHI Sadayuki
0014b7fdb9 java: adds VectoredByteBuffer 2010-11-29 18:01:39 +09:00
FURUHASHI Sadayuki
3b28f1f8af ruby: buffer size limit (disabled at present) 2010-11-28 23:13:53 +09:00
FURUHASHI Sadayuki
c689d476ca Merge remote branch 'egtra/master' 2010-11-24 18:05:50 +09:00
FURUHASHI Sadayuki
cc534fd21f ruby: adds Unpacker#feed_each 2010-11-24 17:24:55 +09:00
egtra
124efcf247 improve msvc support 2010-11-23 23:32:55 +09:00
Muga Nishizawa
dd452b05e3 java: rollback MessagePack.java 2010-11-19 02:57:42 +09:00
Muga Nishizawa
b5617f7df9 java: refactor register method in MessagePack.java for TemplateProvider 2010-11-19 01:58:30 +09:00
Muga Nishizawa
b73ca1ba3a java: edit MessagePack.java for TemplateProvider 2010-11-19 01:46:31 +09:00
Muga Nishizawa
39ad071c4f java: fixed a bug that javassist cannot find class files that were loaded by custom class loader 2010-11-18 22:26:58 +09:00
Muga Nishizawa
fa0b576a45 java: Fixed a bug that ClassTemplate cannot pack a ByteBuffer object but, it is a temporary impl. 2010-11-11 13:38:15 +09:00
frsyuki
c2c7591987 java: version 0.4.3-devel 2010-11-10 00:54:49 +09:00
frsyuki
3e939e3775 java: fixes MessagePackObject.convert(Template, T) 2010-11-10 00:53:15 +09:00
frsyuki
f6384e10bc java: adds test for DynamicOrdinalEnumTemplate 2010-11-10 00:32:25 +09:00
frsyuki
c283842563 java: MessagePackOptional -> Optional, MessagePackNullable -> Nullable 2010-11-10 00:16:23 +09:00
frsyuki
1135976225 java: adds MessagePack.unpack(Class<?>, FieldList) 2010-11-09 23:51:58 +09:00
frsyuki
76679d33df java: changes Template interface: unpack(Unpacker, Object to = null), convert(MessagePackObject from, Object to = null) 2010-11-09 23:43:16 +09:00
frsyuki
e9d44b90bc java: adds FieldList class 2010-11-09 22:11:47 +09:00
Muga Nishizawa
8a7a391166 java: delete ByteBufferTemplate.java in org.msgpack.util.codegen package 2010-11-09 10:13:55 +09:00
Muga Nishizawa
d6c5a9eece delete a dead code within DynamicCodeGen.java 2010-11-09 09:57:23 +09:00
Muga Nishizawa
56ad6915d0 Merge branch 'master' of git@github.com:msgpack/msgpack 2010-11-09 09:28:38 +09:00
frsyuki
466c260782 java: version 0.4.2-devel 2010-11-09 03:16:00 +09:00
frsyuki
d8e2d1725a java: MessagePack.unpack(InputStream) throws IOException 2010-11-09 02:57:49 +09:00
frsyuki
33b43d03ac java: adds MessagePackNullable annotation 2010-11-09 02:46:23 +09:00
frsyuki
517509db6e java: adds NullableTemplate 2 2010-11-09 02:07:53 +09:00
frsyuki
95f01a5976 java: adds MessagePackObject.unpack(Class<T> klass) 2010-11-09 02:07:50 +09:00
frsyuki
d08d3bf56d java: adds NullableTemplate 2010-11-09 01:07:25 +09:00
frsyuki
587fd669e8 java: adds ByteBufferTemplate 2010-11-08 23:20:27 +09:00
Muga Nishizawa
e3553b87fe java: move ByteBufferTemplate.java to org.msgpack.util.codegen package 2010-11-06 11:31:40 +09:00
Muga Nishizawa
a078d2360c java: add temporal implementation of ByteBufferTemplate.java 2010-11-06 00:59:32 +09:00
frsyuki
2d3abf8e6e java: version 0.4.1-devel 2010-11-05 19:21:27 +09:00
Muga Nishizawa
cacae0fb7d java: refactor DynamicCodeGen.java and Constants.java. Thanks frsyuki for fixing a bug in DynamicCodeGen.java 2010-11-04 02:00:34 +09:00
INADA Naoki
d7fc215c16 python: 0.1.7 2010-11-03 03:43:49 +09:00
INADA Naoki
bb69aa18f2 python: Add ws2_32 library if platform is win32. 2010-11-03 03:35:52 +09:00
INADA Naoki
e4f515166a python: Add ChangeLog.rst 2010-11-03 03:26:33 +09:00
INADA Naoki
f325acb0ea Merge branch 'master' of github.com:msgpack/msgpack 2010-11-03 03:19:28 +09:00
INADA Naoki
d1b6e65dd8 python: Port some tests from 2 to 3. 2010-11-03 03:15:12 +09:00
INADA Naoki
4688252bd4 python: Support old buffer protocol when unpack. (experimental) 2010-11-03 03:11:00 +09:00
INADA Naoki
b1df5d3ad7 python: Add test for unpacking buffer object. 2010-11-02 14:09:50 +09:00
INADA Naoki
09bad2938e python: Add msgpack/_msgpack.c to .gitignore 2010-11-02 14:02:10 +09:00
advect
bad69fd397 php: fiexed unpacker 2010-10-30 16:06:50 +09:00
Fuji, Goro
b4ae6bf82c perl: disable warnings 2010-10-30 13:04:30 +09:00
Fuji, Goro
eac0f83864 perl: check data strictly; which is slow, but required 2010-10-30 12:38:32 +09:00
Fuji, Goro
3f16f080ac perl: add failing tests for PP 2010-10-30 01:09:12 +09:00
Fuji, Goro
5de2b974fb perl: ord(substr(...)) *is* faster than unpack() 2010-10-30 00:42:00 +09:00
Fuji, Goro
6a9cb51828 perl: modify internal names for the next refactoring 2010-10-30 00:31:41 +09:00
Fuji, Goro
f1c294ca50 perl: make error messages compatible with XS 2010-10-30 00:28:53 +09:00
Fuji, Goro
c320e44a23 perl: update Unpacker.pod 2010-10-28 17:26:04 +09:00
Fuji, Goro
ea36ef3107 perl: tests 2010-10-28 17:05:41 +09:00
Fuji, Goro
fedc37d079 Revert "perl: cleanup"
This reverts commit bc8d8ab65a.
2010-10-28 16:31:19 +09:00
Fuji, Goro
86ccfcc03c perl: changelogging 2010-10-28 16:25:19 +09:00
Fuji, Goro
bc8d8ab65a Revert "Revert "perl: cleanup""
This reverts commit a7a23d3bc8.
2010-10-28 16:17:53 +09:00
Fuji, Goro
a7a23d3bc8 Revert "perl: cleanup"
This reverts commit 82d33944e6.
2010-10-28 16:16:12 +09:00
Fuji, Goro
82d33944e6 perl: cleanup 2010-10-28 16:08:20 +09:00
Fuji, Goro
8a629ad6fb Fix streaming unpacking for splitted packed data 2010-10-28 15:49:22 +09:00
INADA Naoki
e1711ffcf2 Add list_hook option to unpacker. 2010-10-26 02:09:52 +09:00
INADA Naoki
063d51c662 Add check for recursion limit and default hook result. 2010-10-26 01:49:00 +09:00
INADA Naoki
d8e3575a46 Remove unnecessary refcount manipulation. 2010-10-26 01:32:08 +09:00
INADA Naoki
6fa609be3f Add test for Python3. 2010-10-26 01:31:27 +09:00
INADA Naoki
70982e204c Add object_hook option to unpack and default option to pack.
(see simplejson for how to use).
2010-10-26 01:26:06 +09:00
frsyuki
2af7df5865 java: fixes MessagePack.unpack method 2010-10-25 14:49:14 +09:00
frsyuki
59610e81de java: DynamicCodeGen::insertCodeOfUnpackMethodBody unpacks last optional field of classes correctly 2010-10-25 14:18:41 +09:00
Muga Nishizawa
cdfac703ef java: merge CustomMessage.java and DynamicCodeGenBase.java that can be not merged automatically 2010-10-24 23:24:27 +09:00
Muga Nishizawa
ad5ebd007e java: refactor org.msgpack.util.codegen.*.java 2010-10-24 23:10:07 +09:00
frsyuki
1bd347d997 java: fixes CustomMessage class 2010-10-24 21:17:19 +09:00
frsyuki
147056073d java: improves test case of the MessagePack class 2010-10-24 21:04:31 +09:00
frsyuki
1b3231e617 java: improves test case of the MessagePack class 2010-10-24 20:59:19 +09:00
frsyuki
7ac4ad3e38 java: adds MessagePack.register methods 2010-10-24 20:46:22 +09:00
frsyuki
0a345cb12b java: fixes CollectionTemplate 2010-10-24 20:16:37 +09:00
frsyuki
19ff0dd17f java: fixes ListTemplate and MapTemplate 2010-10-24 20:11:39 +09:00
frsyuki
e3bf8a404b java: adds MessagePack class 2010-10-24 19:32:45 +09:00
frsyuki
dbb28d9a8f java: Template extends MessagePacker 2010-10-24 18:46:48 +09:00
frsyuki
19fd4e755c java: removes ReflectionPacker and ReflectionTemplate (replaced by DynamicCodeGen) 2010-10-24 18:45:58 +09:00
Muga Nishizawa
77698cd924 java: change modifiers specified by several methods 2010-10-24 00:59:14 +09:00
Muga Nishizawa
945d279f28 java: fix a bug within a code of DynamicCodeGenBase.java 2010-10-24 00:40:58 +09:00
Muga Nishizawa
645d296841 java: add test programs for org.msgpack.util.codegen.FieldOption.java 2010-10-23 23:13:54 +09:00
Muga Nishizawa
57446de875 java: refactor org.msgpack.util.codegen.*.java 2010-10-23 23:13:17 +09:00
Muga Nishizawa
3473800ab6 java: not use a putIfAbsent method in ConcurrentHashMap class 2010-10-23 23:11:52 +09:00
Muga Nishizawa
7e5c5153a8 java: edit copyright notions in org.msgpack.annotation.*.java and org.msgpack.util.codegen.*.java 2010-10-23 14:50:32 +09:00
Muga Nishizawa
1b8979f285 java: refactor org.msgpack.util.codegen.*.java 2010-10-23 14:39:01 +09:00
Muga Nishizawa
2aac51dd20 java: append getter methods for element templates in org.msgpack.template.ListTemplate.java, MapTemplate.java and OptionalTemplate.java 2010-10-23 14:37:24 +09:00
Muga Nishizawa
69e32d264c java: write test programs for OptionalTemplate.java 2010-10-22 23:23:53 +09:00
frsyuki
71ae75a5bf java: adds OptionalPacker 2010-10-22 16:18:07 +09:00
frsyuki
86043fd87e java: adds OptionalTemplate 2010-10-22 08:31:03 +09:00
Fuji, Goro
d8aaef4f04 perl: tests 2010-10-21 23:35:07 +09:00
Fuji, Goro
7fc34b6369 perl: tweaks 2010-10-21 23:27:26 +09:00
Fuji, Goro
92b346efa7 perl: clean up 2010-10-21 23:26:03 +09:00
Muga Nishizawa
c790735b9f java: add test programs for org.msgpack.util.codegen.*.java 2010-10-21 02:02:23 +09:00
Muga Nishizawa
64711e615e java: write test programs for org.msgpack.util.codegen.*.java 2010-10-20 21:04:37 +09:00
frsyuki
2065affd45 java: adds CollectionTemplate 2010-10-20 16:40:25 +09:00
frsyuki
4067c56b5d java: supports Collection<T> to pack 2010-10-20 16:32:01 +09:00
tokuhirom
65515638aa perl: oops! added settings for shipit 2010-10-19 13:45:44 +09:00
tokuhirom
371ba3ffe3 Checking in changes prior to tagging of version 0.34.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index 50177f4..486f1c3 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,6 @@
+0.34
+
+    - do not use the corrupt my_snprintf(%ll[du]) on win32(kazuho)

 0.33
2010-10-18 19:30:08 +09:00
Kazuho Oku
5395b62f2f shorter code, fix comment 2010-10-18 19:26:24 +09:00
Kazuho Oku
3e164eab26 do not use the corrupt my_snprintf(%ll[du]) on win32 2010-10-18 19:22:28 +09:00
Muga Nishizawa
ad85533975 java: add a log4j.properties file for unit testing 2010-10-17 19:23:42 +09:00
Muga Nishizawa
d6c2a97931 java: write test programs for org.msgpack.packer.*.java 2010-10-17 18:57:00 +09:00
Muga Nishizawa
17def94ba4 java: describe test programs for org.msgpack.template.*.java 2010-10-17 18:24:08 +09:00
Muga Nishizawa
cf254ea240 Merge branch 'master' of git@github.com:msgpack/msgpack 2010-10-17 14:37:35 +09:00
Muga Nishizawa
2d05110239 java: refactor DynamicCodeGenBase.java 2010-10-17 14:37:13 +09:00
Fuji, Goro
0017f4fce8 Checking in changes prior to tagging of version 0.33.
Changelog diff is:
2010-10-13 12:46:41 +09:00
Fuji, Goro
02f3dd947a perl: optimize PP 2010-10-13 12:46:11 +09:00
Fuji, Goro
ef0874feba perl: tweaks for PreferInteger 2010-10-13 11:02:57 +09:00
Fuji, Goro
14aa1420f0 perl: comments 2010-10-13 10:54:37 +09:00
Fuji, Goro
c506cd97e0 perl: tests 2010-10-13 10:43:56 +09:00
Fuji, Goro
3761aacb1d perl: cleanup PP 2010-10-13 10:14:31 +09:00
Fuji, Goro
233f13aac5 perl: add tests for unpacking 'float' 2010-10-13 10:03:56 +09:00
Fuji, Goro
0ced3ec2d2 perl: fix tests 2010-10-13 09:38:40 +09:00
Fuji, Goro
5b786f65a4 Checking in changes prior to tagging of version 0.32.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index 6e07966..4657079 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,4 +1,8 @@

+0.32
+
+    - add tests to detect Alpha problems reported via CPAN testers (gfx)
+
 0.31

     - update Module::Install::XSUtil for ccache support (gfx)
2010-10-12 23:12:34 +09:00
Fuji, Goro
770542c8c7 perl: add tests 2010-10-12 23:10:59 +09:00
Fuji, Goro
4f1207a38c perl: add a strong assertion 2010-10-12 23:05:58 +09:00
Fuji, Goro
2b65f81e23 Add tests 2010-10-12 22:58:53 +09:00
Muga Nishizawa
c10eb2c17b java: add the code for checking a null pointer to DynamicCodeGen.java 2010-10-11 01:30:42 +09:00
Muga Nishizawa
3f5ac54bf5 java: refactor the programs in a org.msgpack.util.codegen package 2010-10-09 21:53:49 +09:00
Muga Nishizawa
790f9409b1 Merge branch 'master' of git@github.com:msgpack/msgpack 2010-10-07 23:53:22 +09:00
Muga Nishizawa
a3d831b723 java: refactor DynamicCodeGen.java 2010-10-07 23:53:01 +09:00
Fuji, Goro
b9483deea3 Checking in changes prior to tagging of version 0.31.
Changelog diff is:
2010-10-07 17:06:45 +09:00
Fuji, Goro
c211d2ac45 Merge commit 'perl-0.30' 2010-10-07 17:05:37 +09:00
Fuji, Goro
119a03dd5f perl: changelogging 2010-10-07 16:56:36 +09:00
Fuji, Goro
f3fbb7e1f6 perl: Update Makefile.PL using M::I::XSUtil 0.36 (support for ccache) 2010-10-07 16:54:49 +09:00
Fuji, Goro
2be98e8467 perl: changelogging 2010-10-07 16:18:47 +09:00
Fuji, Goro
91b1806e9d perl: add XS_VERSION_BOOTCHECK for safety 2010-10-07 16:16:59 +09:00
Fuji, Goro
8548b3645a perl: cleanup 2010-10-07 16:13:56 +09:00
Muga Nishizawa
4bbfb3f9a3 java: refactor DynamicCodeGen.java 2010-10-07 15:27:11 +09:00
Muga Nishizawa
98eec72522 Merge branch 'master' of git@github.com:msgpack/msgpack 2010-10-07 13:01:33 +09:00
Muga Nishizawa
562d50df4d java: refactor several programs in a org.msgpack.util.codegen package 2010-10-07 13:01:06 +09:00
frsyuki
f3ee5ab372 cpp: fixes ./bootstrap to surely run ./preprocess 2010-10-07 06:28:12 +09:00
INADA Naoki
aa2a3e5b07 Add unicode testcase for Python2. 2010-10-07 03:07:52 +09:00
INADA Naoki
8467307239 Fix testcase for unicode. 2010-10-07 03:04:00 +09:00
INADA Naoki
90da951a6f Use PyUnicode_AsUTF8String() instead of o.encode('utf-8'). 2010-10-07 03:02:02 +09:00
tokuhirom
59f81b331c Checking in changes prior to tagging of version 0.30.
Changelog diff is:
2010-10-06 18:00:00 +09:00
Fuji, Goro
77a7d3d26a perl: Fix utf8 mode not to be reseted by $unpacker->reset method 2010-10-06 17:52:32 +09:00
tokuhirom
4321b80999 Checking in changes prior to tagging of version 0.29.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index b506234..333a824 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,7 @@
+0.29
+
+    - add $unpacker->utf8 mode, decoding strings as UTF-8.
+
 0.28

     - added more tests(gfx)
2010-10-06 12:29:31 +09:00
tokuhirom
4b93b06323 perl: regenerated README file 2010-10-06 12:27:41 +09:00
tokuhirom
96fb2e4b7c Merge branch 'perl-utf8-mode' of github.com:msgpack/msgpack 2010-10-06 12:24:36 +09:00
Muga Nishizawa
3dc1048dfb Merge branch 'master' of git@github.com:msgpack/msgpack 2010-10-05 20:47:41 +09:00
Muga Nishizawa
28f4bd5a67 java: edit test programs for org.msgpack.util.codegen.* 2010-10-05 20:47:03 +09:00
Muga Nishizawa
b01c270889 java: refactor the programs in a org.msgpack.util.codegen package 2010-10-05 20:45:51 +09:00
Fuji, Goro
7c92f8a90b perl: improve docs 2010-10-05 17:47:27 +09:00
Fuji, Goro
a4a04872a3 perl: add $unpacker->utf8 mode, decoding strings as UTF-8. 2010-10-05 17:10:10 +09:00
Fuji, Goro
f2d13cd647 perl: make test code more simple 2010-10-05 15:58:49 +09:00
Fuji, Goro
9346908485 perl: remove tricky hacks 2010-10-05 15:55:38 +09:00
Fuji, Goro
b3a7ba14f7 Merge branch 'master' of github.com:msgpack/msgpack 2010-10-05 15:53:57 +09:00
frsyuki
524ef9553c Merge branch 'master' of http://github.com/advect/msgpack into advect-master 2010-10-03 16:55:59 +09:00
Muga Nishizawa
a85f6e72fe java: edit DynamicCodeGen.java 2010-10-03 02:09:01 +09:00
Muga Nishizawa
1ae6a41336 java: edit BasicConstants.java in org.msgpack.util.codegen 2010-10-02 23:37:08 +09:00
Muga Nishizawa
3ec55791c6 java: refactor DynamicCodeGen.java 2010-10-02 22:12:40 +09:00
Muga Nishizawa
a3accd28ea java: insert logging codes into CustomConverter.java, CustomPacker.java, CustomUnpacker.java and util.codegen programs 2010-10-02 21:28:21 +09:00
Muga Nishizawa
fc5bc84207 java: add a log4j.properties file in src/main/java/resources 2010-10-02 21:25:30 +09:00
Muga Nishizawa
d8b4051d6d java: edit pom.xml to enable to using slf4j logger 2010-10-02 21:24:22 +09:00
Muga Nishizawa
804a1cc22d Merge branch 'master' of git@github.com:msgpack/msgpack 2010-10-02 17:44:00 +09:00
Muga Nishizawa
cdd60e5f9c add a packer and unpacker for Enum types 2010-10-02 17:43:31 +09:00
frsyuki
7c76f07384 java: adds standard packer classes 2010-10-01 13:12:31 +09:00
frsyuki
a3b1ef9527 java: Packer: supports Set 2010-10-01 12:51:09 +09:00
Muga Nishizawa
0bd4150a80 java: changes several methods declared in a DynamicCodeGen class 2010-09-30 01:17:44 +09:00
Muga Nishizawa
7f7f5253f2 java: adds a test program of the DynamicCodeGen class for packing and unpacking an object that has a field anntated by @MessagePackMessage 2010-09-30 00:55:56 +09:00
advect
2a0a847634 php: update 0.3.0 2010-09-29 08:47:06 +09:00
Muga Nishizawa
92ddb37ed3 java: add test programs for DynamicCodeGenPacker, Unpacker, Converter classes 2010-09-28 22:51:38 +09:00
Fuji, Goro
01f944e6bd perl: tiny tweaks 2010-09-28 20:35:05 +09:00
Muga Nishizawa
732c8d7350 Merge branch 'master' of git@github.com:msgpack/msgpack 2010-09-28 19:12:17 +09:00
Muga Nishizawa
21678aeef5 java: moves a TestDynamicCodeGenPackerTemplate.java file to org.msgpack.util.codegen 2010-09-28 19:11:54 +09:00
tokuhirom
cda1ca35a4 Merge branch 'master' of github.com:msgpack/msgpack 2010-09-28 16:02:29 +09:00
Muga Nishizawa
923580d2cd write a simple test program for a DynamicCodeGenPacker class 2010-09-28 15:31:55 +09:00
Muga Nishizawa
190af1d32b delete old programs: org.msgpack.util.codegen.MessagePackOptional, MessagePackRequired, MessagePackUnpackable, and PackUnpackUtil classes 2010-09-28 15:24:47 +09:00
Muga Nishizawa
bffe0443f9 edit DynamicCodeGenPacker and DynamicCodeGenUnpacker class 2010-09-28 12:17:32 +09:00
Muga Nishizawa
29e99e229b Merge branch 'master' of git@github.com:msgpack/msgpack 2010-09-27 17:56:19 +09:00
Muga Nishizawa
2736b88dd5 edit Packer and Unpacker classes, and move org.msgpack.util.annotation.*.java to org.msgpack.util.codegen.*.java 2010-09-27 17:55:48 +09:00
frsyuki
e739c60e9f java: pom.xml: v0.4 2010-09-27 17:42:22 +09:00
frsyuki
1c0afbc5c5 java: loads template classes when Unpacker, MessagePackObject or ClassTemplate is loaded 2010-09-27 17:42:00 +09:00
Muga Nishizawa
ee1ba5c0f2 java: fixed a bug within a Packer class 2010-09-27 10:16:32 +09:00
Muga Nishizawa
02342ba540 java: refactor a Packer class 2010-09-27 10:10:10 +09:00
Muga Nishizawa
12a130e9bc Merge branch 'master' of git@github.com:msgpack/msgpack 2010-09-27 10:02:03 +09:00
Muga Nishizawa
dfb97e7961 java: adds several annotations in an org.msgpack.annotation package and edits Packer.java and its test program 2010-09-27 10:00:47 +09:00
tokuhirom
54e03a62bd Checking in changes prior to tagging of version 0.28.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index 82174fe..b506234 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,8 @@
+0.28
+
+    - added more tests(gfx)
+    - refactor the PP code(gfx)
+
 0.27

     - * 6d9a629 perl: modified trivial codes in PP::Unpacker(makamaka)
2010-09-27 08:35:26 +09:00
tokuhirom
ec9659ff25 Merge branch 'master' of github.com:msgpack/msgpack 2010-09-27 08:32:10 +09:00
frsyuki
0a41b253f3 java: adds templates for primitive types 2010-09-27 04:27:44 +09:00
frsyuki
002b86198c java: adds ReflectionPacker and ReflectionTemplate 2010-09-27 04:17:20 +09:00
frsyuki
7161a235f1 java: uses CustomMessage class on Packer, Unpacker and ClassTemplate 2010-09-27 03:33:21 +09:00
frsyuki
391034a785 java: adds type-conversion mechanisms 2010-09-27 03:06:06 +09:00
frsyuki
446a7fbd67 java: adds CustomMessage class (currently not implemented on Packer, Unpacker and ClassTemplate) 2010-09-27 03:05:32 +09:00
advect
2ccb09434f Merge branch 'master' of http://github.com/msgpack/msgpack 2010-09-26 12:44:05 +09:00
frsyuki
7974060a40 cpp: zone: adds msgpack_zone_swap and msgpack::zone::swap 2010-09-26 11:37:37 +09:00
frsyuki
e8abcc1765 cpp: sbuffer: check initial buffer size != 0 2010-09-26 11:36:57 +09:00
frsyuki
1be1927a1f Merge branch 'master' of github.com:msgpack/msgpack 2010-09-24 16:10:07 +09:00
tanakh
894ff71664 haskell: fix for empty constructor 2010-09-24 03:49:31 +09:00
tanakh
93bed9c5df haskell: finish template-haskell deriving implement 2010-09-24 01:24:13 +09:00
Muga Nishizawa
34c008adce java: refactor annotation-utilities 2010-09-23 20:40:50 +09:00
Muga Nishizawa
22ddd91b1f java: add several API to annotation-utilities 2010-09-23 20:38:54 +09:00
Muga Nishizawa
e121f34407 java: refactor annotation-utilities and edit those test programs 2010-09-23 17:26:31 +09:00
Muga Nishizawa
df8a3e870a java: refactor annotation-utilities 2010-09-23 16:18:23 +09:00
Muga Nishizawa
13b6708a09 java: append a code for generating a messageConvert method to annotation-utilities 2010-09-23 15:24:12 +09:00
tanakh
6aa196cf55 Merge branch 'master' of git@github.com:msgpack/msgpack 2010-09-23 00:06:26 +09:00
tanakh
142493076a haskell: TH support and refactoring 2010-09-23 00:04:34 +09:00
gfx
3d905a7a4f perl: add tests for 'extra bytes' exceptions 2010-09-22 16:14:55 +09:00
gfx
0a8a6ed168 perl: cleanup PP 2010-09-22 15:59:21 +09:00
gfx
68b6fa46e6 perl: add tests for boolean values 2010-09-22 15:28:14 +09:00
gfx
80f7c54e4d perl: make scopes 2010-09-22 15:25:08 +09:00
tokuhirom
c0e2041006 Checking in changes prior to tagging of version 0.27.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index b717a82..82174fe 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,8 @@
+0.27
+
+    - * 6d9a629 perl: modified trivial codes in PP::Unpacker(makamaka)
+    - * ead8edc modified be unpack_(u)int64 in PP(makamaka)
+
 0.26

     - fixed a serious code typo in PP(makamaka)
2010-09-22 15:12:51 +09:00
tokuhirom
f6d2cd7704 Merge branch 'master' of github.com:msgpack/msgpack 2010-09-22 15:09:03 +09:00
makamaka
6d9a629b15 perl: modified trivial codes in PP::Unpacker 2010-09-22 14:19:09 +09:00
makamaka
ead8edc7cd modified be unpack_(u)int64 in PP 2010-09-22 14:12:19 +09:00
tokuhirom
664eefdddb Checking in changes prior to tagging of version 0.26.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index 3d455cb..b717a82 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,7 @@
+0.26
+
+    - fixed a serious code typo in PP(makamaka)
+
 0.25

     (NO FEATURE CHANGES)
2010-09-20 23:40:12 +09:00
tokuhirom
220d76c974 Merge branch 'master' of github.com:msgpack/msgpack 2010-09-20 23:36:50 +09:00
makamaka
d973192b5e perl: modified a serious code typo in PP 2010-09-20 11:49:52 +09:00
tokuhirom
978bb5059f Checking in changes prior to tagging of version 0.25.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index d338cf8..3d455cb 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,7 @@
+0.25
+
+    (NO FEATURE CHANGES)
+    - oops. I failed releng.

 0.24
     - Fixed a lot of streaming unpacking issues (tokuhirom, gfx)
2010-09-20 09:54:25 +09:00
tokuhirom
f59178bc33 Checking in changes prior to tagging of version 0.24.
Changelog diff is:
2010-09-20 09:30:26 +09:00
gfx
53899cc492 perl: tweaks for Makefile.PL 2010-09-19 22:12:28 +09:00
gfx
6379d0fe0f perl: more tests for nil/true/false entities 2010-09-19 15:53:54 +09:00
gfx
a1c4d8696a Merge branch 'master' of github.com:msgpack/msgpack 2010-09-19 15:49:32 +09:00
gfx
7f42ed86f2 More tests 2010-09-19 15:47:32 +09:00
frsyuki
6bb8b4c994 Merge branch 'master' of github.com:msgpack/msgpack 2010-09-19 15:41:46 +09:00
gfx
afefbe4e56 perl: update .gitignore and MANIFEST.SKIP 2010-09-19 15:21:25 +09:00
gfx
5cd37e5505 perl: always unpacking 64 bit ints as a string on 32 bit perls 2010-09-19 15:20:03 +09:00
gfx
d6a825981d perl: fix unpacking int64_t in PP (based on makamaka's patch) 2010-09-19 15:16:08 +09:00
gfx
a1c01c6722 perl: regen README 2010-09-19 15:15:31 +09:00
gfx
8d182f1d79 perl: Changelogging 2010-09-18 16:30:07 +09:00
gfx
29707bd2ea perl: fix bootstrap 2010-09-18 16:19:16 +09:00
gfx
c2bf2a8174 perl: make pp benchmarks available 2010-09-18 16:16:51 +09:00
gfx
b402849557 perl: docs 2010-09-18 15:54:22 +09:00
gfx
cb85dcfcb8 perl: tweaks for benchmarks 2010-09-18 15:49:25 +09:00
gfx
49379140c7 perl: PERL_ONLY=1 disables XS 2010-09-18 15:14:29 +09:00
gfx
63f6c86b46 perl: add a note about 64 bit integers 2010-09-18 15:05:22 +09:00
gfx
1865898cd4 perl: Fix Makefile.PL 2010-09-18 14:58:32 +09:00
gfx
8935ecfdb8 perl: requires the latest version of Math::BigInt for PP 2010-09-18 14:56:33 +09:00
gfx
4902bed409 perl: more kind testing messages 2010-09-18 14:51:17 +09:00
gfx
e6f6aba207 perl: add portability stuff 2010-09-18 14:50:52 +09:00
gfx
bab622de25 perl: fix max depth checks in PP 2010-09-18 14:46:10 +09:00
gfx
a86c1624a7 perl: More kind error messages in PP 2010-09-18 14:38:35 +09:00
gfx
c707392a5a perl: fix int64_t unpacking in both XS and PP 2010-09-18 14:30:08 +09:00
gfx
1f07721ec4 perl: Scalar::Util is no longer used 2010-09-18 13:33:27 +09:00
gfx
4767e45035 perl: fix a test name 2010-09-18 13:18:25 +09:00
Muga Nishizawa
f2a64ed685 Merge branch 'master' of http://github.com/msgpack/msgpack 2010-09-18 10:02:46 +09:00
tokuhirom
2c9966a0a3 perl: fixed stream deserializer in pp. 2010-09-18 09:44:32 +09:00
tokuhirom
953aa95c64 perl: added failing test case for streaming unpacker with PP. 2010-09-18 06:16:26 +09:00
tokuhirom
446266776e perl: regenerate README file 2010-09-18 06:16:17 +09:00
tokuhirom
845af014dc perl: gfx is a author. 2010-09-18 06:15:51 +09:00
gfx
7c8f8703a1 Add TODOs 2010-09-17 18:26:16 +09:00
gfx
a0c18e4380 Docs 2010-09-17 18:16:33 +09:00
gfx
e8d8099563 Fix a macro redefinition 2010-09-17 18:08:34 +09:00
gfx
2c9d90d463 perl: regen README 2010-09-17 18:08:15 +09:00
tokuhirom
130d2064d5 perl: updated benchmark result! gfx++ # performance tuning 2010-09-17 15:28:24 +09:00
gfx
a10eb2a0d7 Changelogging 2010-09-17 14:02:12 +09:00
gfx
b71cc5d7ee chmod -x 2010-09-17 13:59:52 +09:00
gfx
8512f9eda1 Add .gitignore 2010-09-17 13:49:55 +09:00
gfx
80058083b8 Tweaks 2010-09-17 13:49:08 +09:00
gfx
d5a17a3c25 Fix stddata.t 2010-09-17 13:43:42 +09:00
gfx
eab7c87781 Tidy PP 2010-09-17 13:37:17 +09:00
gfx
d2962d8676 Split the boolean class into an outer module 2010-09-17 13:25:23 +09:00
gfx
5e602fb575 Fix tests 2010-09-17 13:10:54 +09:00
gfx
599964ea5f Comments 2010-09-16 21:45:06 +09:00
gfx
562de7926b More tests; some fails now :( 2010-09-16 21:38:17 +09:00
gfx
8eaed95e02 Fix an use of execute() 2010-09-16 20:44:51 +09:00
gfx
3cffd46008 Fix a comment 2010-09-16 20:41:52 +09:00
gfx
e239bfda8a Make leaktrace.t as a regular test 2010-09-16 20:36:07 +09:00
gfx
bd887b660d Preallocate hv keys 2010-09-16 20:31:34 +09:00
gfx
7c1e0ea95d Add binmode() for stream unpacking 2010-09-16 20:27:25 +09:00
gfx
afbddbfcda Fix the stream unpacker 2010-09-16 20:24:01 +09:00
Muga Nishizawa
9eeb702ca5 change an annotation-utility in Java. it allows users to pack and unpack a List object. 2010-09-15 22:28:46 +09:00
gfx
4cb6d6995f Make the code clearer 2010-09-15 15:27:26 +09:00
gfx
fe7e7a8d07 Add leaktrace tests 2010-09-15 15:26:02 +09:00
gfx
f8ee79ab72 Add failing tests 2010-09-15 15:25:48 +09:00
gfx
a11165830b More useful error messages 2010-09-15 15:06:03 +09:00
gfx
11cde61eab No debug output 2010-09-15 14:38:26 +09:00
gfx
cd862409cc Clean up 2010-09-15 14:25:50 +09:00
gfx
7644555d6b Use sv_mortalcopy() 2010-09-15 14:21:44 +09:00
gfx
07e68aa694 Fix an usage message 2010-09-15 14:20:32 +09:00
gfx
0ae206b1bb Revert "The object root can be NULL"
This reverts commit 5bdac96375.
2010-09-15 14:19:22 +09:00
gfx
5bdac96375 The object root can be NULL 2010-09-15 14:18:38 +09:00
gfx
f0e044ecd8 Cleanup 2010-09-15 14:09:03 +09:00
gfx
f32234291e Remove an useless local variable 2010-09-15 14:07:33 +09:00
gfx
83acd6529f Remove an unused user data: source (sv) 2010-09-15 14:06:10 +09:00
gfx
6a60cb4dc0 Add const 2010-09-15 13:54:18 +09:00
gfx
1de03fbe18 Tweaks for unpacker 2010-09-15 13:41:10 +09:00
gfx
0e0a2aa981 Add various integers to benchmarks 2010-09-15 13:34:18 +09:00
gfx
af73b9d11b Shortcut av_push() 2010-09-15 13:22:39 +09:00
gfx
859969241a Tweaks 2010-09-15 13:20:20 +09:00
gfx
6852a8ca9d Remove an unused function: xs_unpack_limit 2010-09-15 13:16:55 +09:00
gfx
c694f1a4a9 Tweaks 2010-09-15 13:16:13 +09:00
gfx
d36543b204 Micro optimizations 2010-09-15 13:12:17 +09:00
gfx
6981234736 Fix a possible mis-unpack on int64 2010-09-15 13:09:14 +09:00
gfx
10bf3ee9de Avoid compiler's warnings 2010-09-15 13:07:44 +09:00
gfx
9953218de1 Tidy 2010-09-15 13:03:47 +09:00
gfx
50c74103aa Avoid compiler's warnings 2010-09-15 12:56:13 +09:00
gfx
c5e15123fd Add an assertion 2010-09-15 12:52:07 +09:00
gfx
4adcdb5ba8 Remove a duplicated depth check 2010-09-15 12:51:33 +09:00
gfx
60b36ffaa3 Micro optimizations 2010-09-15 12:50:11 +09:00
gfx
d86104ed5d Tweaks 2010-09-15 12:48:23 +09:00
gfx
0f02ef20a9 Improve benchmarks 2010-09-15 12:46:11 +09:00
gfx
0768cf17b6 Taking NULL is a bug 2010-09-15 12:36:43 +09:00
gfx
197205853f Use newSV(). NEWSV() is deprecated. 2010-09-15 12:35:10 +09:00
gfx
bebcc24ab8 Depends on XSUtil 0.32 2010-09-15 12:32:01 +09:00
gfx
987248ccbb Use xshelper.h in all the C files 2010-09-15 12:31:01 +09:00
Muga Nishizawa
56ece4db0f fixed a bug the program for packing and unpacking byte[] in annotation-utility 2010-09-14 23:23:09 +09:00
Muga Nishizawa
c7f8b94ccd fixed several bugs of a verify error within annotation-utilities 2010-09-14 22:26:04 +09:00
Muga Nishizawa
95b820305a add a new test program for annotation-utilities 2010-09-14 13:34:11 +09:00
Muga Nishizawa
599b200ca5 change the version of javassist 3.12.1.GA 2010-09-12 23:04:23 +09:00
Muga Nishizawa
a9566b31be add annotation utilities for Java 2010-09-12 22:21:33 +09:00
Muga Nishizawa
f30837d726 Merge branch 'master' of http://github.com/msgpack/msgpack 2010-09-12 09:02:40 +09:00
tokuhirom
1242ffa4c6 Checking in changes prior to tagging of version 0.23.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index dd47b98..4120376 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,10 +1,15 @@
+0.23
+
+    (NO FEATURE CHANGES)
+    - fixed english docs(hanekomu++)
+
 0.22

     - fixed issue on ithreads(broken from 0.21)

 0.21

-    - doc enhancment
+    - doc enhancments
     - micro performance tuning.

 0.20
2010-09-12 05:38:15 +09:00
Muga Nishizawa
37c0347c47 Merge branch 'master' of http://github.com/msgpack/msgpack 2010-09-12 00:50:26 +09:00
tokuhirom
65befb84a0 Checking in changes prior to tagging of version 0.22.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index 5d5a5e2..dd47b98 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,7 @@
+0.22
+
+    - fixed issue on ithreads(broken from 0.21)
+
 0.21

     - doc enhancment
2010-09-12 00:11:31 +09:00
tokuhirom
a41f7ce3bd oops. 0.21 breakes ithreads support! 2010-09-12 00:09:44 +09:00
Muga Nishizawa
81ced6bf2a Merge branch 'master' of git@github.com:muga/msgpack 2010-09-11 12:13:24 +09:00
Muga Nishizawa
fa8033f998 Merge branch 'master' of http://github.com/msgpack/msgpack 2010-09-11 12:12:16 +09:00
Muga Nishizawa
19e3178d0c Merge branch 'master' of http://github.com/msgpack/msgpack 2010-09-10 22:17:06 +09:00
tokuhirom
1e6262f24f Checking in changes prior to tagging of version 0.21.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index dc3dd5c..5d5a5e2 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,8 @@
+0.21
+
+    - doc enhancment
+    - micro performance tuning.
+
 0.20

     - first production ready release with PP driver.
2010-09-10 21:27:38 +09:00
tokuhirom
beb2284440 perl: added docs for circular reference and blessed object. 2010-09-10 21:25:46 +09:00
tokuhirom
0c4f0de13d perl: inlining the small functions 2010-09-10 21:18:45 +09:00
tokuhirom
0cd31a4b96 perl: inlining utility functions 2010-09-10 21:00:27 +09:00
tokuhirom
ef0a86e7cc perl: more inline 2010-09-10 20:45:17 +09:00
tokuhirom
b79c1345b9 use gfx's standard header. 2010-09-10 20:42:40 +09:00
tokuhirom
5bb8b6f16c perl: ugpraded benchmarking script. and added result to docs. 2010-09-10 20:38:37 +09:00
tokuhirom
f6f675d1e1 updated benchmark script 2010-09-10 20:27:11 +09:00
tokuhirom
9f684e7670 Checking in changes prior to tagging of version 0.20.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index 7910882..dc3dd5c 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,7 @@
+0.20
+
+    - first production ready release with PP driver.
+
 0.16_04

     - no feature changes
2010-09-10 09:35:39 +09:00
tanakh
a998706452 haskell: update cabal file 2010-09-08 13:36:45 +09:00
tanakh
5e19bc6f84 haskell: Object is Eq, Ord, Typeable. 2010-09-07 17:35:24 +09:00
tanakh
169f287970 haskell: Now, Object is an instance of NFData. 2010-09-07 16:14:29 +09:00
tanakh
c56926428c haskell: add packToHandle' 2010-09-07 16:14:00 +09:00
tanakh
43eab5c4e5 Merge branch 'master' of git@github.com:msgpack/msgpack 2010-09-06 23:29:10 +09:00
tanakh
c6424c2ce7 haskell: nonblocking enumerator 2010-09-06 23:27:50 +09:00
tanakh
dfe19d308c haskell: add overlapping instances 2010-09-06 18:14:47 +09:00
tanakh
b75db110dc haskell: add Iteratee interface 2010-09-06 17:00:22 +09:00
tanakh
9e50ba6ec6 haskell: instance tupples and String and lazy ByteString 2010-09-06 16:33:36 +09:00
tanakh
aca2ba13c2 haskell: refactoring 2010-09-06 15:37:55 +09:00
tokuhirom
c5afe7a573 Checking in changes prior to tagging of version 0.16_04.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index a4a3e36..7910882 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,4 +1,4 @@
-0.16_03
+0.16_04

     - no feature changes
2010-09-06 14:35:41 +09:00
tokuhirom
8b90968cb1 Checking in changes prior to tagging of version 0.16_03.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index 68b58ba..a4a3e36 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,7 @@
+0.16_03
+
+    - no feature changes
+
 0.16_02

     - document enhancement(tokuhirom)
2010-09-06 14:34:48 +09:00
tokuhirom
9281dba896 Checking in changes prior to tagging of version 0.16_02.
Changelog diff is:

diff --git a/perl/Changes b/perl/Changes
index 9b061cf..68b58ba 100644
--- a/perl/Changes
+++ b/perl/Changes
@@ -1,3 +1,8 @@
+0.16_02
+
+    - document enhancement(tokuhirom)
+    - M::I::XSUtil 0.26 is broken. use 0.27.
+
 0.16_01

     - added PP version (used in cases PERL_DATA_MESSAGEPACK=pp or fail to load XS).
2010-09-06 14:34:04 +09:00
tokuhirom
c7555f1c3c Perl: added link to git repository. 2010-09-06 14:31:53 +09:00
tokuhirom
e781831032 upgraded docs 2010-09-06 14:20:54 +09:00
tokuhirom
8025895168 Checking in changes prior to tagging of version 0.16_01.
Changelog diff is:
2010-09-06 14:20:54 +09:00
tanakh
799935e44c haskel: incr version and update infos. 2010-09-06 14:03:47 +09:00
tanakh
209d8d058c forgot to remove file 2010-09-06 13:57:47 +09:00
tanakh
0368a70dd7 forgot to add file 2010-09-06 13:55:34 +09:00
Hideyuki Tanaka
c3603426de Merge branch 'master' of github.com:msgpack/msgpack 2010-09-06 01:51:18 +09:00
Hideyuki Tanaka
80db9971b5 pure haskell implementation. 2010-09-06 01:50:22 +09:00
tokuhirom
e3e771708e Merge branch 'master' of git://github.com/makamaka/msgpack
Conflicts:
	perl/Changes
2010-09-05 16:18:57 +09:00
tokuhirom
b9bca2a19f bump to 0.16 2010-09-05 16:17:19 +09:00
Muga Nishizawa
ffae70a99a Merge branch 'master' of git@github.com:muga/msgpack 2010-09-05 15:49:42 +09:00
makamaka
10ec1e48b0 modified begin process about byte order 2010-09-05 01:54:44 +09:00
makamaka
84123f5445 fallback PP configuration with c99 unspport compiler 2010-09-04 20:02:46 +09:00
makamaka
25531d8393 modified t/05_preferred_int.t for Win32 2010-09-04 19:54:12 +09:00
makamaka
adfadc542a enable PP to pack/unpack int64 in less than Perl 5.10 2010-09-04 14:35:24 +09:00
makamaka
7682e1cb57 Merge branch 'master' of git://github.com/msgpack/msgpack
Conflicts:
	perl/t/05_preferred_int.t
2010-09-03 15:09:49 +09:00
tokuhirom
1fe4109a42 fixed tests on 64bit machines with -Duselongdouble #60625 2010-09-03 14:50:01 +09:00
makamaka
b97baf4d47 added some comments in Data::MessagePack::PP 2010-09-03 12:53:56 +09:00
makamaka
f91728561f ouch, modified pod 2010-09-02 23:58:40 +09:00
makamaka
2b75d54ce1 modified pod 2010-09-02 23:56:55 +09:00
makamaka
cdc09a7d30 Changes 2010-09-02 23:52:36 +09:00
makamaka
4cc6c3e535 modified t/05_preferred_int.t for Win32 2010-09-02 23:48:57 +09:00
makamaka
8f43e033a4 removed dependency on Data::Float 2010-09-02 23:45:05 +09:00
makamaka
918dbd1926 made Makefile.PL XS/PP configurable 2010-09-02 14:37:22 +09:00
makamaka
8fc86ce7fa removed commented out codes 2010-09-02 14:33:59 +09:00
INADA Naoki
bf0cb40586 python: Add python3 category. 2010-09-02 10:13:49 +09:00
INADA Naoki
a62aefe74b python: Release 0.1.6 - Fix wrong version string. 2010-09-02 10:10:34 +09:00
INADA Naoki
138d232149 python: vesion 0.1.5 2010-09-02 09:58:50 +09:00
INADA Naoki
8fa64e3ab2 Add msgpack.version as version tuple. 2010-09-02 09:54:38 +09:00
INADA Naoki
8d0d2bd3fc python: Add test for python3 and fix found problems. 2010-09-02 02:16:28 +09:00
INADA Naoki
2146f5f623 python: Fix Unpacker.feed doesn't accept bytes on Python3. 2010-09-02 02:02:47 +09:00
INADA Naoki
623df23570 Merge branch 'master' of github.com:msgpack/msgpack 2010-09-02 01:30:32 +09:00
INADA Naoki
4a15d8b6d2 python: Support Python3. 2010-09-02 01:29:57 +09:00
makamaka
af83a62474 modified some codes for test warnings 2010-09-01 16:04:25 +09:00
makamaka
a0705a6c67 added PP backend switch into Data::MessagePack 2010-09-01 11:59:01 +09:00
makamaka
712b8eec3d added pp version 2010-09-01 11:22:43 +09:00
tokuhirom
558e9c21ed Perl: 0.15 2010-09-01 08:19:05 +09:00
tokuhirom
23a7137e6a Perl: better argument validation(patch from dankogai) 2010-08-31 23:42:32 +09:00
frsyuki
71a1cb0184 fixes compatibility with Rubinius 2010-08-31 09:29:01 +09:00
frsyuki
09b47cc536 ruby: fixes compatibility with ruby-1.8.5 2010-08-31 07:00:19 +09:00
frsyuki
b5c78de2dd ruby: converts encodings into UTF-8 on Ruby 1.9 2010-08-31 06:30:16 +09:00
frsyuki
a1bd14e516 template: casts integer types explicitly 2010-08-31 06:27:15 +09:00
Muga Nishizawa
ff0e1bbbc0 change the part for creating a new constructor within DynamicCodeGenerator 2010-08-26 17:53:29 +09:00
Muga Nishizawa
18c712cd99 object serialization with reflection and with dynamic code generation 2010-08-25 21:35:52 +09:00
advect
78f542f6c0 Update PHP Extension 2010-07-17 18:46:28 +09:00
444 changed files with 73912 additions and 4451 deletions

8
.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
*.o
*.so
ruby/Makefile
*.5
*.8
*.6
_obj
_test

View File

@@ -1,4 +1,14 @@
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

View 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

View File

@@ -1,6 +1,6 @@
AC_INIT(src/object.cpp)
AC_CONFIG_AUX_DIR(ac)
AM_INIT_AUTOMAKE(msgpack, 0.5.4)
AM_INIT_AUTOMAKE(msgpack, 0.5.6)
AC_CONFIG_HEADER(config.h)
AC_SUBST(CFLAGS)
@@ -55,7 +55,7 @@ if test "$msgpack_cv_atomic_ops" != "yes"; then
Note that gcc < 4.1 is not supported.
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"
])

View File

@@ -24,7 +24,7 @@ copy src\msgpack\pack.hpp include\msgpack\
copy src\msgpack\unpack.hpp include\msgpack\
copy src\msgpack\object.hpp include\msgpack\
copy src\msgpack\zone.hpp include\msgpack\
copy src\msgpack\type.hpp include\msgpack\type\
copy src\msgpack\type.hpp include\msgpack\
copy src\msgpack\type\bool.hpp include\msgpack\type\
copy src\msgpack\type\deque.hpp include\msgpack\type\
copy src\msgpack\type\fixint.hpp include\msgpack\type\
@@ -40,6 +40,6 @@ copy src\msgpack\type\string.hpp include\msgpack\type\
copy src\msgpack\type\vector.hpp include\msgpack\type\
copy src\msgpack\type\tuple.hpp include\msgpack\type\
copy src\msgpack\type\define.hpp include\msgpack\type\
copy src\msgpack\type\tr1\unordered_map.hpp include\msgpack\type\
copy src\msgpack\type\tr1\unordered_set.hpp include\msgpack\type\
copy src\msgpack\type\tr1\unordered_map.hpp include\msgpack\type\tr1\
copy src\msgpack\type\tr1\unordered_set.hpp include\msgpack\type\tr1\

View File

@@ -12,7 +12,7 @@ preprocess() {
fi
}
if [ "$1" == "clean" ];then
if [ "$1" = "clean" ];then
rm -f src/msgpack/type/tuple.hpp
rm -f src/msgpack/type/define.hpp
rm -f src/msgpack/zone.hpp

View File

@@ -105,9 +105,6 @@ int msgpack_pack_object(msgpack_packer* pk, msgpack_object d);
#define msgpack_pack_inline_func_cint(name) \
inline int msgpack_pack ## name
#define msgpack_pack_inline_func_cint(name) \
inline int msgpack_pack ## name
#define msgpack_pack_inline_func_fixint(name) \
inline int msgpack_pack_fix ## name

View File

@@ -28,9 +28,13 @@ class sbuffer : public msgpack_sbuffer {
public:
sbuffer(size_t initsz = MSGPACK_SBUFFER_INIT_SIZE)
{
base::data = (char*)::malloc(initsz);
if(!base::data) {
throw std::bad_alloc();
if(initsz == 0) {
base::data = NULL;
} else {
base::data = (char*)::malloc(initsz);
if(!base::data) {
throw std::bad_alloc();
}
}
base::size = 0;
@@ -80,7 +84,7 @@ public:
private:
void expand_buffer(size_t len)
{
size_t nsize = (base::alloc) ?
size_t nsize = (base::alloc > 0) ?
base::alloc * 2 : MSGPACK_SBUFFER_INIT_SIZE;
while(nsize < base::size + len) { nsize *= 2; }

View File

@@ -30,7 +30,7 @@ namespace msgpack {
inline float& operator>> (object o, float& v)
{
if(o.type != type::DOUBLE) { throw type_error(); }
v = o.via.dec;
v = (float)o.via.dec;
return v;
}
@@ -60,7 +60,7 @@ inline packer<Stream>& operator<< (packer<Stream>& o, const double& v)
inline void operator<< (object& o, float v)
{
o.type = type::DOUBLE;
o.via.dec = v;
o.via.dec = (double)v;
}
inline void operator<< (object& o, double v)

View File

@@ -35,11 +35,11 @@ namespace detail {
if(o.type == type::POSITIVE_INTEGER) {
if(o.via.u64 > (uint64_t)std::numeric_limits<T>::max())
{ throw type_error(); }
return o.via.u64;
return (T)o.via.u64;
} else if(o.type == type::NEGATIVE_INTEGER) {
if(o.via.i64 < (int64_t)std::numeric_limits<T>::min())
{ throw type_error(); }
return o.via.i64;
return (T)o.via.i64;
}
throw type_error();
}
@@ -51,7 +51,7 @@ namespace detail {
if(o.type == type::POSITIVE_INTEGER) {
if(o.via.u64 > (uint64_t)std::numeric_limits<T>::max())
{ throw type_error(); }
return o.via.u64;
return (T)o.via.u64;
}
throw type_error();
}

View File

@@ -44,7 +44,7 @@ inline void operator<< (object::with_zone& o, const std::string& v)
o.type = type::RAW;
char* ptr = (char*)o.zone->malloc(v.size());
o.via.raw.ptr = ptr;
o.via.raw.size = v.size();
o.via.raw.size = (uint32_t)v.size();
memcpy(ptr, v.data(), v.size());
}
@@ -52,7 +52,7 @@ inline void operator<< (object& o, const std::string& v)
{
o.type = type::RAW;
o.via.raw.ptr = v.data();
o.via.raw.size = v.size();
o.via.raw.size = (uint32_t)v.size();
}

View File

@@ -258,17 +258,7 @@ inline object unpacker::data()
inline zone* unpacker::release_zone()
{
if(!msgpack_unpacker_flush_zone(this)) {
throw std::bad_alloc();
}
zone* r = new zone();
msgpack_zone old = *base::z;
*base::z = *r;
*static_cast<msgpack_zone*>(r) = old;
return r;
return static_cast<msgpack::zone*>(msgpack_unpacker_release_zone(static_cast<msgpack_unpacker*>(this)));
}
inline void unpacker::reset_zone()

View File

@@ -1,7 +1,7 @@
/*
* MessagePack for C memory pool implementation
*
* Copyright (C) 2008-2009 FURUHASHI Sadayuki
* 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.
@@ -73,6 +73,8 @@ static inline void* msgpack_zone_malloc_no_align(msgpack_zone* zone, size_t size
static inline bool msgpack_zone_push_finalizer(msgpack_zone* zone,
void (*func)(void* data), void* data);
static inline void msgpack_zone_swap(msgpack_zone* a, msgpack_zone* b);
bool msgpack_zone_is_empty(msgpack_zone* zone);
void msgpack_zone_clear(msgpack_zone* zone);
@@ -129,6 +131,13 @@ bool msgpack_zone_push_finalizer(msgpack_zone* zone,
return true;
}
void msgpack_zone_swap(msgpack_zone* a, msgpack_zone* b)
{
msgpack_zone tmp = *a;
*a = *b;
*b = tmp;
}
#ifdef __cplusplus
}

View File

@@ -1,7 +1,7 @@
//
// MessagePack for C++ memory pool
//
// Copyright (C) 2008-2009 FURUHASHI Sadayuki
// 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.
@@ -43,6 +43,8 @@ public:
void clear();
void swap(zone& o);
<%0.upto(GENERATION_LIMIT) {|i|%>
template <typename T<%1.upto(i) {|j|%>, typename A<%=j%><%}%>>
T* allocate(<%=(1..i).map{|j|"A#{j} a#{j}"}.join(', ')%>);
@@ -111,6 +113,11 @@ inline void zone::clear()
msgpack_zone_clear(this);
}
inline void zone::swap(zone& o)
{
msgpack_zone_swap(this, &o);
}
template <typename T>
void zone::object_destructor(void* obj)
{

View File

@@ -164,7 +164,7 @@ void msgpack_object_print(FILE* out, msgpack_object o)
default:
// FIXME
fprintf(out, "#<UNKNOWN %hu %"PRIu64">", o.type, o.via.u64);
fprintf(out, "#<UNKNOWN %i %"PRIu64">", o.type, o.via.u64);
}
}

View File

@@ -19,6 +19,10 @@
#include "msgpack/unpack_define.h"
#include <stdlib.h>
#ifdef _msgpack_atomic_counter_header
#include _msgpack_atomic_counter_header
#endif
typedef struct {
msgpack_zone* z;
@@ -333,6 +337,7 @@ msgpack_zone* msgpack_unpacker_release_zone(msgpack_unpacker* mpac)
msgpack_zone* old = mpac->z;
mpac->z = r;
CTX_CAST(mpac->ctx)->user.z = mpac->z;
return old;
}

View File

@@ -1,7 +1,7 @@
AM_CPPFLAGS = -I../src
AM_C_CPPFLAGS = -I../src
AM_LDFLAGS = ../src/libmsgpack.la -lgtest_main
AM_LDFLAGS = ../src/libmsgpack.la -lgtest_main -pthread
check_PROGRAMS = \
zone \

View File

@@ -7,9 +7,21 @@ TEST(streaming, basic)
msgpack_sbuffer* buffer = msgpack_sbuffer_new();
msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write);
// 1, 2, 3, "raw", ["data"], {0.3: 0.4}
EXPECT_EQ(0, msgpack_pack_int(pk, 1));
EXPECT_EQ(0, msgpack_pack_int(pk, 2));
EXPECT_EQ(0, msgpack_pack_int(pk, 3));
EXPECT_EQ(0, msgpack_pack_raw(pk, 3));
EXPECT_EQ(0, msgpack_pack_raw_body(pk, "raw", 3));
EXPECT_EQ(0, msgpack_pack_array(pk, 1));
EXPECT_EQ(0, msgpack_pack_raw(pk, 4));
EXPECT_EQ(0, msgpack_pack_raw_body(pk, "data", 4));
EXPECT_EQ(0, msgpack_pack_map(pk, 1));
EXPECT_EQ(0, msgpack_pack_float(pk, 0.4));
EXPECT_EQ(0, msgpack_pack_double(pk, 0.8));
int max_count = 6;
msgpack_packer_free(pk);
const char* input = buffer->data;
@@ -22,36 +34,65 @@ TEST(streaming, basic)
msgpack_unpacked_init(&result);
int count = 0;
while(count < 3) {
while(count < max_count) {
bool unpacked = false;
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;
while(!unpacked) {
/* read buffer into msgpack_unapcker_buffer(&pac) upto
* msgpack_unpacker_buffer_capacity(&pac) bytes. */
memcpy(msgpack_unpacker_buffer(&pac), input, 1);
input += 1;
msgpack_unpacker_buffer_consumed(&pac, len);
EXPECT_TRUE(input <= eof);
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;
msgpack_unpacker_buffer_consumed(&pac, 1);
while(msgpack_unpacker_next(&pac, &result)) {
unpacked = 1;
msgpack_object obj = result.data;
msgpack_object e;
switch(count++) {
case 0:
EXPECT_EQ(MSGPACK_OBJECT_POSITIVE_INTEGER, obj.type);
EXPECT_EQ(1, obj.via.u64);
break;
case 1:
EXPECT_EQ(MSGPACK_OBJECT_POSITIVE_INTEGER, obj.type);
EXPECT_EQ(2, obj.via.u64);
break;
case 2:
EXPECT_EQ(MSGPACK_OBJECT_POSITIVE_INTEGER, obj.type);
EXPECT_EQ(3, obj.via.u64);
break;
case 3:
EXPECT_EQ(MSGPACK_OBJECT_RAW, obj.type);
EXPECT_EQ(std::string("raw",3), std::string(obj.via.raw.ptr, obj.via.raw.size));
break;
case 4:
EXPECT_EQ(MSGPACK_OBJECT_ARRAY, obj.type);
EXPECT_EQ(1, obj.via.array.size);
e = obj.via.array.ptr[0];
EXPECT_EQ(MSGPACK_OBJECT_RAW, e.type);
EXPECT_EQ(std::string("data",4), std::string(e.via.raw.ptr, e.via.raw.size));
break;
case 5:
EXPECT_EQ(MSGPACK_OBJECT_MAP, obj.type);
EXPECT_EQ(1, obj.via.map.size);
e = obj.via.map.ptr[0].key;
EXPECT_EQ(MSGPACK_OBJECT_DOUBLE, e.type);
ASSERT_FLOAT_EQ(0.4, (float)e.via.dec);
e = obj.via.map.ptr[0].val;
EXPECT_EQ(MSGPACK_OBJECT_DOUBLE, e.type);
ASSERT_DOUBLE_EQ(0.8, e.via.dec);
break;
}
}
}
EXPECT_TRUE(input < eof);
}
msgpack_unpacker_destroy(&pac);
msgpack_unpacked_destroy(&result);
}

11
go/Makefile Normal file
View File

@@ -0,0 +1,11 @@
include $(GOROOT)/src/Make.inc
TARG=msgpack
GOFILES=pack.go unpack.go
include $(GOROOT)/src/Make.pkg
%: install %.go
$(GC) $*.go
$(LD) -o $@ $*.$O

218
go/msgpack_test.go Normal file
View File

@@ -0,0 +1,218 @@
package msgpack_test
import (
. "msgpack"
"testing"
"bytes"
"reflect"
"math"
);
func equal(lhs reflect.Value, rhs reflect.Value) bool {
{
_rhs, ok := rhs.(*reflect.InterfaceValue)
if ok { return equal(lhs, _rhs.Elem()) }
}
switch _lhs := lhs.(type) {
case *reflect.InterfaceValue:
return equal(_lhs.Elem(), rhs)
case *reflect.BoolValue:
_rhs, ok := rhs.(*reflect.BoolValue)
return ok && _lhs.Get() == _rhs.Get()
case *reflect.UintValue:
_rhs, ok := rhs.(*reflect.UintValue)
return ok && _lhs.Get() == _rhs.Get()
case *reflect.IntValue:
_rhs, ok := rhs.(*reflect.IntValue)
return ok && _lhs.Get() == _rhs.Get()
case *reflect.FloatValue:
_rhs, ok := rhs.(*reflect.FloatValue)
return ok && _lhs.Get() == _rhs.Get()
case reflect.ArrayOrSliceValue:
_rhs := rhs.(reflect.ArrayOrSliceValue)
if _lhs.Len() != _rhs.Len() { return false; }
for i := 0; i < _lhs.Len(); i++ {
if !equal(_lhs.Elem(i), _rhs.Elem(i)) { return false; }
}
return true;
case *reflect.MapValue:
_rhs := rhs.(*reflect.MapValue)
if _lhs.Len() != _rhs.Len() { return false; }
for _, k := range _lhs.Keys() {
lv, rv := _lhs.Elem(k), _rhs.Elem(k)
if lv == nil || rv == nil || !equal(lv, rv) { return false; }
}
return true;
}
return false;
}
func TestPackUint8(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []uint8 { 0, 1, 2, 125, 126, 127, 128, 253, 254, 255 } {
_, err := PackUint8(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0x00, 0x01, 0x02, 0x7d, 0x7e, 0x7f, 0xcc, 0x80, 0xcc, 0xfd, 0xcc, 0xfe, 0xcc, 0xff }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackUint16(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []uint16 { 0, 1, 2, 125, 126, 127, 128, 253, 254, 255, 256, 65533, 65534, 65535 } {
_, err := PackUint16(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0x00, 0x01, 0x02, 0x7d, 0x7e, 0x7f, 0xcc, 0x80, 0xcc, 0xfd, 0xcc, 0xfe, 0xcc, 0xff, 0xcd, 0x01, 0x00, 0xcd, 0xff, 0xfd, 0xcd, 0xff, 0xfe, 0xcd, 0xff, 0xff }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackUint32(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []uint32 { 0, 1, 2, 125, 126, 127, 128, 253, 254, 255, 256, 65533, 65534, 65535, 65536, 4294967293, 4294967294, 4294967295 } {
_, err := PackUint32(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0x00, 0x01, 0x02, 0x7d, 0x7e, 0x7f, 0xcc, 0x80, 0xcc, 0xfd, 0xcc, 0xfe, 0xcc, 0xff, 0xcd, 0x01, 0x00, 0xcd, 0xff, 0xfd, 0xcd, 0xff, 0xfe, 0xcd, 0xff, 0xff, 0xce, 0x00, 0x01, 0x00, 0x00, 0xce, 0xff, 0xff, 0xff, 0xfd, 0xce, 0xff, 0xff, 0xff, 0xfe, 0xce, 0xff, 0xff, 0xff, 0xff }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackUint64(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []uint64 { 0, 1, 2, 125, 126, 127, 128, 253, 254, 255, 256, 65533, 65534, 65535, 65536, 4294967293, 4294967294, 4294967295, 4294967296, 18446744073709551613, 18446744073709551614, 18446744073709551615 } {
_, err := PackUint64(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0x00, 0x01, 0x02, 0x7d, 0x7e, 0x7f, 0xcc, 0x80, 0xcc, 0xfd, 0xcc, 0xfe, 0xcc, 0xff, 0xcd, 0x01, 0x00, 0xcd, 0xff, 0xfd, 0xcd, 0xff, 0xfe, 0xcd, 0xff, 0xff, 0xce, 0x00, 0x01, 0x00, 0x00, 0xce, 0xff, 0xff, 0xff, 0xfd, 0xce, 0xff, 0xff, 0xff, 0xfe, 0xce, 0xff, 0xff, 0xff, 0xff, 0xcf, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfd, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackInt8(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []int8 { -128, -127, -34, -33, -32, -31, 0, 1, 126, 127 } {
_, err := PackInt8(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0xd0, 0x80, 0xd0, 0x81, 0xd0, 0xde, 0xd0, 0xdf, 0xe0, 0xe1, 0x00, 0x01, 0x7e, 0x7f }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackInt16(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []int16 { -32768, -32767, -131, -130, -129, -128, -127, -34, -33, -32, -31, 0, 1, 126, 127, 128, 129, 130, 32765, 32766, 32767 } {
_, err := PackInt16(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0xd1, 0x80, 0x00, 0xd1, 0x80, 0x01, 0xd1, 0xff, 0x7d, 0xd1, 0xff, 0x7e, 0xd1, 0xff, 0x7f, 0xd0, 0x80, 0xd0, 0x81, 0xd0, 0xde, 0xd0, 0xdf, 0xe0, 0xe1, 0x00, 0x01, 0x7e, 0x7f, 0xd1, 0x00, 0x80, 0xd1, 0x00, 0x81, 0xd1, 0x00, 0x82, 0xd1, 0x7f, 0xfd, 0xd1, 0x7f, 0xfe, 0xd1, 0x7f, 0xff }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackInt32(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []int32 { -2147483648, -2147483647, -2147483646, -32771, -32770, -32769, -32768, -32767, -131, -130, -129, -128, -127, -34, -33, -32, -31, 0, 1, 126, 127, 128, 129, 130, 32765, 32766, 32767, 32768, 32769, 32770, 2147483645, 2147483646, 2147483647 } {
_, err := PackInt32(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0xd2, 0x80, 0x00, 0x00, 0x00, 0xd2, 0x80, 0x00, 0x00, 0x01, 0xd2, 0x80, 0x00, 0x00, 0x02, 0xd2, 0xff, 0xff, 0x7f, 0xfd, 0xd2, 0xff, 0xff, 0x7f, 0xfe, 0xd2, 0xff, 0xff, 0x7f, 0xff, 0xd1, 0x80, 0x00, 0xd1, 0x80, 0x01, 0xd1, 0xff, 0x7d, 0xd1, 0xff, 0x7e, 0xd1, 0xff, 0x7f, 0xd0, 0x80, 0xd0, 0x81, 0xd0, 0xde, 0xd0, 0xdf, 0xe0, 0xe1, 0x00, 0x01, 0x7e, 0x7f, 0xd1, 0x00, 0x80, 0xd1, 0x00, 0x81, 0xd1, 0x00, 0x82, 0xd1, 0x7f, 0xfd, 0xd1, 0x7f, 0xfe, 0xd1, 0x7f, 0xff, 0xd2, 0x00, 0x00, 0x80, 0x00, 0xd2, 0x00, 0x00, 0x80, 0x01, 0xd2, 0x00, 0x00, 0x80, 0x02, 0xd2, 0x7f, 0xff, 0xff, 0xfd, 0xd2, 0x7f, 0xff, 0xff, 0xfe, 0xd2, 0x7f, 0xff, 0xff, 0xff }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackInt64(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []int64 { -9223372036854775808, -9223372036854775807, -9223372036854775806, -2147483651, -2147483650, -2147483649, -2147483648, -2147483647, -2147483646, -32771, -32770, -32769, -32768, -32767, -131, -130, -129, -128, -127, -34, -33, -32, -31, 0, 1, 126, 127, 128, 129, 130, 32765, 32766, 32767, 32768, 32769, 32770, 2147483645, 2147483646, 2147483647, 2147483648, 2147483649, 2147483650, 4294967296, 4294967297, 4294967298 } {
_, err := PackInt64(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0xd3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xd3, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xd3, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xfd, 0xd3, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xfe, 0xd3, 0xff, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xd2, 0x80, 0x00, 0x00, 0x00, 0xd2, 0x80, 0x00, 0x00, 0x01, 0xd2, 0x80, 0x00, 0x00, 0x02, 0xd2, 0xff, 0xff, 0x7f, 0xfd, 0xd2, 0xff, 0xff, 0x7f, 0xfe, 0xd2, 0xff, 0xff, 0x7f, 0xff, 0xd1, 0x80, 0x00, 0xd1, 0x80, 0x01, 0xd1, 0xff, 0x7d, 0xd1, 0xff, 0x7e, 0xd1, 0xff, 0x7f, 0xd0, 0x80, 0xd0, 0x81, 0xd0, 0xde, 0xd0, 0xdf, 0xe0, 0xe1, 0x00, 0x01, 0x7e, 0x7f, 0xd1, 0x00, 0x80, 0xd1, 0x00, 0x81, 0xd1, 0x00, 0x82, 0xd1, 0x7f, 0xfd, 0xd1, 0x7f, 0xfe, 0xd1, 0x7f, 0xff, 0xd2, 0x00, 0x00, 0x80, 0x00, 0xd2, 0x00, 0x00, 0x80, 0x01, 0xd2, 0x00, 0x00, 0x80, 0x02, 0xd2, 0x7f, 0xff, 0xff, 0xfd, 0xd2, 0x7f, 0xff, 0xff, 0xfe, 0xd2, 0x7f, 0xff, 0xff, 0xff, 0xd3, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xd3, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x01, 0xd3, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x02, 0xd3, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0xd3, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02 }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackNil(t *testing.T) {
b := &bytes.Buffer{}
nbyteswrite, err := PackNil(b)
if nbyteswrite != 1 { t.Error("nbyteswrite != 1") }
if err != nil { t.Error("err != nil") }
if bytes.Compare(b.Bytes(), []byte { 0xc0 }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackBool(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range []bool { false, true } {
nbyteswrite, err := PackBool(b, i)
if nbyteswrite != 1 { t.Error("nbyteswrite != 1") }
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0xc2, 0xc3 }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackInt32Array(t *testing.T) {
b := &bytes.Buffer{}
_, err := PackInt32Array(b, []int32 {})
if err != nil { t.Error("err != nil") }
_, err = PackInt32Array(b, []int32 { 0 })
if err != nil { t.Error("err != nil") }
_, err = PackInt32Array(b, []int32 { 0, 1 })
if err != nil { t.Error("err != nil") }
_, err = PackInt32Array(b, []int32 { 0, 1, 2 })
if err != nil { t.Error("err != nil") }
if bytes.Compare(b.Bytes(), []byte { 0x90, 0x91, 0x00, 0x92, 0x00, 0x01, 0x93, 0x00, 0x01, 0x02 }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackArray(t *testing.T) {
b := &bytes.Buffer{}
_, err := PackArray(b, reflect.NewValue([]int32 {}).(reflect.ArrayOrSliceValue))
if err != nil { t.Error("err != nil") }
_, err = PackArray(b, reflect.NewValue([]int32 { 0 }).(reflect.ArrayOrSliceValue))
if err != nil { t.Error("err != nil") }
_, err = PackArray(b, reflect.NewValue([]int32 { 0, 1 }).(reflect.ArrayOrSliceValue))
if err != nil { t.Error("err != nil") }
_, err = PackArray(b, reflect.NewValue([]int32 { 0, 1, 2 }).(reflect.ArrayOrSliceValue))
if err != nil { t.Error("err != nil") }
if bytes.Compare(b.Bytes(), []byte { 0x90, 0x91, 0x00, 0x92, 0x00, 0x01, 0x93, 0x00, 0x01, 0x02 }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPackMap(t *testing.T) {
b := &bytes.Buffer{}
_, err := PackMap(b, reflect.NewValue(map[int] int { 0: 1, 2: 3, 4: 5 }).(*reflect.MapValue))
if err != nil { t.Error("err != nil") }
if bytes.Compare(b.Bytes(), []byte { 0x83, 0x00, 0x01, 0x04, 0x05, 0x02, 0x03 }) != 0 { t.Error("wrong output", b.Bytes()) }
}
func TestPack(t *testing.T) {
b := &bytes.Buffer{}
for _, i := range [](interface{}) { nil, false, true, 0, 1, 2, 3, 127, -32, -1, -33, 128 } {
_, err := Pack(b, i)
if err != nil { t.Error("err != nil") }
}
if bytes.Compare(b.Bytes(), []byte { 0xc0, 0xc2, 0xc3, 0x00, 0x01, 0x02, 0x03, 0x7f, 0xf0, 0xff, 0xd0, 0xef, 0xd1, 0x00, 0x80 }) == 0 { t.Error("wrong output") }
}
func TestUnpackArray(t *testing.T) {
b := bytes.NewBuffer([]byte { 0x90, 0x91, 0x00, 0x92, 0x00, 0x01, 0x93, 0xd1, 0x00, 0x00, 0xd2, 0x00, 0x00, 0x00, 0x01, 0xd3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xdc, 0x00, 0x02, 0x00, 0x01, 0xdd, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x02, 0x03 })
for _, v := range [](interface{}) { [](interface{}) {}, [](interface{}) { int8(0) }, [](interface{}) { int8(0), int8(1) }, [](interface{}) { int16(0), int32(1), int64(2) }, [](interface{}){ int8(0), int8(1) }, [](interface{}) { int8(0), int8(1), int8(2), int8(3) } } {
retval, _, e := Unpack(b)
if e != nil { t.Error("err != nil") }
if !equal(reflect.NewValue(retval.Interface()), reflect.NewValue(v)) { t.Errorf("%s != %s", retval.Interface(), v) }
}
}
func TestUnpackInt(t *testing.T) {
b := bytes.NewBuffer([]byte { 0xff, 0xe0, 0x00, 0x01, 0x02, 0x7d, 0x7e, 0x7f, 0xd0, 0x01, 0xd0, 0x80, 0xd0, 0xff, 0xcc, 0x80, 0xcc, 0xfd, 0xcc, 0xfe, 0xcc, 0xff, 0xd1, 0x00, 0x00, 0xd1, 0x7f, 0xff, 0xd1, 0xff, 0xff, 0xcd, 0x80, 0x00, 0xcd, 0xff, 0xff, 0xd2, 0x7f, 0xff, 0xff, 0xff, 0xce, 0x7f, 0xff, 0xff, 0xff, 0xd3, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff })
for _, v := range [](interface{}) {
int8(-1), int8(-32), int8(0), int8(1), int8(2), int8(125), int8(126), int8(127), int8(1), int8(-128), int8(-1), uint8(128), uint8(253), uint8(254), uint8(255), int16(0), int16(32767), int16(-1), uint16(32768), uint16(65535), int32(2147483647), uint32(2147483647), int64(9223372036854775807), uint64(18446744073709551615) } {
retval, _, e := Unpack(b)
if e != nil { t.Error("err != nil") }
if retval.Interface() != v { t.Errorf("%u != %u", retval.Interface(), v) }
}
}
func TestUnpackFloat(t *testing.T) {
b := bytes.NewBuffer([]byte { 0xca, 0x3d, 0xcc, 0xcc, 0xcd, 0xca, 0x3e, 0x4c, 0xcc, 0xcd, 0xca, 0xbd, 0xcc, 0xcc, 0xcd, 0xca, 0xbe, 0x4c, 0xcc, 0xcd, 0xca, 0x7f, 0x80, 0x00, 0x00, 0xca, 0xff, 0x80, 0x00, 0x00, 0xca, 0xff, 0xc0, 0x00, 0x0, 0xcb, 0x3f, 0xb9, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, 0xcb, 0x3f, 0xc9, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, 0xcb, 0xbf, 0xb9, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, 0xcb, 0xbf, 0xc9, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a, 0xcb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcb, 0xcb, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcb, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })
for _, v := range [](interface{}) { float32(.1), float32(.2), float32(-.1), float32(-.2), float32(math.Inf(1)), float32(math.Inf(-1)), float32(math.NaN()), float64(.1), float64(.2), float64(-.1), float64(-.2) } {
retval, _, e := Unpack(b)
if e != nil { t.Error("err != nil") }
isnan := false
if _v, ok := v.(float64); ok {
isnan = math.IsNaN(_v)
} else if _v, ok := v.(float32); ok {
isnan = math.IsNaN(float64(_v))
}
if isnan {
if retval.Interface() == v { t.Errorf("[NaN] %u == %u", retval.Interface(), v) }
} else {
if retval.Interface() != v { t.Errorf("%u != %u", retval.Interface(), v) }
}
}
}

591
go/pack.go Normal file
View File

@@ -0,0 +1,591 @@
package msgpack
import (
"io"
"os"
"unsafe"
"reflect"
);
// Packs a given value and writes it into the specified writer.
func PackUint8(writer io.Writer, value uint8) (n int, err os.Error) {
if value < 128 {
return writer.Write([]byte { byte(value) })
}
return writer.Write([]byte { 0xcc, byte(value) })
}
// Packs a given value and writes it into the specified writer.
func PackUint16(writer io.Writer, value uint16) (n int, err os.Error) {
if value < 128 {
return writer.Write([]byte { byte(value) })
} else if value < 256 {
return writer.Write([]byte { 0xcc, byte(value) })
}
return writer.Write([]byte { 0xcd, byte(value >> 8), byte(value) })
}
// Packs a given value and writes it into the specified writer.
func PackUint32(writer io.Writer, value uint32) (n int, err os.Error) {
if value < 128 {
return writer.Write([]byte { byte(value) })
} else if value < 256 {
return writer.Write([]byte { 0xcc, byte(value) })
} else if value < 65536 {
return writer.Write([]byte { 0xcd, byte(value >> 8), byte(value) })
}
return writer.Write([]byte { 0xce, byte(value >> 24), byte(value >> 16), byte(value >> 8), byte(value) })
}
// Packs a given value and writes it into the specified writer.
func PackUint64(writer io.Writer, value uint64) (n int, err os.Error) {
if value < 128 {
return writer.Write([]byte { byte(value) })
} else if value < 256 {
return writer.Write([]byte { 0xcc, byte(value) })
} else if value < 65536 {
return writer.Write([]byte { 0xcd, byte(value >> 8), byte(value) })
} else if value < 4294967296 {
return writer.Write([]byte { 0xce, byte(value >> 24), byte(value >> 16), byte(value >> 8), byte(value) })
}
return writer.Write([]byte { 0xcf, byte(value >> 56), byte(value >> 48), byte(value >> 40), byte(value >> 32), byte(value >> 24), byte(value >> 16), byte(value >> 8), byte(value) })
}
func PackUint(writer io.Writer, value uint) (n int, err os.Error) {
// Packs a given value and writes it into the specified writer.
switch unsafe.Sizeof(value) {
case 4:
return PackUint32(writer, *(*uint32)(unsafe.Pointer(&value)))
case 8:
return PackUint64(writer, *(*uint64)(unsafe.Pointer(&value)))
}
return 0, os.ENOENT // never get here
}
// Packs a given value and writes it into the specified writer.
func PackInt8(writer io.Writer, value int8) (n int, err os.Error) {
if value < -32 {
return writer.Write([]byte { 0xd0, byte(value) })
}
return writer.Write([]byte { byte(value) })
}
// Packs a given value and writes it into the specified writer.
func PackInt16(writer io.Writer, value int16) (n int, err os.Error) {
if value < -128 || value >= 128 {
return writer.Write([]byte { 0xd1, byte(uint16(value) >> 8), byte(value) })
} else if value < -32 {
return writer.Write([]byte { 0xd0, byte(value) })
}
return writer.Write([]byte { byte(value) })
}
// Packs a given value and writes it into the specified writer.
func PackInt32(writer io.Writer, value int32) (n int, err os.Error) {
if value < -32768 || value >= 32768 {
return writer.Write([]byte { 0xd2, byte(uint32(value) >> 24), byte(uint32(value) >> 16), byte(uint32(value) >> 8), byte(value) })
} else if value < -128 {
return writer.Write([]byte { 0xd1, byte(uint32(value) >> 8), byte(value) })
} else if value < -32 {
return writer.Write([]byte { 0xd0, byte(value) })
} else if value >= 128 {
return writer.Write([]byte { 0xd1, byte(uint32(value) >> 8), byte(value) })
}
return writer.Write([]byte { byte(value) })
}
// Packs a given value and writes it into the specified writer.
func PackInt64(writer io.Writer, value int64) (n int, err os.Error) {
if value < -2147483648 || value >= 2147483648 {
return writer.Write([]byte { 0xd3, byte(uint64(value) >> 56), byte(uint64(value) >> 48), byte(uint64(value) >> 40), byte(uint64(value) >> 32), byte(uint64(value) >> 24), byte(uint64(value) >> 16), byte(uint64(value) >> 8), byte(value) })
} else if value < -32768 || value >= 32768 {
return writer.Write([]byte { 0xd2, byte(uint64(value) >> 24), byte(uint64(value) >> 16), byte(uint64(value) >> 8), byte(value) })
} else if value < -128 || value >= 128 {
return writer.Write([]byte { 0xd1, byte(uint64(value) >> 8), byte(value) })
} else if value < -32 {
return writer.Write([]byte { 0xd0, byte(value) })
}
return writer.Write([]byte { byte(value) })
}
// Packs a given value and writes it into the specified writer.
func PackInt(writer io.Writer, value int) (n int, err os.Error) {
switch unsafe.Sizeof(value) {
case 4:
return PackInt32(writer, *(*int32)(unsafe.Pointer(&value)))
case 8:
return PackInt64(writer, *(*int64)(unsafe.Pointer(&value)))
}
return 0, os.ENOENT // never get here
}
// Packs a given value and writes it into the specified writer.
func PackNil(writer io.Writer) (n int, err os.Error) {
return writer.Write([]byte{ 0xc0 })
}
// Packs a given value and writes it into the specified writer.
func PackBool(writer io.Writer, value bool) (n int, err os.Error) {
var code byte;
if value {
code = 0xc3
} else {
code = 0xc2
}
return writer.Write([]byte{ code })
}
// Packs a given value and writes it into the specified writer.
func PackFloat32(writer io.Writer, value float32) (n int, err os.Error) {
return PackUint32(writer, *(*uint32)(unsafe.Pointer(&value)))
}
// Packs a given value and writes it into the specified writer.
func PackFloat64(writer io.Writer, value float64) (n int, err os.Error) {
return PackUint64(writer, *(*uint64)(unsafe.Pointer(&value)))
}
// Packs a given value and writes it into the specified writer.
func PackBytes(writer io.Writer, value []byte) (n int, err os.Error) {
if len(value) < 32 {
n1, err := writer.Write([]byte { 0xa0 | uint8(len(value)) })
if err != nil { return n1, err }
n2, err := writer.Write(value)
return n1 + n2, err
} else if len(value) < 65536 {
n1, err := writer.Write([]byte { 0xda, byte(len(value) >> 16), byte(len(value)) })
if err != nil { return n1, err }
n2, err := writer.Write(value)
return n1 + n2, err
}
n1, err := writer.Write([]byte { 0xdb, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n1, err }
n2, err := writer.Write(value)
return n1 + n2, err
}
// Packs a given value and writes it into the specified writer.
func PackUint16Array(writer io.Writer, value []uint16) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint16(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint16(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint16(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackUint32Array(writer io.Writer, value []uint32) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint32(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint32(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint32(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackUint64Array(writer io.Writer, value []uint64) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint64(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint64(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackUint64(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackUintArray(writer io.Writer, value []uint) (n int, err os.Error) {
switch unsafe.Sizeof(0) {
case 4:
return PackUint32Array(writer, *(*[]uint32)(unsafe.Pointer(&value)))
case 8:
return PackUint64Array(writer, *(*[]uint64)(unsafe.Pointer(&value)))
}
return 0, os.ENOENT // never get here
}
// Packs a given value and writes it into the specified writer.
func PackInt8Array(writer io.Writer, value []int8) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt8(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt8(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt8(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackInt16Array(writer io.Writer, value []int16) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt16(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt16(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt16(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackInt32Array(writer io.Writer, value []int32) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt32(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt32(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt32(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackInt64Array(writer io.Writer, value []int64) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt64(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt64(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackInt64(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackIntArray(writer io.Writer, value []int) (n int, err os.Error) {
switch unsafe.Sizeof(0) {
case 4:
return PackInt32Array(writer, *(*[]int32)(unsafe.Pointer(&value)))
case 8:
return PackInt64Array(writer, *(*[]int64)(unsafe.Pointer(&value)))
}
return 0, os.ENOENT // never get here
}
// Packs a given value and writes it into the specified writer.
func PackFloat32Array(writer io.Writer, value []float32) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackFloat32(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackFloat32(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackFloat32(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackFloat64Array(writer io.Writer, value []float64) (n int, err os.Error) {
if len(value) < 16 {
n, err := writer.Write([]byte { 0x90 | byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackFloat64(writer, i)
if err != nil { return n, err }
n += _n
}
} else if len(value) < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackFloat64(writer, i)
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(len(value) >> 24), byte(len(value) >> 16), byte(len(value) >> 8), byte(len(value)) })
if err != nil { return n, err }
for _, i := range value {
_n, err := PackFloat64(writer, i)
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackArray(writer io.Writer, value reflect.ArrayOrSliceValue) (n int, err os.Error) {
{
elemType, ok := value.Type().(reflect.ArrayOrSliceType).Elem().(*reflect.UintType)
if ok && elemType.Kind() == reflect.Uint8 {
return PackBytes(writer, value.Interface().([]byte))
}
}
l := value.Len()
if l < 16 {
n, err := writer.Write([]byte { 0x90 | byte(l) })
if err != nil { return n, err }
for i := 0; i < l; i++ {
_n, err := PackValue(writer, value.Elem(i))
if err != nil { return n, err }
n += _n
}
} else if l < 65536 {
n, err := writer.Write([]byte { 0xdc, byte(l >> 8), byte(l) })
if err != nil { return n, err }
for i := 0; i < l; i++ {
_n, err := PackValue(writer, value.Elem(i))
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdd, byte(l >> 24), byte(l >> 16), byte(l >> 8), byte(l) })
if err != nil { return n, err }
for i := 0; i < l; i++ {
_n, err := PackValue(writer, value.Elem(i))
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackMap(writer io.Writer, value *reflect.MapValue) (n int, err os.Error) {
keys := value.Keys()
if value.Len() < 16 {
n, err := writer.Write([]byte { 0x80 | byte(len(keys)) })
if err != nil { return n, err }
for _, k := range keys {
_n, err := PackValue(writer, k)
if err != nil { return n, err }
n += _n
_n, err = PackValue(writer, value.Elem(k))
if err != nil { return n, err }
n += _n
}
} else if value.Len() < 65536 {
n, err := writer.Write([]byte { 0xde, byte(len(keys) >> 8), byte(len(keys)) })
if err != nil { return n, err }
for _, k := range keys {
_n, err := PackValue(writer, k)
if err != nil { return n, err }
n += _n
_n, err = PackValue(writer, value.Elem(k))
if err != nil { return n, err }
n += _n
}
} else {
n, err := writer.Write([]byte { 0xdf, byte(len(keys) >> 24), byte(len(keys) >> 16), byte(len(keys) >> 8), byte(len(keys)) })
if err != nil { return n, err }
for _, k := range keys {
_n, err := PackValue(writer, k)
if err != nil { return n, err }
n += _n
_n, err = PackValue(writer, value.Elem(k))
if err != nil { return n, err }
n += _n
}
}
return n, nil
}
// Packs a given value and writes it into the specified writer.
func PackValue(writer io.Writer, value reflect.Value) (n int, err os.Error) {
if value == nil || value.Type() == nil { return PackNil(writer) }
switch _value := value.(type) {
case *reflect.BoolValue: return PackBool(writer, _value.Get())
case *reflect.UintValue: return PackUint64(writer, _value.Get())
case *reflect.IntValue: return PackInt64(writer, _value.Get())
case *reflect.FloatValue: return PackFloat64(writer, _value.Get())
case *reflect.ArrayValue: return PackArray(writer, _value)
case *reflect.SliceValue: return PackArray(writer, _value)
case *reflect.MapValue: return PackMap(writer, _value)
case *reflect.InterfaceValue:
__value := reflect.NewValue(_value.Interface())
_, ok := __value.(*reflect.InterfaceValue)
if !ok {
return PackValue(writer, __value)
}
}
panic("unsupported type: " + value.Type().String())
}
// Packs a given value and writes it into the specified writer.
func Pack(writer io.Writer, value interface{}) (n int, err os.Error) {
if value == nil { return PackNil(writer) }
switch _value := value.(type) {
case bool: return PackBool(writer, _value)
case uint8: return PackUint8(writer, _value)
case uint16: return PackUint16(writer, _value)
case uint32: return PackUint32(writer, _value)
case uint64: return PackUint64(writer, _value)
case uint: return PackUint(writer, _value)
case int8: return PackInt8(writer, _value)
case int16: return PackInt16(writer, _value)
case int32: return PackInt32(writer, _value)
case int64: return PackInt64(writer, _value)
case int: return PackInt(writer, _value)
case float32: return PackFloat32(writer, _value)
case float64: return PackFloat64(writer, _value)
case []byte: return PackBytes(writer, _value)
case []uint16: return PackUint16Array(writer, _value)
case []uint32: return PackUint32Array(writer, _value)
case []uint64: return PackUint64Array(writer, _value)
case []uint: return PackUintArray(writer, _value)
case []int8: return PackInt8Array(writer, _value)
case []int16: return PackInt16Array(writer, _value)
case []int32: return PackInt32Array(writer, _value)
case []int64: return PackInt64Array(writer, _value)
case []int: return PackIntArray(writer, _value)
case []float32: return PackFloat32Array(writer, _value)
case []float64: return PackFloat64Array(writer, _value)
default:
return PackValue(writer, reflect.NewValue(value))
}
return 0, nil // never get here
}

288
go/unpack.go Normal file
View File

@@ -0,0 +1,288 @@
package msgpack
import (
"io"
"os"
"unsafe"
"strconv"
"reflect"
)
func readByte(reader io.Reader) (v uint8, err os.Error) {
data := [1]byte{}
_, e := reader.Read(data[0:])
if e != nil { return 0, e }
return data[0], nil
}
func readUint16(reader io.Reader) (v uint16, n int, err os.Error) {
data := [2]byte{}
n, e := reader.Read(data[0:])
if e != nil { return 0, n, e }
return (uint16(data[0]) << 8) | uint16(data[1]), n, nil
}
func readUint32(reader io.Reader) (v uint32, n int, err os.Error) {
data := [4]byte{}
n, e := reader.Read(data[0:])
if e != nil { return 0, n, e }
return (uint32(data[0]) << 24) | (uint32(data[1]) << 16) | (uint32(data[2]) << 8) | uint32(data[3]), n, nil
}
func readUint64(reader io.Reader) (v uint64, n int, err os.Error) {
data := [8]byte{}
n, e := reader.Read(data[0:])
if e != nil { return 0, n, e }
return (uint64(data[0]) << 56) | (uint64(data[1]) << 48) | (uint64(data[2]) << 40) | (uint64(data[3]) << 32) | (uint64(data[4]) << 24) | (uint64(data[5]) << 16) | (uint64(data[6]) << 8) | uint64(data[7]), n, nil
}
func readInt16(reader io.Reader) (v int16, n int, err os.Error) {
data := [2]byte{}
n, e := reader.Read(data[0:])
if e != nil { return 0, n, e }
return (int16(data[0]) << 8) | int16(data[1]), n, nil
}
func readInt32(reader io.Reader) (v int32, n int, err os.Error) {
data := [4]byte{}
n, e := reader.Read(data[0:])
if e != nil { return 0, n, e }
return (int32(data[0]) << 24) | (int32(data[1]) << 16) | (int32(data[2]) << 8) | int32(data[3]), n, nil
}
func readInt64(reader io.Reader) (v int64, n int, err os.Error) {
data := [8]byte{}
n, e := reader.Read(data[0:])
if e != nil { return 0, n, e }
return (int64(data[0]) << 56) | (int64(data[1]) << 48) | (int64(data[2]) << 40) | (int64(data[3]) << 32) | (int64(data[4]) << 24) | (int64(data[5]) << 16) | (int64(data[6]) << 8) | int64(data[7]), n, nil
}
func unpackArray(reader io.Reader, nelems uint) (v reflect.Value, n int, err os.Error) {
retval := make([]interface{}, nelems)
nbytesread := 0
var i uint
for i = 0; i < nelems; i++ {
v, n, e := Unpack(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval[i] = v.Interface()
}
return reflect.NewValue(retval), nbytesread, nil
}
func unpackArrayReflected(reader io.Reader, nelems uint) (v reflect.Value, n int, err os.Error) {
retval := make([]reflect.Value, nelems)
nbytesread := 0
var i uint
for i = 0; i < nelems; i++ {
v, n, e := UnpackReflected(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval[i] = v
}
return reflect.NewValue(retval), nbytesread, nil
}
func unpackMap(reader io.Reader, nelems uint) (v reflect.Value, n int, err os.Error) {
retval := make(map [interface{}] interface{})
nbytesread := 0
var i uint
for i = 0; i < nelems; i++ {
k, n, e := Unpack(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
v, n, e := Unpack(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval[k.Interface()] = v.Interface()
}
return reflect.NewValue(retval), nbytesread, nil
}
func unpackMapReflected(reader io.Reader, nelems uint) (v reflect.Value, n int, err os.Error) {
retval := make(map [reflect.Value] reflect.Value)
nbytesread := 0
var i uint
for i = 0; i < nelems; i++ {
k, n, e := UnpackReflected(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
v, n, e := UnpackReflected(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval[k] = v
}
return reflect.NewValue(retval), nbytesread, nil
}
func unpack(reader io.Reader, reflected bool) (v reflect.Value, n int, err os.Error) {
var retval reflect.Value
var nbytesread int = 0
c, e := readByte(reader)
if e != nil { return nil, 0, e }
nbytesread += 1
if c < 0x80 || c >= 0xe0 {
retval = reflect.NewValue(int8(c))
} else if c >= 0x80 && c <= 0x8f {
if reflected {
retval, n, e = unpackMapReflected(reader, uint(c & 0xf))
} else {
retval, n, e = unpackMap(reader, uint(c & 0xf))
}
nbytesread += n
if e != nil { return nil, nbytesread, e }
nbytesread += n
} else if c >= 0x90 && c <= 0x9f {
if reflected {
retval, n, e = unpackArrayReflected(reader, uint(c & 0xf))
} else {
retval, n, e = unpackArray(reader, uint(c & 0xf))
}
nbytesread += n
if e != nil { return nil, nbytesread, e }
nbytesread += n
} else if c >= 0xa0 && c <= 0xbf {
data := make([]byte, c & 0xf);
n, e := reader.Read(data)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
} else {
switch c {
case 0xc0: retval = reflect.NewValue(nil)
case 0xc2: retval = reflect.NewValue(false)
case 0xc3: retval = reflect.NewValue(true)
case 0xca:
data, n, e := readUint32(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(*(*float32)(unsafe.Pointer(&data)))
case 0xcb:
data, n, e := readUint64(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(*(*float64)(unsafe.Pointer(&data)))
case 0xcc:
data, e := readByte(reader)
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(uint8(data))
nbytesread += 1
case 0xcd:
data, n, e := readUint16(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
case 0xce:
data, n, e := readUint32(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
case 0xcf:
data, n, e := readUint64(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
case 0xd0:
data, e := readByte(reader)
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(int8(data))
nbytesread += 1
case 0xd1:
data, n, e := readInt16(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
case 0xd2:
data, n, e := readInt32(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
case 0xd3:
data, n, e := readInt64(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
case 0xda:
nbytestoread, n, e := readUint16(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
data := make([]byte, nbytestoread)
n, e = reader.Read(data)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
case 0xdb:
nbytestoread, n, e := readUint32(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
data := make([]byte, nbytestoread)
n, e = reader.Read(data)
nbytesread += n
if e != nil { return nil, nbytesread, e }
retval = reflect.NewValue(data)
case 0xdc:
nelemstoread, n, e := readUint16(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
if reflected {
retval, n, e = unpackArrayReflected(reader, uint(nelemstoread))
} else {
retval, n, e = unpackArray(reader, uint(nelemstoread))
}
nbytesread += n
if e != nil { return nil, nbytesread, e }
case 0xdd:
nelemstoread, n, e := readUint32(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
if reflected {
retval, n, e = unpackArrayReflected(reader, uint(nelemstoread))
} else {
retval, n, e = unpackArray(reader, uint(nelemstoread))
}
nbytesread += n
if e != nil { return nil, nbytesread, e }
case 0xde:
nelemstoread, n, e := readUint16(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
if reflected {
retval, n, e = unpackMapReflected(reader, uint(nelemstoread))
} else {
retval, n, e = unpackMap(reader, uint(nelemstoread))
}
nbytesread += n
if e != nil { return nil, nbytesread, e }
case 0xdf:
nelemstoread, n, e := readUint32(reader)
nbytesread += n
if e != nil { return nil, nbytesread, e }
if reflected {
retval, n, e = unpackMapReflected(reader, uint(nelemstoread))
} else {
retval, n, e = unpackMap(reader, uint(nelemstoread))
}
nbytesread += n
if e != nil { return nil, nbytesread, e }
default:
panic("unsupported code: " + strconv.Itoa(int(c)))
}
}
return retval, nbytesread, nil
}
// Reads a value from the reader, unpack and returns it.
func Unpack(reader io.Reader) (v reflect.Value, n int, err os.Error) {
return unpack(reader, false)
}
// Reads unpack a value from the reader, unpack and returns it. When the
// value is an array or map, leaves the elements wrapped by corresponding
// wrapper objects defined in reflect package.
func UnpackReflected(reader io.Reader) (v reflect.Value, n int, err os.Error) {
return unpack(reader, true)
}

View File

@@ -1,4 +1,4 @@
Copyright (c) 2009, Hideyuki Tanaka
Copyright (c) 2009-2010, Hideyuki Tanaka
All rights reserved.
Redistribution and use in source and binary forms, with or without

View File

@@ -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);
}

View File

@@ -1,32 +1,50 @@
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
Name: msgpack
Version: 0.6.1.1
Synopsis: A Haskell implementation of 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
A Haskell implementation of MessagePack <http://msgpack.org/>
library
build-depends: base>=4 && <5, mtl, bytestring
ghc-options: -O2 -Wall
hs-source-dirs: src
extra-libraries: msgpackc
License: BSD3
License-File: LICENSE
Copyright: Copyright (c) 2009-2011, Hideyuki Tanaka
Category: Data
Author: Hideyuki Tanaka
Maintainer: Hideyuki Tanaka <tanaka.hideyuki@gmail.com>
Homepage: http://github.com/msgpack/msgpack
Stability: Experimental
Cabal-Version: >= 1.6
Build-Type: Simple
Extra-source-files:
test/Test.hs
test/UserData.hs
Library
Build-depends: base >=4 && <5,
transformers >= 0.2 && < 0.3,
bytestring >= 0.9 && < 0.10,
text >= 0.11 && < 0.12,
vector >= 0.7 && < 0.8,
attoparsec >= 0.8 && < 0.9,
binary >= 0.5.0 && < 0.5.1,
data-binary-ieee754 >= 0.4 && < 0.5,
deepseq >= 1.1 && <1.2,
template-haskell >= 2.4 && < 2.6
Ghc-options: -Wall
Hs-source-dirs: src
Exposed-modules:
Data.MessagePack
Data.MessagePack.Base
Data.MessagePack.Class
Data.MessagePack.Feed
Data.MessagePack.Monad
Data.MessagePack.Stream
Data.MessagePack.Assoc
Data.MessagePack.Pack
Data.MessagePack.Unpack
Data.MessagePack.Object
Data.MessagePack.Derive
C-Sources:
cbits/msgpack.c
Other-modules:
Data.MessagePack.Internal.Utf8
Source-repository head
Type: git
Location: git://github.com/msgpack/msgpack.git

View File

@@ -1,7 +1,7 @@
--------------------------------------------------------------------
-- |
-- Module : Data.MessagePack
-- Copyright : (c) Hideyuki Tanaka, 2009
-- Copyright : (c) Hideyuki Tanaka, 2009-2010
-- License : BSD3
--
-- Maintainer: tanaka.hideyuki@gmail.com
@@ -13,51 +13,15 @@
--------------------------------------------------------------------
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',
module Data.MessagePack.Assoc,
module Data.MessagePack.Pack,
module Data.MessagePack.Unpack,
module Data.MessagePack.Object,
module Data.MessagePack.Derive,
) 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
import Data.MessagePack.Assoc
import Data.MessagePack.Pack
import Data.MessagePack.Unpack
import Data.MessagePack.Object
import Data.MessagePack.Derive

View File

@@ -0,0 +1,28 @@
{-# Language DeriveDataTypeable #-}
{-# Language GeneralizedNewtypeDeriving #-}
--------------------------------------------------------------------
-- |
-- Module : Data.MessagePack.Assoc
-- Copyright : (c) Daiki Handa, 2010
-- License : BSD3
--
-- Maintainer: tanaka.hideyuki@gmail.com
-- Stability : experimental
-- Portability: portable
--
-- MessagePack map labeling type
--
--------------------------------------------------------------------
module Data.MessagePack.Assoc (
Assoc(..)
) where
import Control.DeepSeq
import Data.Typeable
-- not defined for general Functor for performance reason.
-- (ie. you would want to write custom instances for each type using specialized mapM-like functions)
newtype Assoc a=Assoc{unAssoc :: a} deriving(Show,Eq,Ord,Typeable,NFData)

View File

@@ -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

View File

@@ -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

View File

@@ -0,0 +1,106 @@
{-# Language TemplateHaskell #-}
module Data.MessagePack.Derive (
derivePack,
deriveUnpack,
deriveObject,
) where
import Control.Applicative
import Control.Monad
import Language.Haskell.TH
import Data.MessagePack.Pack
import Data.MessagePack.Unpack
import Data.MessagePack.Object
deriveUnpack :: Name -> Q [Dec]
deriveUnpack typName = do
TyConI (DataD _ name _ cons _) <- reify typName
return
[ InstanceD [] (AppT (ConT ''Unpackable) (ConT name))
[ FunD 'get [Clause [] (NormalB $ ch $ map body cons) []]
]]
where
body (NormalC conName elms) =
DoE $
tupOrListP (map VarP names) (VarE 'get) ++
[ NoBindS $ AppE (VarE 'return) $ foldl AppE (ConE conName) $ map VarE names ]
where
names = zipWith (\ix _ -> mkName $ "a" ++ show (ix :: Int)) [1..] elms
body (RecC conName elms) =
body (NormalC conName $ map (\(_, b, c) -> (b, c)) elms)
ch = foldl1 (\e f -> AppE (AppE (VarE '(<|>)) e) f)
derivePack :: Name -> Q [Dec]
derivePack typName = do
TyConI (DataD _ name _ cons _) <- reify typName
return
[ InstanceD [] (AppT (ConT ''Packable) (ConT name))
[ FunD 'put (map body cons)
]]
where
body (NormalC conName elms) =
Clause
[ ConP conName $ map VarP names ]
(NormalB $ AppE (VarE 'put) $ tupOrListE $ map VarE names) []
where
names = zipWith (\ix _ -> mkName $ "a" ++ show (ix :: Int)) [1..] elms
body (RecC conName elms) =
body (NormalC conName $ map (\(_, b, c) -> (b, c)) elms)
deriveObject :: Name -> Q [Dec]
deriveObject typName = do
g <- derivePack typName
p <- deriveUnpack typName
TyConI (DataD _ name _ cons _) <- reify typName
let o = InstanceD [] (AppT (ConT ''OBJECT) (ConT name))
[ FunD 'toObject (map toObjectBody cons),
FunD 'tryFromObject [Clause [ VarP oname ]
(NormalB $ ch $ map tryFromObjectBody cons) []]]
return $ g ++ p ++ [o]
where
toObjectBody (NormalC conName elms) =
Clause
[ ConP conName $ map VarP names ]
(NormalB $ AppE (VarE 'toObject) $ tupOrListE $ map VarE names) []
where
names = zipWith (\ix _ -> mkName $ "a" ++ show (ix :: Int)) [1..] elms
toObjectBody (RecC conName elms) =
toObjectBody (NormalC conName $ map (\(_, b, c) -> (b, c)) elms)
tryFromObjectBody (NormalC conName elms) =
DoE $
tupOrListP (map VarP names) (AppE (VarE 'tryFromObject) (VarE oname)) ++
[ NoBindS $ AppE (VarE 'return) $ foldl AppE (ConE conName) $ map VarE names ]
where
names = zipWith (\ix _ -> mkName $ "a" ++ show (ix :: Int)) [1..] elms
tryFromObjectBody (RecC conName elms) =
tryFromObjectBody (NormalC conName $ map (\(_, b, c) -> (b, c)) elms)
oname = mkName "o"
ch = foldl1 (\e f -> AppE (AppE (VarE '(<|>)) e) f)
tupOrListP :: [Pat] -> Exp -> [Stmt]
tupOrListP ls e
| length ls == 0 =
let lsname = mkName "ls" in
[ BindS (VarP lsname) e
, NoBindS $ AppE (VarE 'guard) $ AppE (VarE 'null) $ SigE (VarE lsname) (AppT ListT (ConT ''())) ]
| length ls == 1 = [ BindS (ListP ls) e ]
| otherwise = [ BindS (TupP ls) e ]
tupOrListE :: [Exp] -> Exp
tupOrListE ls
| length ls == 0 = SigE (ListE []) (AppT ListT (ConT ''()))
| length ls == 1 = ListE ls
| otherwise = TupE ls

View File

@@ -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

View File

@@ -0,0 +1,28 @@
module Data.MessagePack.Internal.Utf8 (
encodeUtf8,
decodeUtf8,
skipChar,
toLBS,
fromLBS,
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
encodeUtf8 :: String -> B.ByteString
encodeUtf8 = T.encodeUtf8 . T.pack
decodeUtf8 :: B.ByteString -> String
decodeUtf8 = T.unpack . T.decodeUtf8With skipChar
skipChar :: T.OnDecodeError
skipChar _ _ = Nothing
toLBS :: B.ByteString -> BL.ByteString
toLBS bs = BL.fromChunks [bs]
fromLBS :: BL.ByteString -> B.ByteString
fromLBS = B.concat . BL.toChunks

View File

@@ -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)

View File

@@ -0,0 +1,334 @@
{-# Language TypeSynonymInstances #-}
{-# Language FlexibleInstances #-}
{-# Language IncoherentInstances #-}
{-# Language DeriveDataTypeable #-}
--------------------------------------------------------------------
-- |
-- Module : Data.MessagePack.Object
-- Copyright : (c) Hideyuki Tanaka, 2009-2010
-- License : BSD3
--
-- Maintainer: tanaka.hideyuki@gmail.com
-- Stability : experimental
-- Portability: portable
--
-- MessagePack object definition
--
--------------------------------------------------------------------
module Data.MessagePack.Object(
-- * MessagePack Object
Object(..),
-- * Serialization to and from Object
OBJECT(..),
-- Result,
) where
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Control.Monad.Trans.Error ()
import qualified Data.Attoparsec as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import Data.Typeable
import Data.MessagePack.Assoc
import Data.MessagePack.Pack
import Data.MessagePack.Unpack
import Data.MessagePack.Internal.Utf8
-- | Object Representation of MessagePack data.
data Object
= ObjectNil
| ObjectBool Bool
| ObjectInteger Int
| ObjectFloat Float
| ObjectDouble Double
| ObjectRAW B.ByteString
| ObjectArray [Object]
| ObjectMap [(Object, Object)]
deriving (Show, Eq, Ord, Typeable)
instance NFData Object where
rnf obj =
case obj of
ObjectNil -> ()
ObjectBool b -> rnf b
ObjectInteger n -> rnf n
ObjectFloat f -> rnf f
ObjectDouble d -> rnf d
ObjectRAW bs -> bs `seq` ()
ObjectArray a -> rnf a
ObjectMap m -> rnf m
instance Unpackable Object where
get =
A.choice
[ liftM ObjectInteger get
, liftM (\() -> ObjectNil) get
, liftM ObjectBool get
, liftM ObjectFloat get
, liftM ObjectDouble get
, liftM ObjectRAW get
, liftM ObjectArray get
, liftM (ObjectMap . unAssoc) get
]
instance Packable Object where
put obj =
case obj of
ObjectInteger n ->
put n
ObjectNil ->
put ()
ObjectBool b ->
put b
ObjectFloat f ->
put f
ObjectDouble d ->
put d
ObjectRAW raw ->
put raw
ObjectArray arr ->
put arr
ObjectMap m ->
put $ Assoc m
-- | The class of types serializable to and from MessagePack object
class (Unpackable a, Packable a) => OBJECT a where
-- | Encode a value to MessagePack object
toObject :: a -> Object
toObject = unpack . pack
-- | Decode a value from MessagePack object
fromObject :: Object -> a
fromObject a =
case tryFromObject a of
Left err ->
throw $ UnpackError err
Right ret ->
ret
-- | Decode a value from MessagePack object
tryFromObject :: Object -> Either String a
tryFromObject = tryUnpack . pack
instance OBJECT Object where
toObject = id
tryFromObject = Right
tryFromObjectError :: Either String a
tryFromObjectError = Left "tryFromObject: cannot cast"
instance OBJECT () where
toObject = const ObjectNil
tryFromObject ObjectNil = Right ()
tryFromObject _ = tryFromObjectError
instance OBJECT Int where
toObject = ObjectInteger
tryFromObject (ObjectInteger n) = Right n
tryFromObject _ = tryFromObjectError
instance OBJECT Bool where
toObject = ObjectBool
tryFromObject (ObjectBool b) = Right b
tryFromObject _ = tryFromObjectError
instance OBJECT Double where
toObject = ObjectDouble
tryFromObject (ObjectDouble d) = Right d
tryFromObject _ = tryFromObjectError
instance OBJECT Float where
toObject = ObjectFloat
tryFromObject (ObjectFloat f) = Right f
tryFromObject _ = tryFromObjectError
instance OBJECT String where
toObject = toObject . encodeUtf8
tryFromObject obj = liftM decodeUtf8 $ tryFromObject obj
instance OBJECT B.ByteString where
toObject = ObjectRAW
tryFromObject (ObjectRAW bs) = Right bs
tryFromObject _ = tryFromObjectError
instance OBJECT BL.ByteString where
toObject = ObjectRAW . fromLBS
tryFromObject (ObjectRAW bs) = Right $ toLBS bs
tryFromObject _ = tryFromObjectError
instance OBJECT T.Text where
toObject = ObjectRAW . T.encodeUtf8
tryFromObject (ObjectRAW bs) = Right $ T.decodeUtf8With skipChar bs
tryFromObject _ = tryFromObjectError
instance OBJECT TL.Text where
toObject = ObjectRAW . fromLBS . TL.encodeUtf8
tryFromObject (ObjectRAW bs) = Right $ TL.decodeUtf8With skipChar $ toLBS bs
tryFromObject _ = tryFromObjectError
instance OBJECT a => OBJECT [a] where
toObject = ObjectArray . map toObject
tryFromObject (ObjectArray arr) =
mapM tryFromObject arr
tryFromObject _ =
tryFromObjectError
instance (OBJECT a1, OBJECT a2) => OBJECT (a1, a2) where
toObject (a1, a2) = ObjectArray [toObject a1, toObject a2]
tryFromObject (ObjectArray arr) =
case arr of
[o1, o2] -> do
v1 <- tryFromObject o1
v2 <- tryFromObject o2
return (v1, v2)
_ ->
tryFromObjectError
tryFromObject _ =
tryFromObjectError
instance (OBJECT a1, OBJECT a2, OBJECT a3) => OBJECT (a1, a2, a3) where
toObject (a1, a2, a3) = ObjectArray [toObject a1, toObject a2, toObject a3]
tryFromObject (ObjectArray arr) =
case arr of
[o1, o2, o3] -> do
v1 <- tryFromObject o1
v2 <- tryFromObject o2
v3 <- tryFromObject o3
return (v1, v2, v3)
_ ->
tryFromObjectError
tryFromObject _ =
tryFromObjectError
instance (OBJECT a1, OBJECT a2, OBJECT a3, OBJECT a4) => OBJECT (a1, a2, a3, a4) where
toObject (a1, a2, a3, a4) = ObjectArray [toObject a1, toObject a2, toObject a3, toObject a4]
tryFromObject (ObjectArray arr) =
case arr of
[o1, o2, o3, o4] -> do
v1 <- tryFromObject o1
v2 <- tryFromObject o2
v3 <- tryFromObject o3
v4 <- tryFromObject o4
return (v1, v2, v3, v4)
_ ->
tryFromObjectError
tryFromObject _ =
tryFromObjectError
instance (OBJECT a1, OBJECT a2, OBJECT a3, OBJECT a4, OBJECT a5) => OBJECT (a1, a2, a3, a4, a5) where
toObject (a1, a2, a3, a4, a5) = ObjectArray [toObject a1, toObject a2, toObject a3, toObject a4, toObject a5]
tryFromObject (ObjectArray arr) =
case arr of
[o1, o2, o3, o4, o5] -> do
v1 <- tryFromObject o1
v2 <- tryFromObject o2
v3 <- tryFromObject o3
v4 <- tryFromObject o4
v5 <- tryFromObject o5
return (v1, v2, v3, v4, v5)
_ ->
tryFromObjectError
tryFromObject _ =
tryFromObjectError
instance (OBJECT a1, OBJECT a2, OBJECT a3, OBJECT a4, OBJECT a5, OBJECT a6) => OBJECT (a1, a2, a3, a4, a5, a6) where
toObject (a1, a2, a3, a4, a5, a6) = ObjectArray [toObject a1, toObject a2, toObject a3, toObject a4, toObject a5, toObject a6]
tryFromObject (ObjectArray arr) =
case arr of
[o1, o2, o3, o4, o5, o6] -> do
v1 <- tryFromObject o1
v2 <- tryFromObject o2
v3 <- tryFromObject o3
v4 <- tryFromObject o4
v5 <- tryFromObject o5
v6 <- tryFromObject o6
return (v1, v2, v3, v4, v5, v6)
_ ->
tryFromObjectError
tryFromObject _ =
tryFromObjectError
instance (OBJECT a1, OBJECT a2, OBJECT a3, OBJECT a4, OBJECT a5, OBJECT a6, OBJECT a7) => OBJECT (a1, a2, a3, a4, a5, a6, a7) where
toObject (a1, a2, a3, a4, a5, a6, a7) = ObjectArray [toObject a1, toObject a2, toObject a3, toObject a4, toObject a5, toObject a6, toObject a7]
tryFromObject (ObjectArray arr) =
case arr of
[o1, o2, o3, o4, o5, o6, o7] -> do
v1 <- tryFromObject o1
v2 <- tryFromObject o2
v3 <- tryFromObject o3
v4 <- tryFromObject o4
v5 <- tryFromObject o5
v6 <- tryFromObject o6
v7 <- tryFromObject o7
return (v1, v2, v3, v4, v5, v6, v7)
_ ->
tryFromObjectError
tryFromObject _ =
tryFromObjectError
instance (OBJECT a1, OBJECT a2, OBJECT a3, OBJECT a4, OBJECT a5, OBJECT a6, OBJECT a7, OBJECT a8) => OBJECT (a1, a2, a3, a4, a5, a6, a7, a8) where
toObject (a1, a2, a3, a4, a5, a6, a7, a8) = ObjectArray [toObject a1, toObject a2, toObject a3, toObject a4, toObject a5, toObject a6, toObject a7, toObject a8]
tryFromObject (ObjectArray arr) =
case arr of
[o1, o2, o3, o4, o5, o6, o7, o8] -> do
v1 <- tryFromObject o1
v2 <- tryFromObject o2
v3 <- tryFromObject o3
v4 <- tryFromObject o4
v5 <- tryFromObject o5
v6 <- tryFromObject o6
v7 <- tryFromObject o7
v8 <- tryFromObject o8
return (v1, v2, v3, v4, v5, v6, v7, v8)
_ ->
tryFromObjectError
tryFromObject _ =
tryFromObjectError
instance (OBJECT a1, OBJECT a2, OBJECT a3, OBJECT a4, OBJECT a5, OBJECT a6, OBJECT a7, OBJECT a8, OBJECT a9) => OBJECT (a1, a2, a3, a4, a5, a6, a7, a8, a9) where
toObject (a1, a2, a3, a4, a5, a6, a7, a8, a9) = ObjectArray [toObject a1, toObject a2, toObject a3, toObject a4, toObject a5, toObject a6, toObject a7, toObject a8, toObject a9]
tryFromObject (ObjectArray arr) =
case arr of
[o1, o2, o3, o4, o5, o6, o7, o8, o9] -> do
v1 <- tryFromObject o1
v2 <- tryFromObject o2
v3 <- tryFromObject o3
v4 <- tryFromObject o4
v5 <- tryFromObject o5
v6 <- tryFromObject o6
v7 <- tryFromObject o7
v8 <- tryFromObject o8
v9 <- tryFromObject o9
return (v1, v2, v3, v4, v5, v6, v7, v8, v9)
_ ->
tryFromObjectError
tryFromObject _ =
tryFromObjectError
instance (OBJECT a, OBJECT b) => OBJECT (Assoc [(a,b)]) where
toObject =
ObjectMap . map (\(a, b) -> (toObject a, toObject b)) . unAssoc
tryFromObject (ObjectMap mem) = do
liftM Assoc $ mapM (\(a, b) -> liftM2 (,) (tryFromObject a) (tryFromObject b)) mem
tryFromObject _ =
tryFromObjectError
instance OBJECT a => OBJECT (Maybe a) where
toObject (Just a) = toObject a
toObject Nothing = ObjectNil
tryFromObject ObjectNil = return Nothing
tryFromObject obj = liftM Just $ tryFromObject obj

View File

@@ -0,0 +1,204 @@
{-# Language FlexibleInstances #-}
{-# Language IncoherentInstances #-}
{-# Language TypeSynonymInstances #-}
--------------------------------------------------------------------
-- |
-- Module : Data.MessagePack.Pack
-- Copyright : (c) Hideyuki Tanaka, 2009-2010
-- License : BSD3
--
-- Maintainer: tanaka.hideyuki@gmail.com
-- Stability : experimental
-- Portability: portable
--
-- MessagePack Serializer using @Data.Binary.Pack@
--
--------------------------------------------------------------------
module Data.MessagePack.Pack (
-- * Serializable class
Packable(..),
-- * Simple function to pack a Haskell value
pack,
) where
import Data.Binary.Put
import Data.Binary.IEEE754
import Data.Bits
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Vector as V
import Data.MessagePack.Assoc
import Data.MessagePack.Internal.Utf8
-- | Serializable class
class Packable a where
-- | Serialize a value
put :: a -> Put
-- | Pack Haskell data to MessagePack string.
pack :: Packable a => a -> BL.ByteString
pack = runPut . put
instance Packable Int where
put n =
case n of
_ | n >= 0 && n <= 127 ->
putWord8 $ fromIntegral n
_ | n >= -32 && n <= -1 ->
putWord8 $ fromIntegral n
_ | n >= 0 && n < 0x100 -> do
putWord8 0xCC
putWord8 $ fromIntegral n
_ | n >= 0 && n < 0x10000 -> do
putWord8 0xCD
putWord16be $ fromIntegral n
_ | n >= 0 && n < 0x100000000 -> do
putWord8 0xCE
putWord32be $ fromIntegral n
_ | n >= 0 -> do
putWord8 0xCF
putWord64be $ fromIntegral n
_ | n >= -0x80 -> do
putWord8 0xD0
putWord8 $ fromIntegral n
_ | n >= -0x8000 -> do
putWord8 0xD1
putWord16be $ fromIntegral n
_ | n >= -0x80000000 -> do
putWord8 0xD2
putWord32be $ fromIntegral n
_ -> do
putWord8 0xD3
putWord64be $ fromIntegral n
instance Packable () where
put _ =
putWord8 0xC0
instance Packable Bool where
put True = putWord8 0xC3
put False = putWord8 0xC2
instance Packable Float where
put f = do
putWord8 0xCA
putFloat32be f
instance Packable Double where
put d = do
putWord8 0xCB
putFloat64be d
instance Packable String where
put = putString encodeUtf8 B.length putByteString
instance Packable B.ByteString where
put = putString id B.length putByteString
instance Packable BL.ByteString where
put = putString id (fromIntegral . BL.length) putLazyByteString
instance Packable T.Text where
put = putString T.encodeUtf8 B.length putByteString
instance Packable TL.Text where
put = putString TL.encodeUtf8 (fromIntegral . BL.length) putLazyByteString
putString :: (s -> t) -> (t -> Int) -> (t -> Put) -> s -> Put
putString cnv lf pf str = do
let bs = cnv str
case lf bs of
len | len <= 31 -> do
putWord8 $ 0xA0 .|. fromIntegral len
len | len < 0x10000 -> do
putWord8 0xDA
putWord16be $ fromIntegral len
len -> do
putWord8 0xDB
putWord32be $ fromIntegral len
pf bs
instance Packable a => Packable [a] where
put = putArray length (mapM_ put)
instance Packable a => Packable (V.Vector a) where
put = putArray V.length (V.mapM_ put)
instance (Packable a1, Packable a2) => Packable (a1, a2) where
put = putArray (const 2) f where
f (a1, a2) = put a1 >> put a2
instance (Packable a1, Packable a2, Packable a3) => Packable (a1, a2, a3) where
put = putArray (const 3) f where
f (a1, a2, a3) = put a1 >> put a2 >> put a3
instance (Packable a1, Packable a2, Packable a3, Packable a4) => Packable (a1, a2, a3, a4) where
put = putArray (const 4) f where
f (a1, a2, a3, a4) = put a1 >> put a2 >> put a3 >> put a4
instance (Packable a1, Packable a2, Packable a3, Packable a4, Packable a5) => Packable (a1, a2, a3, a4, a5) where
put = putArray (const 5) f where
f (a1, a2, a3, a4, a5) = put a1 >> put a2 >> put a3 >> put a4 >> put a5
instance (Packable a1, Packable a2, Packable a3, Packable a4, Packable a5, Packable a6) => Packable (a1, a2, a3, a4, a5, a6) where
put = putArray (const 6) f where
f (a1, a2, a3, a4, a5, a6) = put a1 >> put a2 >> put a3 >> put a4 >> put a5 >> put a6
instance (Packable a1, Packable a2, Packable a3, Packable a4, Packable a5, Packable a6, Packable a7) => Packable (a1, a2, a3, a4, a5, a6, a7) where
put = putArray (const 7) f where
f (a1, a2, a3, a4, a5, a6, a7) = put a1 >> put a2 >> put a3 >> put a4 >> put a5 >> put a6 >> put a7
instance (Packable a1, Packable a2, Packable a3, Packable a4, Packable a5, Packable a6, Packable a7, Packable a8) => Packable (a1, a2, a3, a4, a5, a6, a7, a8) where
put = putArray (const 8) f where
f (a1, a2, a3, a4, a5, a6, a7, a8) = put a1 >> put a2 >> put a3 >> put a4 >> put a5 >> put a6 >> put a7 >> put a8
instance (Packable a1, Packable a2, Packable a3, Packable a4, Packable a5, Packable a6, Packable a7, Packable a8, Packable a9) => Packable (a1, a2, a3, a4, a5, a6, a7, a8, a9) where
put = putArray (const 9) f where
f (a1, a2, a3, a4, a5, a6, a7, a8, a9) = put a1 >> put a2 >> put a3 >> put a4 >> put a5 >> put a6 >> put a7 >> put a8 >> put a9
putArray :: (a -> Int) -> (a -> Put) -> a -> Put
putArray lf pf arr = do
case lf arr of
len | len <= 15 ->
putWord8 $ 0x90 .|. fromIntegral len
len | len < 0x10000 -> do
putWord8 0xDC
putWord16be $ fromIntegral len
len -> do
putWord8 0xDD
putWord32be $ fromIntegral len
pf arr
instance (Packable k, Packable v) => Packable (Assoc [(k,v)]) where
put = putMap length (mapM_ putPair) . unAssoc
instance (Packable k, Packable v) => Packable (Assoc (V.Vector (k,v))) where
put = putMap V.length (V.mapM_ putPair) . unAssoc
putPair :: (Packable a, Packable b) => (a, b) -> Put
putPair (a, b) = put a >> put b
putMap :: (a -> Int) -> (a -> Put) -> a -> Put
putMap lf pf m = do
case lf m of
len | len <= 15 ->
putWord8 $ 0x80 .|. fromIntegral len
len | len < 0x10000 -> do
putWord8 0xDE
putWord16be $ fromIntegral len
len -> do
putWord8 0xDF
putWord32be $ fromIntegral len
pf m
instance Packable a => Packable (Maybe a) where
put Nothing = put ()
put (Just a) = put a

View File

@@ -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

View File

@@ -0,0 +1,323 @@
{-# Language FlexibleInstances #-}
{-# Language IncoherentInstances #-}
{-# Language TypeSynonymInstances #-}
{-# Language DeriveDataTypeable #-}
--------------------------------------------------------------------
-- |
-- Module : Data.MessagePack.Unpack
-- Copyright : (c) Hideyuki Tanaka, 2009-2010
-- License : BSD3
--
-- Maintainer: tanaka.hideyuki@gmail.com
-- Stability : experimental
-- Portability: portable
--
-- MessagePack Deserializer using @Data.Attoparsec@
--
--------------------------------------------------------------------
module Data.MessagePack.Unpack(
-- * MessagePack deserializer
Unpackable(..),
-- * Simple function to unpack a Haskell value
unpack,
tryUnpack,
-- * Unpack exception
UnpackError(..),
-- * ByteString utils
IsByteString(..),
) where
import Control.Exception
import Control.Monad
import qualified Data.Attoparsec as A
import Data.Binary.Get
import Data.Binary.IEEE754
import Data.Bits
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import Data.Int
import Data.Typeable
import qualified Data.Vector as V
import Data.Word
import Text.Printf
import Data.MessagePack.Assoc
import Data.MessagePack.Internal.Utf8
-- | Deserializable class
class Unpackable a where
-- | Deserialize a value
get :: A.Parser a
class IsByteString s where
toBS :: s -> B.ByteString
instance IsByteString B.ByteString where
toBS = id
instance IsByteString BL.ByteString where
toBS = B.concat . BL.toChunks
-- | The exception of unpack
data UnpackError =
UnpackError String
deriving (Show, Typeable)
instance Exception UnpackError
-- | Unpack MessagePack string to Haskell data.
unpack :: (Unpackable a, IsByteString s) => s -> a
unpack bs =
case tryUnpack bs of
Left err ->
throw $ UnpackError err
Right ret ->
ret
-- | Unpack MessagePack string to Haskell data.
tryUnpack :: (Unpackable a, IsByteString s) => s -> Either String a
tryUnpack bs =
case A.parse get (toBS bs) of
A.Fail _ _ err ->
Left err
A.Partial _ ->
Left "not enough input"
A.Done _ ret ->
Right ret
instance Unpackable Int where
get = do
c <- A.anyWord8
case c of
_ | c .&. 0x80 == 0x00 ->
return $ fromIntegral c
_ | c .&. 0xE0 == 0xE0 ->
return $ fromIntegral (fromIntegral c :: Int8)
0xCC ->
return . fromIntegral =<< A.anyWord8
0xCD ->
return . fromIntegral =<< parseUint16
0xCE ->
return . fromIntegral =<< parseUint32
0xCF ->
return . fromIntegral =<< parseUint64
0xD0 ->
return . fromIntegral =<< parseInt8
0xD1 ->
return . fromIntegral =<< parseInt16
0xD2 ->
return . fromIntegral =<< parseInt32
0xD3 ->
return . fromIntegral =<< parseInt64
_ ->
fail $ printf "invlid integer tag: 0x%02X" c
instance Unpackable () where
get = do
c <- A.anyWord8
case c of
0xC0 ->
return ()
_ ->
fail $ printf "invlid nil tag: 0x%02X" c
instance Unpackable Bool where
get = do
c <- A.anyWord8
case c of
0xC3 ->
return True
0xC2 ->
return False
_ ->
fail $ printf "invlid bool tag: 0x%02X" c
instance Unpackable Float where
get = do
c <- A.anyWord8
case c of
0xCA ->
return . runGet getFloat32be . toLBS =<< A.take 4
_ ->
fail $ printf "invlid float tag: 0x%02X" c
instance Unpackable Double where
get = do
c <- A.anyWord8
case c of
0xCB ->
return . runGet getFloat64be . toLBS =<< A.take 8
_ ->
fail $ printf "invlid double tag: 0x%02X" c
instance Unpackable String where
get = parseString (\n -> return . decodeUtf8 =<< A.take n)
instance Unpackable B.ByteString where
get = parseString A.take
instance Unpackable BL.ByteString where
get = parseString (\n -> return . toLBS =<< A.take n)
instance Unpackable T.Text where
get = parseString (\n -> return . T.decodeUtf8With skipChar =<< A.take n)
instance Unpackable TL.Text where
get = parseString (\n -> return . TL.decodeUtf8With skipChar . toLBS =<< A.take n)
parseString :: (Int -> A.Parser a) -> A.Parser a
parseString aget = do
c <- A.anyWord8
case c of
_ | c .&. 0xE0 == 0xA0 ->
aget . fromIntegral $ c .&. 0x1F
0xDA ->
aget . fromIntegral =<< parseUint16
0xDB ->
aget . fromIntegral =<< parseUint32
_ ->
fail $ printf "invlid raw tag: 0x%02X" c
instance Unpackable a => Unpackable [a] where
get = parseArray (flip replicateM get)
instance Unpackable a => Unpackable (V.Vector a) where
get = parseArray (flip V.replicateM get)
instance (Unpackable a1, Unpackable a2) => Unpackable (a1, a2) where
get = parseArray f where
f 2 = get >>= \a1 -> get >>= \a2 -> return (a1, a2)
f n = fail $ printf "wrong tupple size: expected 2 but got " n
instance (Unpackable a1, Unpackable a2, Unpackable a3) => Unpackable (a1, a2, a3) where
get = parseArray f where
f 3 = get >>= \a1 -> get >>= \a2 -> get >>= \a3 -> return (a1, a2, a3)
f n = fail $ printf "wrong tupple size: expected 3 but got " n
instance (Unpackable a1, Unpackable a2, Unpackable a3, Unpackable a4) => Unpackable (a1, a2, a3, a4) where
get = parseArray f where
f 4 = get >>= \a1 -> get >>= \a2 -> get >>= \a3 -> get >>= \a4 -> return (a1, a2, a3, a4)
f n = fail $ printf "wrong tupple size: expected 4 but got " n
instance (Unpackable a1, Unpackable a2, Unpackable a3, Unpackable a4, Unpackable a5) => Unpackable (a1, a2, a3, a4, a5) where
get = parseArray f where
f 5 = get >>= \a1 -> get >>= \a2 -> get >>= \a3 -> get >>= \a4 -> get >>= \a5 -> return (a1, a2, a3, a4, a5)
f n = fail $ printf "wrong tupple size: expected 5 but got " n
instance (Unpackable a1, Unpackable a2, Unpackable a3, Unpackable a4, Unpackable a5, Unpackable a6) => Unpackable (a1, a2, a3, a4, a5, a6) where
get = parseArray f where
f 6 = get >>= \a1 -> get >>= \a2 -> get >>= \a3 -> get >>= \a4 -> get >>= \a5 -> get >>= \a6 -> return (a1, a2, a3, a4, a5, a6)
f n = fail $ printf "wrong tupple size: expected 6 but got " n
instance (Unpackable a1, Unpackable a2, Unpackable a3, Unpackable a4, Unpackable a5, Unpackable a6, Unpackable a7) => Unpackable (a1, a2, a3, a4, a5, a6, a7) where
get = parseArray f where
f 7 = get >>= \a1 -> get >>= \a2 -> get >>= \a3 -> get >>= \a4 -> get >>= \a5 -> get >>= \a6 -> get >>= \a7 -> return (a1, a2, a3, a4, a5, a6, a7)
f n = fail $ printf "wrong tupple size: expected 7 but got " n
instance (Unpackable a1, Unpackable a2, Unpackable a3, Unpackable a4, Unpackable a5, Unpackable a6, Unpackable a7, Unpackable a8) => Unpackable (a1, a2, a3, a4, a5, a6, a7, a8) where
get = parseArray f where
f 8 = get >>= \a1 -> get >>= \a2 -> get >>= \a3 -> get >>= \a4 -> get >>= \a5 -> get >>= \a6 -> get >>= \a7 -> get >>= \a8 -> return (a1, a2, a3, a4, a5, a6, a7, a8)
f n = fail $ printf "wrong tupple size: expected 8 but got " n
instance (Unpackable a1, Unpackable a2, Unpackable a3, Unpackable a4, Unpackable a5, Unpackable a6, Unpackable a7, Unpackable a8, Unpackable a9) => Unpackable (a1, a2, a3, a4, a5, a6, a7, a8, a9) where
get = parseArray f where
f 9 = get >>= \a1 -> get >>= \a2 -> get >>= \a3 -> get >>= \a4 -> get >>= \a5 -> get >>= \a6 -> get >>= \a7 -> get >>= \a8 -> get >>= \a9 -> return (a1, a2, a3, a4, a5, a6, a7, a8, a9)
f n = fail $ printf "wrong tupple size: expected 9 but got " n
parseArray :: (Int -> A.Parser a) -> A.Parser a
parseArray aget = do
c <- A.anyWord8
case c of
_ | c .&. 0xF0 == 0x90 ->
aget . fromIntegral $ c .&. 0x0F
0xDC ->
aget . fromIntegral =<< parseUint16
0xDD ->
aget . fromIntegral =<< parseUint32
_ ->
fail $ printf "invlid array tag: 0x%02X" c
instance (Unpackable k, Unpackable v) => Unpackable (Assoc [(k,v)]) where
get = liftM Assoc $ parseMap (flip replicateM parsePair)
instance (Unpackable k, Unpackable v) => Unpackable (Assoc (V.Vector (k, v))) where
get = liftM Assoc $ parseMap (flip V.replicateM parsePair)
parsePair :: (Unpackable k, Unpackable v) => A.Parser (k, v)
parsePair = do
a <- get
b <- get
return (a, b)
parseMap :: (Int -> A.Parser a) -> A.Parser a
parseMap aget = do
c <- A.anyWord8
case c of
_ | c .&. 0xF0 == 0x80 ->
aget . fromIntegral $ c .&. 0x0F
0xDE ->
aget . fromIntegral =<< parseUint16
0xDF ->
aget . fromIntegral =<< parseUint32
_ ->
fail $ printf "invlid map tag: 0x%02X" c
instance Unpackable a => Unpackable (Maybe a) where
get =
A.choice
[ liftM Just get
, liftM (\() -> Nothing) get ]
parseUint16 :: A.Parser Word16
parseUint16 = do
b0 <- A.anyWord8
b1 <- A.anyWord8
return $ (fromIntegral b0 `shiftL` 8) .|. fromIntegral b1
parseUint32 :: A.Parser Word32
parseUint32 = do
b0 <- A.anyWord8
b1 <- A.anyWord8
b2 <- A.anyWord8
b3 <- A.anyWord8
return $ (fromIntegral b0 `shiftL` 24) .|.
(fromIntegral b1 `shiftL` 16) .|.
(fromIntegral b2 `shiftL` 8) .|.
fromIntegral b3
parseUint64 :: A.Parser Word64
parseUint64 = do
b0 <- A.anyWord8
b1 <- A.anyWord8
b2 <- A.anyWord8
b3 <- A.anyWord8
b4 <- A.anyWord8
b5 <- A.anyWord8
b6 <- A.anyWord8
b7 <- A.anyWord8
return $ (fromIntegral b0 `shiftL` 56) .|.
(fromIntegral b1 `shiftL` 48) .|.
(fromIntegral b2 `shiftL` 40) .|.
(fromIntegral b3 `shiftL` 32) .|.
(fromIntegral b4 `shiftL` 24) .|.
(fromIntegral b5 `shiftL` 16) .|.
(fromIntegral b6 `shiftL` 8) .|.
fromIntegral b7
parseInt8 :: A.Parser Int8
parseInt8 = return . fromIntegral =<< A.anyWord8
parseInt16 :: A.Parser Int16
parseInt16 = return . fromIntegral =<< parseUint16
parseInt32 :: A.Parser Int32
parseInt32 = return . fromIntegral =<< parseUint32
parseInt64 :: A.Parser Int64
parseInt64 = return . fromIntegral =<< parseUint64

View File

@@ -1,16 +1,21 @@
import Control.Monad.Trans
{-# Language OverloadedStrings #-}
import Control.Monad.IO.Class
import qualified Data.ByteString as B
import Data.MessagePack
main = do
sb <- packToString $ do
sb <- return $ packToString $ do
put [1,2,3::Int]
put (3.14 :: Double)
put "Hoge"
put ("Hoge" :: B.ByteString)
print sb
unpackFromString sb $ do
r <- unpackFromString sb $ do
arr <- get
dbl <- get
str <- get
liftIO $ print (arr :: [Int], dbl :: Double, str :: String)
return (arr :: [Int], dbl :: Double, str :: B.ByteString)
print r

View File

@@ -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

View File

@@ -1,36 +1,70 @@
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import Control.Monad
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as L
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
instance Arbitrary a => Arbitrary (Assoc a) where
arbitrary = liftM Assoc arbitrary
let f = do
res <- unpackerExecute up
when (res==1) $ do
obj <- unpackerData up
print obj
f
f
mid :: (Packable a, Unpackable a) => a -> a
mid = unpack . pack
return ()
-}
prop_mid_int a = a == mid a
where types = a :: Int
prop_mid_nil a = a == mid a
where types = a :: ()
prop_mid_bool a = a == mid a
where types = a :: Bool
prop_mid_double a = a == mid a
where types = a :: Double
prop_mid_string a = a == mid a
where types = a :: String
prop_mid_bytestring a = B.pack a == mid (B.pack a)
where types = a :: String
prop_mid_lazy_bytestring a = (L.pack a) == mid (L.pack a)
where types = a :: String
prop_mid_array_int a = a == mid a
where types = a :: [Int]
prop_mid_array_string a = a == mid a
where types = a :: [String]
prop_mid_pair2 a = a == mid a
where types = a :: (Int, Int)
prop_mid_pair3 a = a == mid a
where types = a :: (Int, Int, Int)
prop_mid_pair4 a = a == mid a
where types = a :: (Int, Int, Int, Int)
prop_mid_pair5 a = a == mid a
where types = a :: (Int, Int, Int, Int, Int)
prop_mid_list_int_double a = a == mid a
where types = a :: [(Int, Double)]
prop_mid_list_string_string a = a == mid a
where types = a :: [(String, String)]
prop_mid_map_string_int a = a == mid a
where types = a :: Assoc [(String,Int)]
main = do
bs <- packb [(1,2),(2,3),(3::Int,4::Int)]
print bs
dat <- unpackb bs
print (dat :: Result [(Int, Int)])
tests =
[ testGroup "simple"
[ testProperty "int" prop_mid_int
, testProperty "nil" prop_mid_nil
, testProperty "bool" prop_mid_bool
, testProperty "double" prop_mid_double
, testProperty "string" prop_mid_string
, testProperty "bytestring" prop_mid_bytestring
, testProperty "lazy-bytestring" prop_mid_lazy_bytestring
, testProperty "[int]" prop_mid_array_int
, testProperty "[string]" prop_mid_array_string
, testProperty "(int, int)" prop_mid_pair2
, testProperty "(int, int, int)" prop_mid_pair3
, testProperty "(int, int, int, int)" prop_mid_pair4
, testProperty "(int, int, int, int, int)" prop_mid_pair5
, testProperty "[(int, double)]" prop_mid_list_int_double
, testProperty "[(string, string)]" prop_mid_list_string_string
, testProperty "Assoc [(string, int)]" prop_mid_map_string_int
]
]
main = defaultMain tests

43
haskell/test/UserData.hs Normal file
View File

@@ -0,0 +1,43 @@
{-# Language TemplateHaskell #-}
import Data.MessagePack
import Data.MessagePack.Derive
data T
= A Int String
| B Double
deriving (Show, Eq)
$(deriveObject ''T)
data U
= C { c1 :: Int, c2 :: String }
| D { d1 :: Double }
deriving (Show, Eq)
$(deriveObject ''U)
data V
= E String | F
deriving (Show, Eq)
$(deriveObject ''V)
test :: (OBJECT a, Show a, Eq a) => a -> IO ()
test v = do
let bs = pack v
print bs
print (unpack bs == v)
let oa = toObject v
print oa
print (fromObject oa == v)
main = do
test $ A 123 "hoge"
test $ B 3.14
test $ C 123 "hoge"
test $ D 3.14
test $ E "hello"
test $ F
return ()

View File

@@ -1,5 +1,13 @@
#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
#Tue Apr 12 19:14:17 JST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.6

View File

@@ -0,0 +1,9 @@
#Mon Sep 27 07:43:27 JST 2010
activeProfiles=
eclipse.preferences.version=1
fullBuildGoals=process-test-resources
includeModules=false
resolveWorkspaceProjects=true
resourceFilterGoals=process-resources resources\:testResources
skipCompilerPlugin=true
version=1

1
java/AUTHORS Normal file
View File

@@ -0,0 +1 @@
FURUHASHI Sadayuki <frsyuki _at_ users.sourceforge.jp>

View File

@@ -1,3 +1,97 @@
Release 0.5.2 - 2011/04/23
NEW FEATURES
MSGPACK-6 Added TemplatePrecompiler program
Added built-in templates of BigDecimal and Date classes.
Added @MessagePackBeans annotation that enables you to serialize/deserialize
JavaBeans.
BUG FIXES
MSGPACK-4 Fixes the deserialization routine of Long value
IMPROVEMENTS
#35 Improves handling of ClassLoader on Javassist template builder.
MSGPACK-7 Improves compatibility with Java 1.5. Now it runs on JRE 5.
It is tested on Jenkins CI: http://ci.msgpack.org/job/java-jre5/
Release 0.5.1 - 2010/12/14
BUG FIXES
Fixes cast error on GenericArrayType
Throws MessagePackException instead of NullPointerException if target is null
on pack method.
Release 0.5.0 - 2010/12/09
NEW FEATURES
Dynamic template builder is rewritten. New ReflectionTemplateBuilder
supports DalvikVM.
Some optimization for dynamic code generator.
@MessagePackMessage accepts default filed option.
Added new field annotations: @Ignore, @Requred and @Index.
Supported pack/unpack/convertion of arrays including multidimensional arrays.
Added native pack/unpack routine of ByteBuffer. It will be zero-copy optimized
under a specific condition.
Release 0.4.3 - 2010/11/10
NEW FEATURES
Added FieldList class and MessagePack.register(Class<T>, FieldList) method
to specify optional/nullable options on runtime without annotations.
Changed annotation name: @MessagePackNullable -> @Nullable
Changed annotation name: @MessagePackOptional -> @Optional
Supported pack/unpack/convertion of enums.
Added MessagePack.unpack(buffer, T to) and MessagePackObject.convert(T to)
methods. They can unpack/convert buffer/object into existing object and
eliminate re-allocation overhead.
Release 0.4.2 - 2010/11/09
NEW FEATURES
Added MessagePackNullable annotation and Tempalte.tNullable(Template)
method.
Added <T> T MessagePackObject.unpack(Class<T>) method.
Release 0.4.1 - 2010/11/05
BUG FIXES
Fixed dynamic code generation of unpack methods
Release 0.4.0 - 2010/10/25
NEW FEATURES
Added MessagePackObject class and org.msgpack.object package that
represent unpacked (=dynamically typed) objects.
Unpacker.unpack method returns MessagePackObject instead of Object.
Added Templates class and org.msgpack.template package that provide
type conversion feature.
User-defined classes annotated with MessagePackMessage can be
pack/unpack/converted.
User-defined classes registered with MessagePack.register(Class) can be
pack/unpack/converted.
Added dynamic code generation feature for user-defined classes.
Added MessagePackOptional annotation.
Added MessagePack class that implements typical useful methods.
Release 0.3 - 2010/05/23
NEW FEATURES
Added Unbuffered API + Direct Conversion API to the Unpacker.

17
java/msgpack.iml Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_6" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.8.1" level="project" />
</component>
</module>

View File

@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.msgpack</groupId>
<artifactId>msgpack</artifactId>
<version>0.3</version>
<version>0.5.2-devel</version>
<description>MessagePack for Java</description>
<name>MessagePack for Java</name>
@@ -29,6 +29,22 @@
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
@@ -47,8 +63,8 @@
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
@@ -65,6 +81,20 @@
<connectionUrl>scm:git://github.com/msgpack/msgpack.git</connectionUrl>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
@@ -101,6 +131,13 @@
<name>MessagePack Maven2 Repository</name>
<url>http://msgpack.org/maven2</url>
</repository>
<repository>
<id>repository.jboss.org</id>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<distributionManagement>
@@ -109,12 +146,14 @@
<id>msgpack.org</id>
<name>Repository at msgpack.org</name>
<url>file://${project.build.directory}/website/maven2/</url>
<!--<url>${deploy-release-url}</url>-->
</repository>
<snapshotRepository>
<uniqueVersion>true</uniqueVersion>
<id>msgpack.org</id>
<name>Repository at msgpack.org</name>
<url>file://${project.build.directory}/website/maven2/</url>
<!--<url>${deploy-snapshot-url}</url>-->
</snapshotRepository>
</distributionManagement>

View File

@@ -0,0 +1,26 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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 abstract class AbstractTemplate implements Template {
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return convert(pac.unpackObject(), to);
}
}

View File

@@ -25,6 +25,7 @@ abstract class BufferedUnpackerImpl extends UnpackerImpl {
int offset = 0;
int filled = 0;
byte[] buffer = null;
boolean bufferReferenced = false; // TODO zero-copy buffer
private ByteBuffer castBuffer = ByteBuffer.allocate(8);
abstract boolean fill() throws IOException;
@@ -145,10 +146,10 @@ abstract class BufferedUnpackerImpl extends UnpackerImpl {
advance(3);
return (int)castBuffer.getShort(0);
case 0xd2: // signed int 32
more(4);
more(5);
castBuffer.rewind();
castBuffer.put(buffer, offset+1, 4);
advance(4);
advance(5);
return (int)castBuffer.getInt(0);
case 0xd3: // signed int 64
more(9);
@@ -214,10 +215,10 @@ abstract class BufferedUnpackerImpl extends UnpackerImpl {
advance(3);
return (long)castBuffer.getShort(0);
case 0xd2: // signed int 32
more(4);
more(5);
castBuffer.rewind();
castBuffer.put(buffer, offset+1, 4);
advance(4);
advance(5);
return (long)castBuffer.getInt(0);
case 0xd3: // signed int 64
more(9);
@@ -417,7 +418,18 @@ abstract class BufferedUnpackerImpl extends UnpackerImpl {
final byte[] unpackByteArray() throws IOException, MessageTypeException {
int length = unpackRaw();
return unpackRawBody(length);
byte[] body = unpackRawBody(length);
return body;
}
final ByteBuffer unpackByteBuffer() throws IOException, MessageTypeException {
// TODO zero-copy buffer
int length = unpackRaw();
more(length);
ByteBuffer buf = ByteBuffer.wrap(buffer, offset, length);
bufferReferenced = true; // TODO fix magical code
advance(length);
return buf;
}
final String unpackString() throws IOException, MessageTypeException {

View File

@@ -0,0 +1,23 @@
//
// 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 MessageConverter {
Object convert(MessagePackObject from, Object to) throws MessageTypeException;
}

View File

@@ -0,0 +1,160 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.msgpack.template.TemplateRegistry;
import org.msgpack.template.FieldList;
public class MessagePack {
public static byte[] pack(Object obj) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
new Packer(out).pack(obj);
} catch (IOException e) {
throw new RuntimeException(e);
}
return out.toByteArray();
}
public static void pack(OutputStream out, Object obj) throws IOException {
new Packer(out).pack(obj);
}
public static byte[] pack(Object obj, Template tmpl) throws MessageTypeException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
new Packer(out).pack(obj, tmpl);
} catch (IOException e) {
throw new RuntimeException(e);
}
return out.toByteArray();
}
public static void pack(OutputStream out, Object obj, Template tmpl) throws IOException, MessageTypeException {
new Packer(out).pack(obj, tmpl);
}
public static MessagePackObject unpack(byte[] buffer) throws MessageTypeException {
Unpacker pac = new Unpacker();
pac.wrap(buffer);
try {
return pac.unpackObject();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Object unpack(byte[] buffer, Template tmpl) throws MessageTypeException {
Unpacker pac = new Unpacker();
pac.wrap(buffer);
try {
return pac.unpack(tmpl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T unpack(byte[] buffer, Template tmpl, T to) throws MessageTypeException {
Unpacker pac = new Unpacker();
pac.wrap(buffer);
try {
return pac.unpack(tmpl, to);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T unpack(byte[] buffer, Class<T> klass) throws MessageTypeException {
Unpacker pac = new Unpacker();
pac.wrap(buffer);
try {
return pac.unpack(klass);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T unpack(byte[] buffer, T to) throws MessageTypeException {
Unpacker pac = new Unpacker();
pac.wrap(buffer);
try {
return pac.unpack(to);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static MessagePackObject unpack(InputStream in) throws IOException {
Unpacker pac = new Unpacker(in);
return pac.unpackObject();
}
public static Object unpack(InputStream in, Template tmpl) throws IOException, MessageTypeException {
Unpacker pac = new Unpacker(in);
try {
return pac.unpack(tmpl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T unpack(InputStream in, Template tmpl, T to) throws IOException, MessageTypeException {
Unpacker pac = new Unpacker(in);
try {
return pac.unpack(tmpl, to);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T unpack(InputStream in, Class<T> klass) throws IOException, MessageTypeException {
Unpacker pac = new Unpacker(in);
try {
return pac.unpack(klass);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T unpack(InputStream in, T to) throws IOException, MessageTypeException {
Unpacker pac = new Unpacker(in);
try {
return pac.unpack(to);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void register(Class<?> target) {
TemplateRegistry.register(target);
}
public static void register(Class<?> target, FieldList flist) throws NoSuchFieldException {
TemplateRegistry.register(target, flist);
}
public static void register(Class<?> target, Template tmpl) {
TemplateRegistry.register(target, tmpl);
}
}

View File

@@ -21,6 +21,7 @@ import java.util.List;
import java.util.Set;
import java.util.Map;
import java.math.BigInteger;
import org.msgpack.template.TemplateRegistry;
public abstract class MessagePackObject implements Cloneable, MessagePackable {
public boolean isNil() {
@@ -132,5 +133,28 @@ public abstract class MessagePackObject implements Cloneable, MessagePackable {
}
abstract public Object clone();
public Object convert(Template tmpl) throws MessageTypeException {
return convert(tmpl, null);
}
public <T> T convert(Template tmpl, T to) throws MessageTypeException {
return (T)tmpl.convert(this, to);
}
public <T> T convert(Class<T> klass) throws MessageTypeException {
return convert(klass, null);
}
public <T> T convert(T to) throws MessageTypeException {
return convert((Class<T>)to.getClass(), to);
}
public <T> T convert(Class<T> klass, T to) throws MessageTypeException {
if(isNil()) {
return null;
}
return (T)convert(TemplateRegistry.lookup(klass), to);
}
}

View File

@@ -0,0 +1,22 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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 MessagePackTemplateProvider {
Template getTemplate();
}

View File

@@ -0,0 +1,25 @@
//
// 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 MessagePacker {
void pack(Packer pk, Object target) throws IOException;
}

View File

@@ -23,5 +23,13 @@ public class MessageTypeException extends RuntimeException {
public MessageTypeException(String s) {
super(s);
}
public MessageTypeException(String s, Throwable t) {
super(s, t);
}
public MessageTypeException(Throwable t) {
super(t);
}
}

View File

@@ -0,0 +1,25 @@
//
// 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 MessageUnpacker {
Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException;
}

View File

@@ -21,8 +21,11 @@ import java.io.OutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.Collection;
import java.math.BigInteger;
import org.msgpack.template.TemplateRegistry;
/**
* Packer enables you to serialize objects into OutputStream.
@@ -41,8 +44,10 @@ import java.math.BigInteger;
* You can serialize objects that implements {@link MessagePackable} interface.
*/
public class Packer {
public static void load() { }
protected byte[] castBytes = new byte[9];
protected ByteBuffer castBuffer = ByteBuffer.wrap(castBytes);
//protected ByteBuffer castBuffer = ByteBuffer.wrap(castBytes);
protected OutputStream out;
public Packer(OutputStream out) {
@@ -65,7 +70,9 @@ public class Packer {
if(d < -(1<<7)) {
// signed 16
castBytes[0] = (byte)0xd1;
castBuffer.putShort(1, d);
// castBuffer.putShort(1, d);
castBytes[1] = (byte)(d >> 8);
castBytes[2] = (byte)(d >> 0);
out.write(castBytes, 0, 3);
} else {
// signed 8
@@ -85,7 +92,9 @@ public class Packer {
} else {
// unsigned 16
castBytes[0] = (byte)0xcd;
castBuffer.putShort(1, d);
// castBuffer.putShort(1, d);
castBytes[1] = (byte)(d >> 8);
castBytes[2] = (byte)(d >> 0);
out.write(castBytes, 0, 3);
}
}
@@ -97,12 +106,18 @@ public class Packer {
if(d < -(1<<15)) {
// signed 32
castBytes[0] = (byte)0xd2;
castBuffer.putInt(1, d);
// castBuffer.putInt(1, d);
castBytes[1] = (byte)(d >> 24);
castBytes[2] = (byte)(d >> 16);
castBytes[3] = (byte)(d >> 8);
castBytes[4] = (byte)(d >> 0);
out.write(castBytes, 0, 5);
} else if(d < -(1<<7)) {
// signed 16
castBytes[0] = (byte)0xd1;
castBuffer.putShort(1, (short)d);
// castBuffer.putShort(1, (short)d);
castBytes[1] = (byte)(d >> 8);
castBytes[2] = (byte)(d >> 0);
out.write(castBytes, 0, 3);
} else {
// signed 8
@@ -122,12 +137,18 @@ public class Packer {
} else if(d < (1<<16)) {
// unsigned 16
castBytes[0] = (byte)0xcd;
castBuffer.putShort(1, (short)d);
// castBuffer.putShort(1, (short)d);
castBytes[1] = (byte)(d >> 8);
castBytes[2] = (byte)(d >> 0);
out.write(castBytes, 0, 3);
} else {
// unsigned 32
castBytes[0] = (byte)0xce;
castBuffer.putInt(1, d);
// castBuffer.putInt(1, d);
castBytes[1] = (byte)(d >> 24);
castBytes[2] = (byte)(d >> 16);
castBytes[3] = (byte)(d >> 8);
castBytes[4] = (byte)(d >> 0);
out.write(castBytes, 0, 5);
}
}
@@ -140,19 +161,33 @@ public class Packer {
if(d < -(1L<<31)) {
// signed 64
castBytes[0] = (byte)0xd3;
castBuffer.putLong(1, d);
// castBuffer.putLong(1, d);
castBytes[1] = (byte)(d >> 56);
castBytes[2] = (byte)(d >> 48);
castBytes[3] = (byte)(d >> 40);
castBytes[4] = (byte)(d >> 32);
castBytes[5] = (byte)(d >> 24);
castBytes[6] = (byte)(d >> 16);
castBytes[7] = (byte)(d >> 8);
castBytes[8] = (byte)(d >> 0);
out.write(castBytes, 0, 9);
} else {
// signed 32
castBytes[0] = (byte)0xd2;
castBuffer.putInt(1, (int)d);
// castBuffer.putInt(1, (int)d);
castBytes[1] = (byte)(d >> 24);
castBytes[2] = (byte)(d >> 16);
castBytes[3] = (byte)(d >> 8);
castBytes[4] = (byte)(d >> 0);
out.write(castBytes, 0, 5);
}
} else {
if(d < -(1<<7)) {
// signed 16
castBytes[0] = (byte)0xd1;
castBuffer.putShort(1, (short)d);
// castBuffer.putShort(1, (short)d);
castBytes[1] = (byte)(d >> 8);
castBytes[2] = (byte)(d >> 0);
out.write(castBytes, 0, 3);
} else {
// signed 8
@@ -174,7 +209,9 @@ public class Packer {
} else {
// unsigned 16
castBytes[0] = (byte)0xcd;
castBuffer.putShort(1, (short)d);
// castBuffer.putShort(1, (short)d);
castBytes[1] = (byte)((d & 0x0000ff00) >> 8);
castBytes[2] = (byte)((d & 0x000000ff) >> 0);
out.write(castBytes, 0, 3);
//System.out.println("pack uint 16 "+(short)d);
}
@@ -182,12 +219,24 @@ public class Packer {
if(d < (1L<<32)) {
// unsigned 32
castBytes[0] = (byte)0xce;
castBuffer.putInt(1, (int)d);
// castBuffer.putInt(1, (int)d);
castBytes[1] = (byte)((d & 0xff000000) >> 24);
castBytes[2] = (byte)((d & 0x00ff0000) >> 16);
castBytes[3] = (byte)((d & 0x0000ff00) >> 8);
castBytes[4] = (byte)((d & 0x000000ff) >> 0);
out.write(castBytes, 0, 5);
} else {
// unsigned 64
castBytes[0] = (byte)0xcf;
castBuffer.putLong(1, d);
// castBuffer.putLong(1, d);
castBytes[1] = (byte)(d >> 56);
castBytes[2] = (byte)(d >> 48);
castBytes[3] = (byte)(d >> 40);
castBytes[4] = (byte)(d >> 32);
castBytes[5] = (byte)(d >> 24);
castBytes[6] = (byte)(d >> 16);
castBytes[7] = (byte)(d >> 8);
castBytes[8] = (byte)(d >> 0);
out.write(castBytes, 0, 9);
}
}
@@ -209,7 +258,7 @@ public class Packer {
castBytes[6] = barray[barray.length-3];
castBytes[7] = barray[barray.length-2];
castBytes[8] = barray[barray.length-1];
out.write(castBytes);
out.write(castBytes, 0, 9);
return this;
} else {
throw new MessageTypeException("can't pack BigInteger larger than 0xffffffffffffffff");
@@ -218,14 +267,28 @@ public class Packer {
public Packer packFloat(float d) throws IOException {
castBytes[0] = (byte)0xca;
castBuffer.putFloat(1, d);
// castBuffer.putFloat(1, d);
int f = Float.floatToRawIntBits(d);
castBytes[1] = (byte)(f >> 24);
castBytes[2] = (byte)(f >> 16);
castBytes[3] = (byte)(f >> 8);
castBytes[4] = (byte)(f >> 0);
out.write(castBytes, 0, 5);
return this;
}
public Packer packDouble(double d) throws IOException {
castBytes[0] = (byte)0xcb;
castBuffer.putDouble(1, d);
// castBuffer.putDouble(1, d);
long f = Double.doubleToRawLongBits(d);
castBytes[1] = (byte)(f >> 56);
castBytes[2] = (byte)(f >> 48);
castBytes[3] = (byte)(f >> 40);
castBytes[4] = (byte)(f >> 32);
castBytes[5] = (byte)(f >> 24);
castBytes[6] = (byte)(f >> 16);
castBytes[7] = (byte)(f >> 8);
castBytes[8] = (byte)(f >> 0);
out.write(castBytes, 0, 9);
return this;
}
@@ -255,11 +318,17 @@ public class Packer {
out.write((byte)d);
} else if(n < 65536) {
castBytes[0] = (byte)0xdc;
castBuffer.putShort(1, (short)n);
// castBuffer.putShort(1, (short)n);
castBytes[1] = (byte)(n >> 8);
castBytes[2] = (byte)(n >> 0);
out.write(castBytes, 0, 3);
} else {
castBytes[0] = (byte)0xdd;
castBuffer.putInt(1, n);
// castBuffer.putInt(1, n);
castBytes[1] = (byte)(n >> 24);
castBytes[2] = (byte)(n >> 16);
castBytes[3] = (byte)(n >> 8);
castBytes[4] = (byte)(n >> 0);
out.write(castBytes, 0, 5);
}
return this;
@@ -271,11 +340,17 @@ public class Packer {
out.write((byte)d);
} else if(n < 65536) {
castBytes[0] = (byte)0xde;
castBuffer.putShort(1, (short)n);
// castBuffer.putShort(1, (short)n);
castBytes[1] = (byte)(n >> 8);
castBytes[2] = (byte)(n >> 0);
out.write(castBytes, 0, 3);
} else {
castBytes[0] = (byte)0xdf;
castBuffer.putInt(1, n);
// castBuffer.putInt(1, n);
castBytes[1] = (byte)(n >> 24);
castBytes[2] = (byte)(n >> 16);
castBytes[3] = (byte)(n >> 8);
castBytes[4] = (byte)(n >> 0);
out.write(castBytes, 0, 5);
}
return this;
@@ -287,11 +362,17 @@ public class Packer {
out.write((byte)d);
} else if(n < 65536) {
castBytes[0] = (byte)0xda;
castBuffer.putShort(1, (short)n);
// castBuffer.putShort(1, (short)n);
castBytes[1] = (byte)(n >> 8);
castBytes[2] = (byte)(n >> 0);
out.write(castBytes, 0, 3);
} else {
castBytes[0] = (byte)0xdb;
castBuffer.putInt(1, n);
// castBuffer.putInt(1, n);
castBytes[1] = (byte)(n >> 24);
castBytes[2] = (byte)(n >> 16);
castBytes[3] = (byte)(n >> 8);
castBytes[4] = (byte)(n >> 0);
out.write(castBytes, 0, 5);
}
return this;
@@ -308,6 +389,21 @@ public class Packer {
}
public Packer packByteArray(byte[] b) throws IOException {
packRaw(b.length);
return packRawBody(b, 0, b.length);
}
public Packer packByteArray(byte[] b, int off, int length) throws IOException {
packRaw(length);
return packRawBody(b, off, length);
}
public Packer packByteBuffer(ByteBuffer buf) throws IOException {
packRaw(buf.remaining());
return packRawBody(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining());
}
public Packer packString(String s) throws IOException {
byte[] b = ((String)s).getBytes("UTF-8");
packRaw(b.length);
@@ -396,18 +492,18 @@ public class Packer {
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(ByteBuffer o) throws IOException {
if (o == null) { return packNil(); }
packRaw(o.remaining());
return packRawBody(o.array(), o.arrayOffset() + o.position(), o.remaining());
}
public Packer pack(List o) throws IOException {
if(o == null) { return packNil(); }
packArray(o.size());
@@ -425,57 +521,21 @@ public class Packer {
return this;
}
public Packer pack(MessagePackable o) throws IOException {
if(o == null) { return packNil(); }
o.messagePack(this);
return this;
}
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<Object,Object> 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 if(o instanceof BigInteger) {
return packBigInteger((BigInteger)o);
} else {
throw new MessageTypeException("unknown object "+o+" ("+o.getClass()+")");
}
if(o == null) { return packNil(); }
TemplateRegistry.lookup(o.getClass()).pack(this, o);
return this;
}
public Packer pack(Object o, Template tmpl) throws IOException {
tmpl.pack(this, o);
return this;
}
}

View File

@@ -0,0 +1,21 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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 Template extends MessagePacker, MessageUnpacker, MessageConverter {
}

View File

@@ -0,0 +1,119 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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 org.msgpack.template.*;
public class Templates {
public static Template tNullable(Template elementTemplate) {
return new NullableTemplate(elementTemplate);
}
public static final Template TAny = AnyTemplate.getInstance();
public static Template tAny() {
return TAny;
}
public static Template tList(Template elementTemplate) {
return new ListTemplate(elementTemplate);
}
public static Template tMap(Template keyTemplate, Template valueTemplate) {
return new MapTemplate(keyTemplate, valueTemplate);
}
public static Template tCollection(Template elementTemplate) {
return new CollectionTemplate(elementTemplate);
}
public static Template tClass(Class target) {
Template tmpl = TemplateRegistry.lookup(target);
if(tmpl == null) {
// FIXME
}
return tmpl;
}
public static final Template TByte = ByteTemplate.getInstance();
public static Template tByte() {
return TByte;
}
public static final Template TShort = ShortTemplate.getInstance();
public static Template tShort() {
return TShort;
}
public static final Template TInteger = IntegerTemplate.getInstance();
public static Template tInteger() {
return TInteger;
}
public static final Template TLong = LongTemplate.getInstance();
public static Template tLong() {
return TLong;
}
public static final Template TBigInteger = BigIntegerTemplate.getInstance();
public static Template tBigInteger() {
return TBigInteger;
}
public static final Template TBigDecimal = BigDecimalTemplate.getInstance();
public static Template tBigDecimal() {
return TBigDecimal;
}
public static final Template TFloat = FloatTemplate.getInstance();
public static Template tFloat() {
return TFloat;
}
public static final Template TDouble = DoubleTemplate.getInstance();
public static Template tDouble() {
return TDouble;
}
public static final Template TBoolean = BooleanTemplate.getInstance();
public static Template tBoolean() {
return TBoolean;
}
public static final Template TString = StringTemplate.getInstance();
public static Template tString() {
return TString;
}
public static final Template TByteArray = ByteArrayTemplate.getInstance();
public static Template tByteArray() {
return TByteArray;
}
public static final Template TByteBuffer = ByteBufferTemplate.getInstance();
public static Template tByteBuffer() {
return TByteBuffer;
}
public static final Template TDate = DateTemplate.getInstance();
public static Template tDate() {
return TDate;
}
}

View File

@@ -23,6 +23,7 @@ import java.io.IOException;
import java.util.Iterator;
import java.nio.ByteBuffer;
import java.math.BigInteger;
import org.msgpack.template.TemplateRegistry;
/**
* Unpacker enables you to deserialize objects from stream.
@@ -103,7 +104,6 @@ import java.math.BigInteger;
* </pre>
*/
public class Unpacker implements Iterable<MessagePackObject> {
// buffer:
// +---------------------------------------------+
// | [object] | [obje| unparsed ... | unused ...|
@@ -232,6 +232,7 @@ public class Unpacker implements Iterable<MessagePackObject> {
impl.buffer = buffer;
impl.offset = offset;
impl.filled = length;
impl.bufferReferenced = false; // TODO zero-copy buffer
}
/**
@@ -276,13 +277,16 @@ public class Unpacker implements Iterable<MessagePackObject> {
if(impl.buffer == null) {
int nextSize = (bufferReserveSize < require) ? require : bufferReserveSize;
impl.buffer = new byte[nextSize];
impl.bufferReferenced = false; // TODO zero-copy buffer
return;
}
if(impl.filled <= impl.offset) {
// rewind the buffer
impl.filled = 0;
impl.offset = 0;
if(!impl.bufferReferenced) { // TODO zero-copy buffer
if(impl.filled <= impl.offset) {
// rewind the buffer
impl.filled = 0;
impl.offset = 0;
}
}
if(impl.buffer.length - impl.filled >= require) {
@@ -301,6 +305,7 @@ public class Unpacker implements Iterable<MessagePackObject> {
impl.buffer = tmp;
impl.filled = notParsed;
impl.offset = 0;
impl.bufferReferenced = false; // TODO zero-copy buffer
}
/**
@@ -367,8 +372,7 @@ public class Unpacker implements Iterable<MessagePackObject> {
* @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;
int noffset = impl.execute(buffer, offset, length);
if(impl.isFinished()) {
impl.resetState();
}
@@ -536,14 +540,23 @@ public class Unpacker implements Iterable<MessagePackObject> {
return impl.unpackRawBody(length);
}
/**
* Gets one raw bytes from the buffer.
* Gets one raw object (header + body) from the buffer.
* This method calls {@link fill()} method if needed.
*/
public byte[] unpackByteArray() throws IOException {
return impl.unpackByteArray();
}
/**
* Gets one raw object (header + body) from the buffer.
* This method calls {@link fill()} method if needed.
*/
public ByteBuffer unpackByteBuffer() throws IOException {
return impl.unpackByteBuffer();
}
/**
* Gets one {@code String} value from the buffer.
* This method calls {@link fill()} method if needed.
@@ -561,12 +574,37 @@ public class Unpacker implements Iterable<MessagePackObject> {
return impl.unpackObject();
}
final public boolean tryUnpackNull() throws IOException {
return impl.tryUnpackNull();
}
final public void unpack(MessageUnpackable obj) throws IOException, MessageTypeException {
obj.messageUnpack(this);
}
final public boolean tryUnpackNull() throws IOException {
return impl.tryUnpackNull();
//final public MessagePackObject unpack() throws IOException {
// return unpackObject();
//}
final public <T> T unpack(T to) throws IOException, MessageTypeException {
return unpack((Class<T>)to.getClass(), to);
}
final public <T> T unpack(Class<T> klass) throws IOException, MessageTypeException {
return unpack(klass, null);
}
final public <T> T unpack(Class<T> klass, T to) throws IOException, MessageTypeException {
if(tryUnpackNull()) { return null; }
return (T)TemplateRegistry.lookup(klass).unpack(this, to);
}
final public Object unpack(Template tmpl) throws IOException, MessageTypeException {
return unpack(tmpl, null);
}
final public <T> T unpack(Template tmpl, T to) throws IOException, MessageTypeException {
return (T)tmpl.unpack(this, to);
}
}

View File

@@ -309,6 +309,7 @@ public class UnpackerImpl {
cs = ACS_RAW_VALUE;
break _fixed_trail_again;
case ACS_RAW_VALUE: {
// TODO zero-copy buffer
byte[] raw = new byte[trail];
System.arraycopy(src, n, raw, 0, trail);
obj = RawType.create(raw);

View File

@@ -0,0 +1,28 @@
//
// 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Ignore {
}

View File

@@ -0,0 +1,29 @@
//
// 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Index {
int value();
}

View File

@@ -0,0 +1,35 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.msgpack.template.FieldOption;
/**
* Annotation for java beans class
* @author takeshita
*
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MessagePackBeans {
FieldOption value() default FieldOption.DEFAULT;
}

View File

@@ -0,0 +1,29 @@
//
// 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MessagePackDelegate {
String value();
}

View File

@@ -0,0 +1,30 @@
//
// 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.msgpack.template.FieldOption;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MessagePackMessage {
FieldOption value() default FieldOption.DEFAULT;
}

View File

@@ -0,0 +1,28 @@
//
// 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MessagePackOrdinalEnum {
}

View File

@@ -0,0 +1,28 @@
//
// 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Nullable {
}

View File

@@ -0,0 +1,28 @@
//
// 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Optional {
}

View File

@@ -0,0 +1,28 @@
//
// 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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Required {
}

View File

@@ -0,0 +1,462 @@
//
// MessagePack for Java
//
// Copyright (C) 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.buffer;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.nio.channels.ScatteringByteChannel;
public class VectoredByteBuffer implements GatheringByteChannel, ScatteringByteChannel {
private List<ByteBuffer> vec = new ArrayList<ByteBuffer>();
private ByteBuffer internalBuffer;
private ByteBuffer lastInternalBuffer;
private int chunkSize;
private int referenceThreshold;
public VectoredByteBuffer() {
this(32*1024);
}
public VectoredByteBuffer(int chunkSize) {
this(chunkSize, 32);
}
public VectoredByteBuffer(int chunkSize, int referenceThreshold) {
this.chunkSize = chunkSize;
this.referenceThreshold = referenceThreshold;
internalBuffer = ByteBuffer.allocateDirect(chunkSize);
}
public void setChunkSize(int chunkSize) {
this.chunkSize = chunkSize;
}
public int getChunkSize(int chunkSize) {
return this.chunkSize;
}
public void setReferenceThreshold(int referenceThreshold) {
this.referenceThreshold = referenceThreshold;
}
public int getReferenceThreshold(int referenceThreshold) {
return this.referenceThreshold;
}
@Override
public void close() {
reset();
}
@Override
public boolean isOpen() {
return true; // FIXME?
}
public synchronized void reset() {
vec.clear();
lastInternalBuffer = null;
}
public void write(byte[] b) {
write(b, 0, b.length);
}
public void write(byte[] b, int off, int len) {
if(off < 0 || len < 0 || b.length < off+len) {
throw new IndexOutOfBoundsException();
}
if(referenceThreshold >= 0 && len > referenceThreshold) {
writeReference(b, off, len);
} else {
writeCopy(b, off, len);
}
}
public void write(int b) {
byte[] ba = new byte[1];
ba[0] = (byte)b;
write(ba);
}
@Override
public int write(ByteBuffer src) {
int slen = src.remaining();
if(referenceThreshold >= 0 && slen > referenceThreshold) {
writeCopy(src);
} else {
writeReference(src);
}
return slen;
}
@Override
public synchronized long write(ByteBuffer[] srcs) {
return write(srcs, 0, srcs.length);
}
@Override
public synchronized long write(ByteBuffer[] srcs, int offset, int length) {
if(offset < 0 || length < 0 || srcs.length < offset+length) {
throw new IndexOutOfBoundsException();
}
long total = 0;
for(int i=offset; offset < length; offset++) {
ByteBuffer src = srcs[i];
total += write(src);
}
return total;
}
private synchronized void writeCopy(byte[] b, int off, int len) {
int ipos = internalBuffer.position();
if(internalBuffer.capacity() - ipos < len) {
// allocate new buffer
int nsize = chunkSize > len ? chunkSize : len;
internalBuffer = ByteBuffer.allocateDirect(nsize);
ipos = 0;
} else if(internalBuffer == lastInternalBuffer) {
// optimization: concatenates to the last buffer instead
// of adding new reference
ByteBuffer dup = vec.get(vec.size()-1);
internalBuffer.put(b, off, len);
dup.limit(ipos + len);
return;
}
internalBuffer.put(b, off, len);
ByteBuffer dup = internalBuffer.duplicate();
dup.position(ipos);
dup.mark();
dup.limit(ipos + len);
vec.add(dup);
lastInternalBuffer = internalBuffer;
}
private synchronized void writeCopy(ByteBuffer src) {
int slen = src.remaining();
int ipos = internalBuffer.position();
if(internalBuffer.capacity() - ipos < slen) {
// allocate new buffer
int nsize = chunkSize > slen ? chunkSize : slen;
internalBuffer = ByteBuffer.allocateDirect(nsize);
ipos = 0;
} else if(internalBuffer == lastInternalBuffer) {
// optimization: concatenates to the last buffer instead
// of adding new reference
ByteBuffer dup = vec.get(vec.size()-1);
int dpos = dup.position();
internalBuffer.put(src);
ByteBuffer dup2 = internalBuffer.duplicate();
dup2.position(dpos);
dup2.limit(ipos + slen);
vec.set(vec.size()-1, dup2);
return;
}
internalBuffer.put(src);
ByteBuffer dup = internalBuffer.duplicate();
dup.position(ipos);
dup.mark();
dup.limit(ipos + slen);
vec.add(dup);
lastInternalBuffer = internalBuffer;
}
private synchronized void writeReference(byte[] b, int off, int len) {
ByteBuffer buf = ByteBuffer.wrap(b, off, len);
vec.add(buf);
lastInternalBuffer = null;
}
private synchronized void writeReference(ByteBuffer src) {
ByteBuffer buf = src.duplicate();
vec.add(buf);
lastInternalBuffer = null;
}
public synchronized void writeTo(java.io.OutputStream out) throws IOException {
byte[] tmpbuf = null;
for(int i=0; i < vec.size(); i++) {
ByteBuffer r = vec.get(i);
int rpos = r.position();
int rlen = r.limit() - rpos;
if(r.hasArray()) {
byte[] array = r.array();
out.write(array, rpos, rlen);
} else {
if(tmpbuf == null) {
int max = rlen;
for(int j=i+1; j < vec.size(); j++) {
ByteBuffer c = vec.get(j);
int clen = c.remaining();
if(max < clen) {
max = clen;
}
}
tmpbuf = new byte[max];
}
r.get(tmpbuf, 0, rlen);
r.position(rpos);
out.write(tmpbuf, 0, rlen);
}
}
}
public synchronized byte[] toByteArray() {
byte[] out = new byte[available()];
int off = 0;
for(ByteBuffer r: vec) {
int rpos = r.position();
int rlen = r.limit() - rpos;
r.get(out, off, rlen);
r.position(rpos);
off += rlen;
}
return out;
}
public synchronized int available() {
int total = 0;
for(ByteBuffer r : vec) {
total += r.remaining();
}
return total;
}
public synchronized int read(byte[] b) {
return read(b, 0, b.length);
}
public synchronized int read(byte[] b, int off, int len) {
if(off < 0 || len < 0 || b.length < off+len) {
throw new IndexOutOfBoundsException();
}
int start = len;
while(!vec.isEmpty()) {
ByteBuffer r = vec.get(0);
int rlen = r.remaining();
if(rlen <= len) {
r.get(b, off, rlen);
vec.remove(0);
off += rlen;
len -= rlen;
} else {
r.get(b, off, len);
return start;
}
}
return start - len;
}
public synchronized int read() {
byte[] ba = new byte[1];
if(read(ba) >= 1) {
return ba[0];
} else {
return -1;
}
}
@Override
public synchronized int read(ByteBuffer dst) {
int len = dst.remaining();
int start = len;
while(!vec.isEmpty()) {
ByteBuffer r = vec.get(0);
int rlen = r.remaining();
if(rlen <= len) {
dst.put(r);
vec.remove(0);
len -= rlen;
} else {
int blim = r.limit();
r.limit(len);
try {
dst.put(r);
} finally {
r.limit(blim);
}
return start;
}
}
return start - len;
}
@Override
public synchronized long read(ByteBuffer[] dsts) {
return read(dsts, 0, dsts.length);
}
@Override
public synchronized long read(ByteBuffer[] dsts, int offset, int length) {
if(offset < 0 || length < 0 || dsts.length < offset+length) {
throw new IndexOutOfBoundsException();
}
long total = 0;
for(int i=offset; i < length; i++) {
ByteBuffer dst = dsts[i];
int dlen = dst.remaining();
int rlen = read(dsts[i]);
total += rlen;
if(rlen < dlen) {
return total;
}
}
return total;
}
public synchronized long read(GatheringByteChannel to) throws IOException {
long total = to.write(vec.toArray(new ByteBuffer[0]));
while(!vec.isEmpty()) {
ByteBuffer r = vec.get(0);
if(r.remaining() == 0) {
vec.remove(0);
} else {
break;
}
}
return total;
}
public synchronized long skip(long len) {
if(len <= 0) {
return 0;
}
long start = len;
while(!vec.isEmpty()) {
ByteBuffer r = vec.get(0);
int rlen = r.remaining();
if(rlen <= len) {
r.position(r.position()+rlen);
vec.remove(0);
len -= rlen;
} else {
r.position((int)(r.position()+len));
return start;
}
}
return start - len;
}
public final static class OutputStream extends java.io.OutputStream {
private VectoredByteBuffer vbb;
OutputStream(VectoredByteBuffer vbb) {
this.vbb = vbb;
}
@Override
public void write(byte[] b) {
vbb.write(b);
}
@Override
public void write(byte[] b, int off, int len) {
vbb.write(b, off, len);
}
@Override
public void write(int b) {
vbb.write(b);
}
public int write(ByteBuffer src) {
return vbb.write(src);
}
public long write(ByteBuffer[] srcs) {
return vbb.write(srcs);
}
public long write(ByteBuffer[] srcs, int offset, int length) {
return vbb.write(srcs, offset, length);
}
public void writeTo(OutputStream out) throws IOException {
vbb.writeTo(out);
}
public byte[] toByteArray() {
return vbb.toByteArray();
}
}
public final static class InputStream extends java.io.InputStream {
private VectoredByteBuffer vbb;
InputStream(VectoredByteBuffer vbb) {
this.vbb = vbb;
}
@Override
public int available() {
return vbb.available();
}
@Override
public int read(byte[] b) {
return vbb.read(b);
}
@Override
public int read(byte[] b, int off, int len) {
return vbb.read(b, off, len);
}
@Override
public int read() {
return vbb.read();
}
public int read(ByteBuffer dst) {
return vbb.read(dst);
}
public long read(ByteBuffer[] dsts, int offset, int length) {
return vbb.read(dsts, offset, length);
}
public long read(GatheringByteChannel to) throws IOException {
return vbb.read(to);
}
public long skip(long len) {
return vbb.skip(len);
}
}
public OutputStream outputStream() {
return new OutputStream(this);
}
public InputStream inputStream() {
return new InputStream(this);
}
}

View File

@@ -1,7 +1,7 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
// Copyright (C) 2009-2011 FURUHASHI Sadayuki
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -79,7 +79,7 @@ public class RawType extends MessagePackObject {
@Override
public int hashCode() {
return bytes.hashCode();
return Arrays.hashCode(bytes);
}
@Override

View File

@@ -0,0 +1,54 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class AnyTemplate implements Template {
private AnyTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
if(target instanceof MessagePackObject) {
pk.pack((MessagePackObject)target);
} else if(target == null) {
pk.packNil();
} else {
TemplateRegistry.lookup(target.getClass()).pack(pk, target);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return pac.unpackObject();
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
return from;
}
static public AnyTemplate getInstance() {
return instance;
}
static final AnyTemplate instance = new AnyTemplate();
static {
TemplateRegistry.register(MessagePackObject.class, instance);
}
}

View File

@@ -0,0 +1,143 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import org.msgpack.*;
/**
* Field entry for Java beans property.
* @author takeshita
*
*/
public class BeansFieldEntry implements IFieldEntry {
PropertyDescriptor desc;
FieldOption option = FieldOption.DEFAULT;
public BeansFieldEntry(PropertyDescriptor desc) {
this.desc = desc;
}
@Override
public String getName() {
return desc.getDisplayName();
}
public String getGetterName(){
return desc.getReadMethod().getName();
}
public String getSetterName(){
return desc.getWriteMethod().getName();
}
@Override
public Class<?> getType() {
return desc.getPropertyType();
}
@Override
public String getJavaTypeName() {
Class<?> type = getType();
if(type.isArray()) {
return arrayTypeToString(type);
} else {
return type.getName();
}
}
static String arrayTypeToString(Class<?> type) {
int dim = 1;
Class<?> baseType = type.getComponentType();
while(baseType.isArray()) {
baseType = baseType.getComponentType();
dim += 1;
}
StringBuilder sb = new StringBuilder();
sb.append(baseType.getName());
for (int i = 0; i < dim; ++i) {
sb.append("[]");
}
return sb.toString();
}
@Override
public Type getGenericType() {
return desc.getReadMethod().getGenericReturnType();
}
@Override
public FieldOption getOption() {
return option;
}
public void setOption(FieldOption option){
this.option = option;
}
@Override
public boolean isAvailable() {
return option != FieldOption.IGNORE;
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#isRequired()
*/
@Override
public boolean isRequired() {
return option == FieldOption.REQUIRED;
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#isOptional()
*/
@Override
public boolean isOptional() {
return option == FieldOption.OPTIONAL;
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#isNullable()
*/
@Override
public boolean isNullable() {
return option == FieldOption.NULLABLE;
}
public Object get(Object target){
try {
return desc.getReadMethod().invoke(target);
} catch (IllegalArgumentException e) {
throw new MessageTypeException(e);
} catch (IllegalAccessException e) {
throw new MessageTypeException(e);
} catch (InvocationTargetException e) {
throw new MessageTypeException(e);
}
}
public void set(Object target , Object value){
try {
desc.getWriteMethod().invoke(target, value);
} catch (IllegalArgumentException e) {
throw new MessageTypeException(e);
} catch (IllegalAccessException e) {
throw new MessageTypeException(e);
} catch (InvocationTargetException e) {
throw new MessageTypeException(e);
}
}
}

View File

@@ -0,0 +1,188 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.msgpack.annotation.Ignore;
import org.msgpack.annotation.Index;
import org.msgpack.annotation.MessagePackMessage;
import org.msgpack.annotation.Nullable;
import org.msgpack.annotation.Optional;
import org.msgpack.annotation.Required;
/**
* List up Java beans property methods.
* @author takeshita
*
*/
public class BeansFieldEntryReader implements IFieldEntryReader{
public IFieldEntry[] convertFieldEntries(Class<?> targetClass, FieldList flist) throws NoSuchFieldException {
List<FieldList.Entry> src = flist.getList();
FieldEntry[] result = new FieldEntry[src.size()];
for(int i=0; i < src.size(); i++) {
FieldList.Entry s = src.get(i);
if(s.isAvailable()) {
result[i] = new FieldEntry(targetClass.getDeclaredField(s.getName()), s.getOption());
} else {
result[i] = new FieldEntry();
}
}
return result;
}
@Override
public IFieldEntry[] readFieldEntries(Class<?> targetClass,
FieldOption implicitOption) {
BeanInfo desc;
try {
desc = Introspector.getBeanInfo(targetClass);
} catch (IntrospectionException e1) {
throw new TemplateBuildException("Class must be java beans class:" + targetClass.getName());
}
PropertyDescriptor[] props = desc.getPropertyDescriptors();
ArrayList<PropertyDescriptor> list = new ArrayList<PropertyDescriptor>();
for(int i = 0;i < props.length;i++){
PropertyDescriptor pd = props[i];
if(!isIgnoreProp(pd)){
list.add(pd);
}
}
props = new PropertyDescriptor[list.size()];
list.toArray(props);
BeansFieldEntry[] entries = new BeansFieldEntry[props.length];
for(int i = 0;i < props.length;i++){
PropertyDescriptor p = props[i];
int index = readPropIndex(p);
if(index >= 0){
if(entries[index] != null){
throw new TemplateBuildException("duplicated index: "+index);
}
if(index >= entries.length){
throw new TemplateBuildException("invalid index: "+index);
}
entries[index] = new BeansFieldEntry(p);
props[index] = null;
}
}
int insertIndex = 0;
for(int i = 0;i < props.length;i++){
PropertyDescriptor p = props[i];
if(p != null){
while(entries[insertIndex] != null){
insertIndex++;
}
entries[insertIndex] = new BeansFieldEntry(p);
}
}
for(int i = 0;i < entries.length;i++){
BeansFieldEntry e = entries[i];
FieldOption op = readPropOption(e.desc, implicitOption);
e.setOption(op);
}
return entries;
}
public FieldOption readImplicitFieldOption(Class<?> targetClass) {
MessagePackMessage a = targetClass.getAnnotation(MessagePackMessage.class);
if(a == null) {
return FieldOption.DEFAULT;
}
return a.value();
}
private FieldOption readPropOption(PropertyDescriptor desc, FieldOption implicitOption) {
FieldOption forGetter = readMethodOption(desc.getReadMethod());
if(forGetter != FieldOption.DEFAULT){
return forGetter;
}
FieldOption forSetter = readMethodOption(desc.getWriteMethod());
if(forSetter != FieldOption.DEFAULT){
return forSetter;
}else{
return implicitOption;
}
}
private FieldOption readMethodOption(Method method){
if(isAnnotated(method, Ignore.class)) {
return FieldOption.IGNORE;
} else if(isAnnotated(method, Required.class)) {
return FieldOption.REQUIRED;
} else if(isAnnotated(method, Optional.class)) {
return FieldOption.OPTIONAL;
} else if(isAnnotated(method, Nullable.class)) {
if(method.getDeclaringClass().isPrimitive()) {
return FieldOption.REQUIRED;
} else {
return FieldOption.NULLABLE;
}
}
return FieldOption.DEFAULT;
}
private int readPropIndex(PropertyDescriptor desc) {
int forGetter = readMethodIndex(desc.getReadMethod());
if(forGetter >= 0){
return forGetter;
}
int forSetter = readMethodIndex(desc.getWriteMethod());
return forSetter;
}
private int readMethodIndex(Method method){
Index a = method.getAnnotation(Index.class);
if(a == null) {
return -1;
} else {
return a.value();
}
}
private boolean isAnnotated(AccessibleObject ao, Class<? extends Annotation> with) {
return ao.getAnnotation(with) != null;
}
boolean isIgnoreProp(PropertyDescriptor desc){
if(desc == null)return true;
Method getter = desc.getReadMethod();
Method setter = desc.getWriteMethod();
return getter == null ||
setter == null ||
!Modifier.isPublic(getter.getModifiers()) ||
!Modifier.isPublic(setter.getModifiers()) ||
isAnnotated(getter,Ignore.class) ||
isAnnotated(setter, Ignore.class);
}
}

View File

@@ -0,0 +1,61 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
import java.io.IOException;
import java.math.BigDecimal;
import org.msgpack.MessagePackObject;
import org.msgpack.MessageTypeException;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Unpacker;
public class BigDecimalTemplate implements Template {
@Override
public void pack(Packer pk, Object target) throws IOException {
BigDecimal temp = (BigDecimal) target;
try {
pk.packString(temp.toString());
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
}
@Override
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
String temp = pac.unpackString();
return new BigDecimal(temp);
}
@Override
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
String temp = from.asString();
return new BigDecimal(temp);
}
static public BigDecimalTemplate getInstance() {
return instance;
}
static final BigDecimalTemplate instance = new BigDecimalTemplate();
static {
TemplateRegistry.register(BigDecimal.class, instance);
}
}

View File

@@ -0,0 +1,53 @@
//
// 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.template;
import java.io.IOException;
import java.math.BigInteger;
import org.msgpack.*;
public class BigIntegerTemplate implements Template {
private BigIntegerTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
try {
pk.packBigInteger((BigInteger)target);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return pac.unpackBigInteger();
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
return from.asBigInteger();
}
static public BigIntegerTemplate getInstance() {
return instance;
}
static final BigIntegerTemplate instance = new BigIntegerTemplate();
static {
TemplateRegistry.register(BigInteger.class, instance);
}
}

View File

@@ -0,0 +1,80 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class BooleanArrayTemplate implements Template {
private BooleanArrayTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
if(!(target instanceof boolean[])) {
throw new MessageTypeException();
}
boolean[] array = (boolean[])target;
try {
pk.packArray(array.length);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
for(boolean a : array) {
pk.pack(a);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
int length = pac.unpackArray();
boolean[] array;
if(to != null && to instanceof boolean[] && ((boolean[])to).length == length) {
array = (boolean[])to;
} else {
array = new boolean[length];
}
for(int i=0; i < length; i++) {
array[i] = pac.unpackBoolean();
}
return array;
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
MessagePackObject[] src = from.asArray();
boolean[] array;
if(to != null && to instanceof boolean[] && ((boolean[])to).length == src.length) {
array = (boolean[])to;
} else {
array = new boolean[src.length];
}
for(int i=0; i < src.length; i++) {
MessagePackObject s = src[i];
array[i] = s.asBoolean();
}
return array;
}
static public BooleanArrayTemplate getInstance() {
return instance;
}
static final BooleanArrayTemplate instance = new BooleanArrayTemplate();
static {
TemplateRegistry.register(boolean[].class, instance);
}
}

View File

@@ -0,0 +1,53 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class BooleanTemplate implements Template {
private BooleanTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
try {
pk.packBoolean((Boolean)target);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return pac.unpackBoolean();
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
return from.asBoolean();
}
static public BooleanTemplate getInstance() {
return instance;
}
static final BooleanTemplate instance = new BooleanTemplate();
static {
TemplateRegistry.register(Boolean.class, instance);
TemplateRegistry.register(boolean.class, instance);
}
}

View File

@@ -0,0 +1,49 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
public class BuiltInTemplateLoader {
public static void load() {
AnyTemplate.getInstance();
BigIntegerTemplate.getInstance();
BigDecimalTemplate.getInstance();
BooleanArrayTemplate.getInstance();
BooleanTemplate.getInstance();
ByteArrayTemplate.getInstance();
ByteBufferTemplate.getInstance();
ByteTemplate.getInstance();
DoubleArrayTemplate.getInstance();
DoubleTemplate.getInstance();
DateTemplate.getInstance();
FloatArrayTemplate.getInstance();
FloatTemplate.getInstance();
IntArrayTemplate.getInstance();
IntegerTemplate.getInstance();
LongArrayTemplate.getInstance();
LongTemplate.getInstance();
ShortArrayTemplate.getInstance();
ShortTemplate.getInstance();
StringTemplate.getInstance();
CollectionTemplate.load();
ListTemplate.load();
MapTemplate.load();
NullableTemplate.load();
}
}

View File

@@ -0,0 +1,52 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class ByteArrayTemplate implements Template {
private ByteArrayTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
try {
pk.packByteArray((byte[])target);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return pac.unpackByteArray();
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
return from.asByteArray();
}
static public ByteArrayTemplate getInstance() {
return instance;
}
static final ByteArrayTemplate instance = new ByteArrayTemplate();
static {
TemplateRegistry.register(byte[].class, instance);
}
}

View File

@@ -0,0 +1,56 @@
//
// 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.template;
import java.nio.ByteBuffer;
import java.io.IOException;
import org.msgpack.*;
public class ByteBufferTemplate implements Template {
private ByteBufferTemplate() {
}
public void pack(Packer pk, Object target) throws IOException {
try {
pk.packByteBuffer((ByteBuffer) target);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return pac.unpackByteBuffer();
}
public Object convert(MessagePackObject from, Object to)
throws MessageTypeException {
// FIXME
byte[] bytes = from.asByteArray();
return ByteBuffer.wrap(bytes);
}
static public ByteBufferTemplate getInstance() {
return instance;
}
static final ByteBufferTemplate instance = new ByteBufferTemplate();
static {
TemplateRegistry.register(ByteBuffer.class, instance);
}
}

View File

@@ -0,0 +1,53 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class ByteTemplate implements Template {
private ByteTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
try {
pk.packByte((Byte)target);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return pac.unpackByte();
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
return from.asByte();
}
static public ByteTemplate getInstance() {
return instance;
}
static final ByteTemplate instance = new ByteTemplate();
static {
TemplateRegistry.register(Byte.class, instance);
TemplateRegistry.register(byte.class, instance);
}
}

View File

@@ -0,0 +1,93 @@
//
// 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.template;
import java.util.Collection;
import java.util.LinkedList;
import java.io.IOException;
import org.msgpack.MessagePackObject;
import org.msgpack.MessageTypeException;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Unpacker;
public class CollectionTemplate implements Template {
public static void load() { }
private Template elementTemplate;
public CollectionTemplate(Template elementTemplate) {
this.elementTemplate = elementTemplate;
}
@SuppressWarnings("unchecked")
public void pack(Packer pk, Object target) throws IOException {
if (! (target instanceof Collection)) {
if (target == null) {
throw new MessageTypeException(new NullPointerException("target is null."));
}
throw new MessageTypeException("target is not Collection type: " + target.getClass());
}
Collection<Object> collection = (Collection<Object>) target;
pk.packArray(collection.size());
for(Object element : collection) {
elementTemplate.pack(pk, element);
}
}
@SuppressWarnings("unchecked")
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
int length = pac.unpackArray();
Collection<Object> c;
if(to == null) {
c = new LinkedList<Object>();
} else {
// TODO: optimize if list is instanceof ArrayList
c = (Collection<Object>) to;
c.clear();
}
for(; length > 0; length--) {
c.add(elementTemplate.unpack(pac, null));
}
return c;
}
@SuppressWarnings("unchecked")
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
MessagePackObject[] array = from.asArray();
Collection<Object> c;
if(to == null) {
c = new LinkedList<Object>();
} else {
// TODO: optimize if list is instanceof ArrayList
c = (Collection<Object>) to;
c.clear();
}
for(MessagePackObject element : array) {
c.add(elementTemplate.convert(element, null));
}
return c;
}
static {
TemplateRegistry.registerGeneric(Collection.class, new GenericTemplate1(CollectionTemplate.class));
TemplateRegistry.register(Collection.class, new CollectionTemplate(AnyTemplate.getInstance()));
}
}

View File

@@ -0,0 +1,57 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
import java.io.IOException;
import java.util.Date;
import org.msgpack.MessagePackObject;
import org.msgpack.MessageTypeException;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Unpacker;
public class DateTemplate implements Template {
@Override
public void pack(Packer pk, Object target) throws IOException {
Date temp = (Date) target;
pk.packLong(temp.getTime());
}
@Override
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
Long temp = pac.unpackLong();
return new Date(temp);
}
@Override
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
Long temp = from.asLong();
return new Date(temp);
}
static public DateTemplate getInstance() {
return instance;
}
static final DateTemplate instance = new DateTemplate();
static {
TemplateRegistry.register(Date.class, instance);
}
}

View File

@@ -0,0 +1,96 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
import java.io.IOException;
import java.lang.reflect.Type;
import org.msgpack.*;
public class DefaultTemplate implements Template {
private Class<?> targetClass;
private Type lookupType;
private boolean messagePackable;
private boolean messageUnpackable;
private boolean messageConvertable;
public DefaultTemplate(Class<?> targetClass) {
this(targetClass, (Type)targetClass);
}
public DefaultTemplate(Class<?> targetClass, Type lookupType) {
this.targetClass = targetClass;
this.lookupType = lookupType;
this.messagePackable = MessagePackable.class.isAssignableFrom(targetClass);
this.messageUnpackable = MessageUnpackable.class.isAssignableFrom(targetClass);
this.messageConvertable = MessageConvertable.class.isAssignableFrom(targetClass);
}
public void pack(Packer pk, Object target) throws IOException {
if(messagePackable) {
if(target == null) {
throw new MessageTypeException("target is null.");
}
((MessagePackable)target).messagePack(pk);
return;
}
Template tmpl = TemplateRegistry.tryLookup(lookupType);
if(tmpl == this || tmpl == null) {
throw new MessageTypeException("Template lookup fail: " + lookupType.getClass().getName());
}
tmpl.pack(pk, target);
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
if(messageUnpackable) {
if(to == null) {
try {
to = targetClass.newInstance();
} catch (Exception e) {
throw new MessageTypeException(e);
}
}
((MessageUnpackable)to).messageUnpack(pac);
return to;
}
Template tmpl = TemplateRegistry.tryLookup(lookupType);
if(tmpl == this || tmpl == null) {
throw new MessageTypeException("Template lookup fail: " + lookupType.getClass().getName());
}
return tmpl.unpack(pac, to);
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
if(messageConvertable) {
if(to == null) {
try {
to = targetClass.newInstance();
} catch (Exception e) {
throw new MessageTypeException(e);
}
}
((MessageConvertable)to).messageConvert(from);
return from;
}
Template tmpl = TemplateRegistry.tryLookup(lookupType);
if(tmpl == this || tmpl == null) {
throw new MessageTypeException("Template lookup fail: " + lookupType.getClass().getName());
}
return tmpl.convert(from, to);
}
}

View File

@@ -0,0 +1,80 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class DoubleArrayTemplate implements Template {
private DoubleArrayTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
if(!(target instanceof double[])) {
throw new MessageTypeException();
}
double[] array = (double[])target;
try {
pk.packArray(array.length);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
for(double a : array) {
pk.pack(a);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
int length = pac.unpackArray();
double[] array;
if(to != null && to instanceof double[] && ((double[])to).length == length) {
array = (double[])to;
} else {
array = new double[length];
}
for(int i=0; i < length; i++) {
array[i] = pac.unpackDouble();
}
return array;
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
MessagePackObject[] src = from.asArray();
double[] array;
if(to != null && to instanceof double[] && ((double[])to).length == src.length) {
array = (double[])to;
} else {
array = new double[src.length];
}
for(int i=0; i < src.length; i++) {
MessagePackObject s = src[i];
array[i] = s.asDouble();
}
return array;
}
static public DoubleArrayTemplate getInstance() {
return instance;
}
static final DoubleArrayTemplate instance = new DoubleArrayTemplate();
static {
TemplateRegistry.register(double[].class, instance);
}
}

View File

@@ -0,0 +1,53 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class DoubleTemplate implements Template {
private DoubleTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
try {
pk.packDouble(((Double)target));
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return pac.unpackDouble();
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
return from.asDouble();
}
static public DoubleTemplate getInstance() {
return instance;
}
static final DoubleTemplate instance = new DoubleTemplate();
static {
TemplateRegistry.register(Double.class, instance);
TemplateRegistry.register(double.class, instance);
}
}

View File

@@ -0,0 +1,143 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
import java.io.IOException;
import java.lang.reflect.*;
import java.lang.annotation.*;
import java.util.List;
import java.util.ArrayList;
import java.util.EnumSet;
import org.msgpack.*;
import org.msgpack.annotation.*;
public class FieldEntry implements IFieldEntry {
private Field field;
private FieldOption option;
public FieldEntry() {
this.field = null;
this.option = FieldOption.IGNORE;
}
public FieldEntry(FieldEntry e) {
this.field = e.field;
this.option = e.option;
}
public FieldEntry(Field field, FieldOption option) {
this.field = field;
this.option = option;
}
public Field getField() {
return field;
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#getName()
*/
@Override
public String getName() {
return field.getName();
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#getType()
*/
@Override
public Class<?> getType() {
return field.getType();
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#getJavaTypeName()
*/
@Override
public String getJavaTypeName() {
Class<?> type = field.getType();
if(type.isArray()) {
return arrayTypeToString(type);
} else {
return type.getName();
}
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#getGenericType()
*/
@Override
public Type getGenericType() {
return field.getGenericType();
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#getOption()
*/
@Override
public FieldOption getOption() {
return option;
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#isAvailable()
*/
@Override
public boolean isAvailable() {
return option != FieldOption.IGNORE;
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#isRequired()
*/
@Override
public boolean isRequired() {
return option == FieldOption.REQUIRED;
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#isOptional()
*/
@Override
public boolean isOptional() {
return option == FieldOption.OPTIONAL;
}
/* (non-Javadoc)
* @see org.msgpack.template.IFieldEntry#isNullable()
*/
@Override
public boolean isNullable() {
return option == FieldOption.NULLABLE;
}
static String arrayTypeToString(Class<?> type) {
int dim = 1;
Class<?> baseType = type.getComponentType();
while(baseType.isArray()) {
baseType = baseType.getComponentType();
dim += 1;
}
StringBuilder sb = new StringBuilder();
sb.append(baseType.getName());
for (int i = 0; i < dim; ++i) {
sb.append("[]");
}
return sb.toString();
}
}

View File

@@ -0,0 +1,182 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.msgpack.annotation.Ignore;
import org.msgpack.annotation.Index;
import org.msgpack.annotation.MessagePackMessage;
import org.msgpack.annotation.Nullable;
import org.msgpack.annotation.Optional;
import org.msgpack.annotation.Required;
public class FieldEntryReader implements IFieldEntryReader{
public IFieldEntry[] convertFieldEntries(Class<?> targetClass, FieldList flist) throws NoSuchFieldException {
List<FieldList.Entry> src = flist.getList();
FieldEntry[] result = new FieldEntry[src.size()];
for(int i=0; i < src.size(); i++) {
FieldList.Entry s = src.get(i);
if(s.isAvailable()) {
result[i] = new FieldEntry(targetClass.getDeclaredField(s.getName()), s.getOption());
} else {
result[i] = new FieldEntry();
}
}
return result;
}
@Override
public IFieldEntry[] readFieldEntries(Class<?> targetClass,
FieldOption implicitOption) {
Field[] allFields = readAllFields(targetClass);
/* index:
* @Index(0) int field_a; // 0
* int field_b; // 1
* @Index(3) int field_c; // 3
* int field_d; // 4
* @Index(2) int field_e; // 2
* int field_f; // 5
*/
List<FieldEntry> indexed = new ArrayList<FieldEntry>();
int maxIndex = -1;
for(Field f : allFields) {
FieldOption opt = readFieldOption(f, implicitOption);
if(opt == FieldOption.IGNORE) {
// skip
continue;
}
int index = readFieldIndex(f, maxIndex);
if(indexed.size() > index && indexed.get(index) != null) {
throw new TemplateBuildException("duplicated index: "+index);
}
if(index < 0) {
throw new TemplateBuildException("invalid index: "+index);
}
while(indexed.size() <= index) {
indexed.add(null);
}
indexed.set(index, new FieldEntry(f, opt));
if(maxIndex < index) {
maxIndex = index;
}
}
FieldEntry[] result = new FieldEntry[maxIndex+1];
for(int i=0; i < indexed.size(); i++) {
FieldEntry e = indexed.get(i);
if(e == null) {
result[i] = new FieldEntry();
} else {
result[i] = e;
}
}
return result;
}
public FieldOption readImplicitFieldOption(Class<?> targetClass) {
MessagePackMessage a = targetClass.getAnnotation(MessagePackMessage.class);
if(a == null) {
return FieldOption.DEFAULT;
}
return a.value();
}
private Field[] readAllFields(Class<?> targetClass) {
// order: [fields of super class, ..., fields of this class]
List<Field[]> succ = new ArrayList<Field[]>();
int total = 0;
for(Class<?> c = targetClass; c != Object.class; c = c.getSuperclass()) {
Field[] fields = c.getDeclaredFields();
total += fields.length;
succ.add(fields);
}
Field[] result = new Field[total];
int off = 0;
for(int i=succ.size()-1; i >= 0; i--) {
Field[] fields = succ.get(i);
System.arraycopy(fields, 0, result, off, fields.length);
off += fields.length;
}
return result;
}
private static FieldOption readFieldOption(Field field, FieldOption implicitOption) {
int mod = field.getModifiers();
if(Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
return FieldOption.IGNORE;
}
if(isAnnotated(field, Ignore.class)) {
return FieldOption.IGNORE;
} else if(isAnnotated(field, Required.class)) {
return FieldOption.REQUIRED;
} else if(isAnnotated(field, Optional.class)) {
return FieldOption.OPTIONAL;
} else if(isAnnotated(field, Nullable.class)) {
if(field.getDeclaringClass().isPrimitive()) {
return FieldOption.REQUIRED;
} else {
return FieldOption.NULLABLE;
}
}
if(implicitOption != FieldOption.DEFAULT) {
return implicitOption;
}
// default mode:
// transient : Ignore
// public : Required
// others : Ignore
if(Modifier.isTransient(mod)) {
return FieldOption.IGNORE;
} else if(Modifier.isPublic(mod)) {
return FieldOption.REQUIRED;
} else {
return FieldOption.IGNORE;
}
}
private static int readFieldIndex(Field field, int maxIndex) {
Index a = field.getAnnotation(Index.class);
if(a == null) {
return maxIndex + 1;
} else {
return a.value();
}
}
private static boolean isAnnotated(AccessibleObject ao, Class<? extends Annotation> with) {
return ao.getAnnotation(with) != null;
}
}

View File

@@ -0,0 +1,96 @@
//
// 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.template;
import java.util.List;
import java.util.ArrayList;
public class FieldList {
public static class Entry {
public Entry() {
this.name = null;
this.option = FieldOption.IGNORE;
}
public Entry(String name, FieldOption option) {
this.name = name;
this.option = option;
}
private String name;
private FieldOption option;
public String getName() {
return name;
}
public FieldOption getOption() {
return option;
}
public boolean isAvailable() {
return this.option != FieldOption.IGNORE;
}
public boolean isRequired() {
return this.option == FieldOption.REQUIRED;
}
public boolean isOptional() {
return this.option == FieldOption.OPTIONAL;
}
public boolean isNullable() {
return this.option == FieldOption.NULLABLE;
}
}
private ArrayList<Entry> list;
public FieldList() {
list = new ArrayList<Entry>();
}
public void add(final String name) {
add(name, FieldOption.REQUIRED);
}
public void add(final String name, final FieldOption option) {
list.add(new Entry(name, option));
}
public void put(int index, final String name) {
put(index, name, FieldOption.REQUIRED);
}
public void put(int index, final String name, final FieldOption option) {
if(list.size() < index) {
do {
list.add(new Entry());
} while(list.size() < index);
list.add(new Entry(name, option));
} else {
list.set(index, new Entry(name, option));
}
}
public List<Entry> getList() {
return list;
}
}

View File

@@ -0,0 +1,27 @@
//
// 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.template;
public enum FieldOption {
IGNORE,
REQUIRED,
OPTIONAL,
NULLABLE,
DEFAULT;
}

View File

@@ -0,0 +1,80 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class FloatArrayTemplate implements Template {
private FloatArrayTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
if(!(target instanceof float[])) {
throw new MessageTypeException();
}
float[] array = (float[])target;
try {
pk.packArray(array.length);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
for(float a : array) {
pk.pack(a);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
int length = pac.unpackArray();
float[] array;
if(to != null && to instanceof float[] && ((float[])to).length == length) {
array = (float[])to;
} else {
array = new float[length];
}
for(int i=0; i < length; i++) {
array[i] = pac.unpackFloat();
}
return array;
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
MessagePackObject[] src = from.asArray();
float[] array;
if(to != null && to instanceof float[] && ((float[])to).length == src.length) {
array = (float[])to;
} else {
array = new float[src.length];
}
for(int i=0; i < src.length; i++) {
MessagePackObject s = src[i];
array[i] = s.asFloat();
}
return array;
}
static public FloatArrayTemplate getInstance() {
return instance;
}
static final FloatArrayTemplate instance = new FloatArrayTemplate();
static {
TemplateRegistry.register(float[].class, instance);
}
}

View File

@@ -0,0 +1,53 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class FloatTemplate implements Template {
private FloatTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
try {
pk.packFloat((Float)target);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
return pac.unpackFloat();
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
return from.asFloat();
}
static public FloatTemplate getInstance() {
return instance;
}
static final FloatTemplate instance = new FloatTemplate();
static {
TemplateRegistry.register(Float.class, instance);
TemplateRegistry.register(float.class, instance);
}
}

View File

@@ -0,0 +1,25 @@
//
// 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.template;
import org.msgpack.Template;
public interface GenericTemplate {
public Template build(Template[] params);
}

View File

@@ -0,0 +1,54 @@
//
// 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.template;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.msgpack.Template;
public class GenericTemplate1 implements GenericTemplate {
Constructor<? extends Template> constructor;
public GenericTemplate1(Class<? extends Template> tmpl) {
try {
this.constructor = tmpl.getConstructor(new Class<?>[]{Template.class});
constructor.newInstance(new Object[]{AnyTemplate.getInstance()});
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
}
}
public Template build(Template[] params) {
try {
return constructor.newInstance(params);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
}
}
}

View File

@@ -0,0 +1,54 @@
//
// 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.template;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.msgpack.Template;
public class GenericTemplate2 implements GenericTemplate {
Constructor<? extends Template> constructor;
public GenericTemplate2(Class<? extends Template> tmpl) {
try {
this.constructor = tmpl.getConstructor(new Class<?>[]{Template.class, Template.class});
constructor.newInstance(new Object[]{AnyTemplate.getInstance(), AnyTemplate.getInstance()});
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
}
}
public Template build(Template[] params) {
try {
return constructor.newInstance(params);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
}
}
}

View File

@@ -0,0 +1,42 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
import java.lang.reflect.Type;
public interface IFieldEntry {
public abstract String getName();
public abstract Class<?> getType();
public abstract String getJavaTypeName();
public abstract Type getGenericType();
public abstract FieldOption getOption();
public abstract boolean isAvailable();
public abstract boolean isRequired();
public abstract boolean isOptional();
public abstract boolean isNullable();
}

View File

@@ -0,0 +1,25 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2011 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.template;
public interface IFieldEntryReader {
public IFieldEntry[] convertFieldEntries(Class<?> targetClass, FieldList flist) throws NoSuchFieldException;
public IFieldEntry[] readFieldEntries(Class<?> targetClass, FieldOption implicitOption);
public FieldOption readImplicitFieldOption(Class<?> targetClass) ;
}

View File

@@ -0,0 +1,80 @@
//
// 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.template;
import java.io.IOException;
import org.msgpack.*;
public class IntArrayTemplate implements Template {
private IntArrayTemplate() { }
public void pack(Packer pk, Object target) throws IOException {
if(!(target instanceof int[])) {
throw new MessageTypeException();
}
int[] array = (int[])target;
try {
pk.packArray(array.length);
} catch (NullPointerException e) {
throw new MessageTypeException("target is null.", e);
}
for(int a : array) {
pk.pack(a);
}
}
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
int length = pac.unpackArray();
int[] array;
if(to != null && to instanceof int[] && ((int[])to).length == length) {
array = (int[])to;
} else {
array = new int[length];
}
for(int i=0; i < length; i++) {
array[i] = pac.unpackInt();
}
return array;
}
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
MessagePackObject[] src = from.asArray();
int[] array;
if(to != null && to instanceof int[] && ((int[])to).length == src.length) {
array = (int[])to;
} else {
array = new int[src.length];
}
for(int i=0; i < src.length; i++) {
MessagePackObject s = src[i];
array[i] = s.asInt();
}
return array;
}
static public IntArrayTemplate getInstance() {
return instance;
}
static final IntArrayTemplate instance = new IntArrayTemplate();
static {
TemplateRegistry.register(int[].class, instance);
}
}

Some files were not shown because too many files have changed in this diff Show More