├── .circleci
└── config.yml
├── .gitignore
├── .gitmodules
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── ISSUE_TEMPLATE.md
├── LICENSE
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── moshipack-retrofit
├── build.gradle
└── src
│ ├── main
│ └── kotlin
│ │ └── com
│ │ └── daveanthonythomas
│ │ └── moshipack
│ │ └── MoshiPackConverterFactory.kt
│ └── test
│ ├── kotlin
│ └── TestMoshiPackRetrofit.kt
│ └── resources
│ └── cats
├── moshipack
├── build.gradle
└── src
│ ├── main
│ └── kotlin
│ │ └── com
│ │ ├── daveanthonythomas
│ │ └── moshipack
│ │ │ ├── FormatInterchange.kt
│ │ │ ├── MoshiPack.kt
│ │ │ └── TypeReference.kt
│ │ └── squareup
│ │ └── moshi
│ │ ├── MsgpackFormat.kt
│ │ ├── MsgpackReader.kt
│ │ ├── MsgpackWriter.kt
│ │ └── MsgpackWriterOptions.kt
│ └── test
│ ├── kotlin
│ ├── TestAgainstMessagePackJava.kt
│ ├── TestCatData.kt
│ ├── TestClasses.kt
│ ├── TestMessagePackReader.kt
│ ├── TestMessagePackWriter.kt
│ ├── TestReadAndWrite.kt
│ ├── TestTransform.kt
│ └── TestUtil.kt
│ └── resources
│ └── cats
└── settings.gradle
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | # Java Gradle CircleCI 2.0 configuration file
2 | #
3 | # Check https://circleci.com/docs/2.0/language-java/ for more details
4 | #
5 | version: 2
6 | jobs:
7 | build:
8 | docker:
9 | # specify the version you desire here
10 | - image: circleci/openjdk:8-jdk
11 |
12 | # Specify service dependencies here if necessary
13 | # CircleCI maintains a library of pre-built images
14 | # documented at https://circleci.com/docs/2.0/circleci-images/
15 | # - image: circleci/postgres:9.4
16 |
17 | working_directory: ~/repo
18 |
19 | environment:
20 | # Customize the JVM maximum heap limit
21 | JVM_OPTS: -Xmx3200m
22 | TERM: dumb
23 |
24 | steps:
25 | - checkout
26 |
27 | # Download and cache dependencies
28 | - restore_cache:
29 | keys:
30 | - v1-dependencies-{{ checksum "build.gradle" }}
31 | # fallback to using the latest cache if no exact match is found
32 | - v1-dependencies-
33 |
34 | - run: gradle allDeps
35 |
36 | - save_cache:
37 | paths:
38 | - ~/.gradle
39 | key: v1-dependencies-{{ checksum "build.gradle" }}
40 |
41 | # run tests!
42 | - run: gradle test
43 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | gradle.properties
2 | *.iml
3 | .gradle
4 | out
5 | .idea
6 | build
7 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "example-android-app"]
2 | path = example-android-app
3 | url = https://github.com/davethomas11/MoshiPack_AndroidAppExample.git
4 | [submodule "test-servers/node"]
5 | path = test-servers/node
6 | url = https://github.com/davethomas11/MoshiPack_TestNodeServer.git
7 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at davethomas11@icloud.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Accepting your help and pull requests!
2 |
3 | - Please create an issue to discuss any pull requests for new features or major bug fixes.
4 | - If the pull request is for a minor bug fix or typo, then no issue is required.
5 | - No tests must be deleted/ignored unless under API change or special requirements.
6 |
--------------------------------------------------------------------------------
/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ### Expected behaviour
2 |
3 | ### Actual behaviour
4 |
5 | ### Steps to reproduce behaviour
6 | ! Please provide a complete reproducable example with source code
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | MoshiPack
2 | =========
3 |
4 | [](https://circleci.com/gh/davethomas11/MoshiPack/tree/master)
5 |
6 | ### Gradle
7 |
8 |
9 | ```
10 | implementation com.daveanthonythomas.moshipack:moshipack:1.0.1
11 | ```
12 |
13 | Optional Retrofit support:
14 | ```
15 | implementation com.daveanthonythomas.moshipack:moshipack-retrofit:1.0.1
16 | ```
17 |
18 | ## About
19 |
20 | This is a Kotilin implementation of MessagePack serialization and deserialization built ontop of Moshi to take advantage of Moshi's type adapters and utilizes okio for reading and writing MessagePack bytes.
21 |
22 | The library is intended to be consumed in a Kotlin project, and is not intended for Java use.
23 |
24 | Inspired by Kaushik Gopal's [tweet](https://twitter.com/kaushikgopal/status/961426258818039808)
25 |
26 | See [Moshi](https://github.com/square/moshi) for adapter usage and reference.
27 |
28 | ### Convert an object to [MessagePack](https://msgpack.org) format
29 |
30 | ```kotlin
31 | data class MessagePackWebsitePlug(var compact: Boolean = true, var schema: Int = 0)
32 |
33 | val moshiPack = MoshiPack()
34 | val packed: BufferedSource = moshiPack.pack(MessagePackWebsitePlug())
35 |
36 | println(packed.readByteString().hex())
37 | ```
38 | This prints the MessagePack bytes as a hex string **82a7636f6d70616374c3a6736368656d6100**
39 |
40 | - **82** - Map with two entries
41 | - **a7** - String of seven bytes
42 | - **63 6f 6d 70 61 63 74** - UTF8 String "compact"
43 | - **c3** - Boolean value true
44 | - **a6** - String of size bytes
45 | - **73 63 68 65 6d 61** - UTF8 String "schema"
46 | - **00** - Integer value 0
47 |
48 |
49 | ### Convert binary MessagePack back to an Object
50 | ```kotlin
51 | val bytes = ByteString.decodeHex("82a7636f6d70616374c3a6736368656d6100").toByteArray()
52 |
53 | val moshiPack = MoshiPack()
54 | val plug: MessagePackWebsitePlug = moshiPack.unpack(bytes)
55 | ```
56 |
57 | ### Static API
58 |
59 | If you prefer to not instantiate a ```MoshiPack``` instance you can access the API in a static fashion as well. Note this will create a new ```Moshi``` instance every time you make an API call. You may want to use the API this way if you aren't providing ```MoshiPack``` by some form of dependency injection and you do not have any specific builder parameters for ```Moshi```
60 |
61 | ---
62 |
63 | ## Format Support
64 |
65 | See [MessagePack format spec](https://github.com/msgpack/msgpack/blob/master/spec.md) for further reference.
66 |
67 | format name | first byte (in binary) | first byte (in hex) | Supported |
68 | positive fixint | 0xxxxxxx | 0x00 - 0x7f | Yes |
69 | fixmap | 1000xxxx | 0x80 - 0x8f | Yes |
70 | fixarray | 1001xxxx | 0x90 - 0x9f | Yes |
71 | fixstr | 101xxxxx | 0xa0 - 0xbf | Yes |
72 | nil | 11000000 | 0xc0 | Yes |
73 | (never used) | 11000001 | 0xc1 | Yes |
74 | false | 11000010 | 0xc2 | Yes |
75 | true | 11000011 | 0xc3 | Yes |
76 | bin 8 | 11000100 | 0xc4 | No |
77 | bin 16 | 11000101 | 0xc5 | No |
78 | bin 32 | 11000110 | 0xc6 | No |
79 | ext 8 | 11000111 | 0xc7 | No |
80 | ext 16 | 11001000 | 0xc8 | No |
81 | ext 32 | 11001001 | 0xc9 | No |
82 | float 32 | 11001010 | 0xca | Yes |
83 | float 64 | 11001011 | 0xcb | Yes |
84 | uint 8 | 11001100 | 0xcc | Yes |
85 | uint 16 | 11001101 | 0xcd | Yes |
86 | uint 32 | 11001110 | 0xce | Yes |
87 | uint 64 | 11001111 | 0xcf | Yes |
88 | int 8 | 11010000 | 0xd0 | Yes |
89 | int 16 | 11010001 | 0xd1 | Yes |
90 | int 32 | 11010010 | 0xd2 | Yes |
91 | int 64 | 11010011 | 0xd3 | Yes |
92 | fixext 1 | 11010100 | 0xd4 | No |
93 | fixext 2 | 11010101 | 0xd5 | No |
94 | fixext 4 | 11010110 | 0xd6 | No |
95 | fixext 8 | 11010111 | 0xd7 | No |
96 | fixext 16 | 11011000 | 0xd8 | No |
97 | str 8 | 11011001 | 0xd9 | Yes |
98 | str 16 | 11011010 | 0xda | Yes |
99 | str 32 | 11011011 | 0xdb | Yes |
100 | array 16 | 11011100 | 0xdc | Yes |
101 | array 32 | 11011101 | 0xdd | Yes |
102 | map 16 | 11011110 | 0xde | Yes |
103 | map 32 | 11011111 | 0xdf | Yes |
104 | negative fixint | 111xxxxx | 0xe0 - 0xff | Yes |
105 |
106 |
107 | ---
108 |
109 | ## API
110 |
111 | ### pack
112 |
113 | Serializes an object into MessagePack. **Returns:** ```okio.BufferedSource```
114 |
115 | Instance version:
116 | ```kotlin
117 | MoshiPack().pack(anyObject)
118 | ```
119 |
120 | Static version:
121 | ```kotlin
122 | MoshiPack.pack(anyObject)
123 | ```
124 |
125 | ### packToByeArray
126 |
127 | If you prefer to get a ```ByteArray``` instead of a ```BufferedSource``` you can use this method.
128 |
129 | Instance version only
130 | ```kotlin
131 | MoshiPack().packToByteArray(anObject)
132 | ```
133 |
134 | Static can be done
135 | ```kotlin
136 | MoshiPack.pack(anObject).readByteArray()
137 | ```
138 |
139 | ### unpack
140 |
141 | Deserializes MessagePack bytes into an Object. **Returns:** ```T: Any```
142 | Works with ```ByteArray``` and ```okio.BufferedSource```
143 |
144 | Instance version:
145 | ```kotlin
146 | // T must be valid type so Moshi knows what to deserialize to
147 | val unpacked: T = MoshiPack().unpack(byteArray)
148 | ```
149 |
150 | Static version:
151 | ```kotlin
152 | val unpacked: T = MoshiPack.upack(byteArray)
153 | ```
154 |
155 | Instance version:
156 | ```kotlin
157 | val unpacked: T = MoshiPack().unpack(bufferedSource)
158 | ```
159 |
160 | Static version:
161 | ```kotlin
162 | val unpacked: T = MoshiPack.upack(bufferedSource)
163 | ```
164 |
165 | T can be an Object, a List, a Map, and can include generics. Unlike ```Moshi``` you do not need to specify a parameterized type to deserialize to a List with generics. ```MoshiPack``` can infer the paramterized type for you.
166 |
167 | The following examples are valid for ```MoshiPack```:
168 |
169 | A typed List
170 | ```kotlin
171 | val listCars: List = MoshiPack.unpack(carMsgPkBytes)
172 | ```
173 |
174 | A List of Any
175 | ```kotlin
176 | val listCars: List = MoshiPack.unpack(carMsgPkBytes)
177 | ```
178 |
179 | An Object
180 | ```kotlin
181 | val car: Car = MoshiPack.unpack(carBytes)
182 | ```
183 |
184 | A Map of Any, Any
185 | ```kotlin
186 | val car: Map = MoshiPack.unpack(carBytes)
187 | ```
188 |
189 | ### msgpackToJson
190 |
191 | Convert directly from MessagePack bytes to JSON. Use this method for the most effecient implementation as no objects are instantiated in the process. This uses the ```FormatInterchange``` class to match implementations of ```JsonReader``` and a ```JsonWriter```. If you wanted to say support XML as a direct conversion to and from, you could implement Moshi's ```JsonReader``` and ```JsonWriter``` classes and use the ```FormatInterchange``` class to convert directly to other formats. **Returns** ```String``` containing a JSON representation of the MessagePack data
192 |
193 | Instance versions: (takes ```ByteArray``` or ```BufferedSource```)
194 | ```kotlin
195 | MoshiPack().msgpackToJson(byteArray)
196 | ```
197 |
198 | ```kotlin
199 | MoshiPack().msgpackToJson(bufferedSource)
200 | ```
201 |
202 | Static versions: (takes ```ByteArray``` or ```BufferedSource```)
203 | ```kotlin
204 | MoshiPack.msgpackToJson(byteArray)
205 | ```
206 |
207 | ```kotlin
208 | MoshiPack.msgpackToJson(bufferedSource)
209 | ```
210 |
211 | ### jsonToMsgpack
212 |
213 | Convert directly from JSON to MessagePack bytes. Use this method for the most effecient implementation as no objects are instantiated in the process. **Returns** ```BufferedSource```
214 |
215 | Instance versions: (takes ```String``` or ```BufferedSource```)
216 | ```kotlin
217 | MoshiPack().jsonToMsgpack(jsonString)
218 | ```
219 |
220 | ```kotlin
221 | MoshiPack().jsonToMsgpack(bufferedSource)
222 | ```
223 |
224 | Static versions: (takes ```String``` or ```BufferedSource```)
225 | ```kotlin
226 | MoshiPack.jsonToMsgpack(jsonString)
227 | ```
228 |
229 | ```kotlin
230 | MoshiPack.jsonToMsgpack(bufferedSource)
231 | ```
232 |
233 | ### MoshiPack - constructor + Moshi builder
234 |
235 | The ```MoshiPack``` constructor takes an optional ```Moshi.Builder.() -> Unit``` lambda which is applied to the builder that is used to instantiate the ```Moshi``` instance it uses.
236 |
237 | Example adding custom adapter:
238 | ```kotlin
239 | val moshiPack = MoshiPack({
240 | add(customAdapter)
241 | })
242 | ```
243 |
244 | ```Moshi``` is also a settable property which can be changed on a ```MoshiPack``` instance:
245 | ```kotlin
246 | val m = MoshiPack()
247 | m.moshi = Moshi.Builder().build()
248 | ```
249 |
250 | The static version of the API also can be passed a lambda to applied to the ```Moshi.Builder``` used to instantiate ```Moshi```:
251 |
252 | ```kotlin
253 | MoshiPack.pack(someBytes) { add(customAdapter) }
254 | ```
255 |
256 |
257 | ### Forcing integers to write as certain format
258 | - new in v1.0.1
259 |
260 | This will force all integers to be packed as the type given.
261 | By default the smallest message pack type is used for integers.
262 | ```kotlin
263 | val moshiPack = MoshiPack().apply {
264 | writerOptions.writeAllIntsAs = MsgpackIntByte.INT_64
265 | }
266 | ```
267 |
268 |
269 | ---
270 |
271 | Kotiln Support
272 | --------------
273 |
274 | Since this library is intended for Kotlin use, the ```moshi-kotlin``` artifact is included as a depedency. A ```KotlinJsonAdapterFactory``` is added by default to the instantiated ```Moshi``` that ```MoshiPack``` uses.
275 | This adapter allows for the use of ```Moshi```'s annotaions in Kotlin. To learn more about it see the [```Moshi```](https://github.com/square/moshi) documentation.
276 |
277 | If you'd like to use ```Moshi``` with out a ```KotlinJsonAdapterFactory``` supply a ```Moshi``` instance for ```MoshiPack```:
278 | ```kotlin
279 | MoshiPack(moshi = Moshi.Builder().build)
280 | ```
281 |
282 | ProGuard
283 | --------
284 |
285 | From ```Moshi```'s README.md;
286 | If you are using ProGuard you might need to add the following options:
287 | ```
288 | -dontwarn okio.**
289 | -dontwarn javax.annotation.**
290 | -keepclasseswithmembers class * {
291 | @com.squareup.moshi.* ;
292 | }
293 | -keep @com.squareup.moshi.JsonQualifier interface *
294 | -keepclassmembers class kotlin.Metadata {
295 | public ;
296 | }
297 | ```
298 |
299 |
300 | Retrofit
301 | --------
302 |
303 | An example of using the retorfit adapter can be found here:
304 | https://github.com/davethomas11/MoshiPack_AndroidAppExample
305 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.kotlin_version = "1.3.11"
3 | ext.moshi_version = "1.5.0"
4 |
5 | repositories {
6 | mavenCentral()
7 | }
8 | dependencies {
9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
10 | }
11 | }
12 |
13 | allprojects {
14 | repositories {
15 | mavenCentral()
16 | }
17 | }
18 |
19 | subprojects {
20 | task allDeps(type: DependencyReportTask) {}
21 | group "com.daveanthonythomas.moshipack"
22 | version "1.0.1"
23 |
24 | apply plugin: "kotlin"
25 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davethomas11/MoshiPack/5f30e820923b5fde92e36a6fccf748dec8830504/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.8.1-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/moshipack-retrofit/build.gradle:
--------------------------------------------------------------------------------
1 | def retrofit_version = "2.3.0"
2 |
3 | dependencies {
4 | compile project(":moshipack")
5 | compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
6 | compile "com.squareup.retrofit2:retrofit:$retrofit_version"
7 | testCompile "junit:junit:4.12"
8 | testCompile "com.squareup.okhttp3:mockwebserver:3.10.0"
9 | }
10 |
11 | compileKotlin {
12 | kotlinOptions.jvmTarget = "1.6"
13 | }
14 | compileTestKotlin {
15 | kotlinOptions.jvmTarget = "1.6"
16 | }
17 |
18 | test {
19 | testLogging {
20 | events "passed", "skipped", "failed"
21 | }
22 | }
23 |
24 | apply plugin: 'maven'
25 | apply plugin: 'signing'
26 |
27 | task javadocJar(type: Jar) {
28 | classifier = 'javadoc'
29 | from javadoc
30 | }
31 |
32 | task sourcesJar(type: Jar) {
33 | classifier = 'sources'
34 | from sourceSets.main.allSource
35 | }
36 |
37 | artifacts {
38 | archives javadocJar, sourcesJar
39 | }
40 |
41 | signing {
42 | sign configurations.archives
43 | }
44 |
45 | if (project.hasProperty("ossrhUsername")) {
46 | uploadArchives {
47 | repositories {
48 | mavenDeployer {
49 | beforeDeployment { deployment -> signing.signPom(deployment) }
50 |
51 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
52 | authentication(userName: ossrhUsername, password: ossrhPassword)
53 | }
54 |
55 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
56 | authentication(userName: ossrhUsername, password: ossrhPassword)
57 | }
58 |
59 | pom.project {
60 | name 'MoshiPack Retrofit Adapter'
61 | packaging 'jar'
62 | artifactId "moshipack-retrofit"
63 | description 'MessagePack converter for Retrofit'
64 | url 'https://github.com/davethomas11/MoshiPack'
65 |
66 | scm {
67 | connection 'git@github.com:davethomas11/MoshiPack.git'
68 | developerConnection 'git@github.com:davethomas11/MoshiPack.git'
69 | url 'https://github.com/davethomas11/MoshiPack/tree/master/moshipack-retrofit'
70 | }
71 |
72 | licenses {
73 | license {
74 | name 'The Apache License, Version 2.0'
75 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
76 | }
77 | }
78 |
79 | developers {
80 | developer {
81 | id 'davethomas11'
82 | name 'Dave Anthony Thomas'
83 | email 'davethomas11@icloud.com'
84 | }
85 | }
86 | }
87 | }
88 | }
89 | }
90 | }
--------------------------------------------------------------------------------
/moshipack-retrofit/src/main/kotlin/com/daveanthonythomas/moshipack/MoshiPackConverterFactory.kt:
--------------------------------------------------------------------------------
1 | package com.daveanthonythomas.moshipack
2 |
3 | import com.squareup.moshi.JsonAdapter
4 | import com.squareup.moshi.MsgpackReader
5 | import com.squareup.moshi.MsgpackWriter
6 | import okhttp3.MediaType
7 | import okhttp3.RequestBody
8 | import okhttp3.ResponseBody
9 | import okio.Buffer
10 | import retrofit2.Converter
11 | import retrofit2.Retrofit
12 | import java.lang.reflect.Type
13 | import java.util.Collections.emptySet
14 | import java.util.Collections.unmodifiableSet
15 | import com.squareup.moshi.JsonQualifier
16 | import java.util.*
17 | import com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.close
18 | import com.squareup.moshi.JsonDataException
19 | import com.squareup.moshi.JsonReader
20 | import okio.ByteString
21 | import okio.ByteString.decodeHex
22 |
23 |
24 |
25 |
26 |
27 |
28 | class MoshiPackConverterFactory(val moshiPack: MoshiPack = MoshiPack(),
29 | val failOnUnknown: Boolean = false,
30 | val serializeNull: Boolean = false) : Converter.Factory() {
31 |
32 | companion object {
33 | val UTF8_BOM = ByteString.decodeHex("EFBBBF")
34 | }
35 |
36 | override fun responseBodyConverter(type: Type?,
37 | annotations: Array?,
38 | retrofit: Retrofit?): Converter? {
39 | return if (type != null && annotations != null) {
40 | var adapter = moshiPack.moshi.adapter(type, jsonAnnotations(annotations))
41 | if (failOnUnknown) adapter = adapter.failOnUnknown()
42 | if (serializeNull) adapter = adapter.serializeNulls()
43 | return MoshiPackResponseBodyConverter(adapter)
44 | } else null
45 | }
46 |
47 | override fun requestBodyConverter(type: Type?,
48 | parameterAnnotations: Array?,
49 | methodAnnotations: Array?,
50 | retrofit: Retrofit?): Converter<*, RequestBody>? {
51 | return if (type != null && parameterAnnotations != null) {
52 | var adapter = moshiPack.moshi.adapter(type, jsonAnnotations(parameterAnnotations))
53 | if (failOnUnknown) adapter = adapter.failOnUnknown()
54 | if (serializeNull) adapter = adapter.serializeNulls()
55 | return MoshiPackRequestBodyConverter(adapter)
56 | } else null
57 | }
58 |
59 | private class MoshiPackResponseBodyConverter(private val adapter: JsonAdapter) : Converter {
60 |
61 | override fun convert(value: ResponseBody?): T? = if (value != null) {
62 | val source = value.source()
63 | value.use {
64 | // Moshi has no document-level API so the responsibility of BOM skipping falls to whatever
65 | // is delegating to it. Since it's a UTF-8-only library as well we only honor the UTF-8 BOM.
66 | if (source.rangeEquals(0, UTF8_BOM)) {
67 | source.skip(UTF8_BOM.size().toLong())
68 | }
69 | val reader = MsgpackReader(source)
70 | adapter.fromJson(reader)
71 | }
72 | } else {
73 | null
74 | }
75 | }
76 |
77 | private class MoshiPackRequestBodyConverter(private val adapter: JsonAdapter) : Converter {
78 | private val MEDIA_TYPE = MediaType.parse("application/x-msgpack; charset=utf-8")
79 |
80 | override fun convert(value: T): RequestBody {
81 | val buffer = Buffer()
82 | adapter.toJson(MsgpackWriter(buffer), value)
83 | return RequestBody.create(MEDIA_TYPE, buffer.readByteString())
84 | }
85 | }
86 |
87 | private fun jsonAnnotations(annotations: Array): Set {
88 | var result: MutableSet? = null
89 | for (annotation in annotations) {
90 | if (annotation.annotationClass.java.isAnnotationPresent(JsonQualifier::class.java)) {
91 | if (result == null) result = LinkedHashSet()
92 | result.add(annotation)
93 | }
94 | }
95 | return if (result != null) unmodifiableSet(result) else emptySet()
96 | }
97 | }
--------------------------------------------------------------------------------
/moshipack-retrofit/src/test/kotlin/TestMoshiPackRetrofit.kt:
--------------------------------------------------------------------------------
1 | import com.daveanthonythomas.moshipack.MoshiPackConverterFactory
2 | import okhttp3.mockwebserver.MockResponse
3 | import okhttp3.mockwebserver.MockWebServer
4 | import okio.Buffer
5 | import org.junit.Assert.assertEquals
6 | import org.junit.Rule
7 | import org.junit.Test
8 | import retrofit2.Call
9 | import retrofit2.Retrofit
10 | import retrofit2.http.GET
11 |
12 | class TestMoshiPackRetrofit {
13 |
14 | @Rule @JvmField
15 | var server = MockWebServer()
16 |
17 | interface Cats {
18 | @GET("/")
19 | fun cats(): Call>
20 | }
21 |
22 | @Test
23 | fun testCats() {
24 | val buffer = Buffer().apply { write(TestMoshiPackRetrofit::class.java.getResource("cats").readBytes()) }
25 | server.enqueue(MockResponse().setBody(buffer))
26 |
27 | val retrofit = Retrofit.Builder()
28 | .baseUrl(server.url("/"))
29 | .addConverterFactory(MoshiPackConverterFactory())
30 | .build()
31 |
32 | val catsEndpoint = retrofit.create(Cats::class.java)
33 | val call = catsEndpoint.cats()
34 | val response = call.execute()
35 |
36 | assertEquals(32, response.body()?.size)
37 | }
38 | }
39 |
40 | class Cat {
41 | var breed: String = ""
42 | var country: String? = null
43 | var origin: String? = null
44 | var bodytype: String? = null
45 | var coat: String? = null
46 | var pattern: String? = null
47 | var image: String? = null
48 | }
--------------------------------------------------------------------------------
/moshipack-retrofit/src/test/resources/cats:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davethomas11/MoshiPack/5f30e820923b5fde92e36a6fccf748dec8830504/moshipack-retrofit/src/test/resources/cats
--------------------------------------------------------------------------------
/moshipack/build.gradle:
--------------------------------------------------------------------------------
1 | dependencies {
2 | compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
3 | compile "com.squareup.moshi:moshi:$moshi_version"
4 | compile "com.squareup.moshi:moshi-kotlin:$moshi_version"
5 | testCompile "junit:junit:4.12"
6 | testCompile "org.msgpack:msgpack-core:0.8.14"
7 | }
8 |
9 | compileKotlin {
10 | kotlinOptions.jvmTarget = "1.6"
11 | }
12 | compileTestKotlin {
13 | kotlinOptions.jvmTarget = "1.6"
14 | }
15 |
16 | test {
17 | testLogging {
18 | events "passed", "skipped", "failed"
19 | }
20 | }
21 |
22 | apply plugin: 'maven'
23 | apply plugin: 'signing'
24 |
25 | task javadocJar(type: Jar) {
26 | classifier = 'javadoc'
27 | from javadoc
28 | }
29 |
30 | task sourcesJar(type: Jar) {
31 | classifier = 'sources'
32 | from sourceSets.main.allSource
33 | }
34 |
35 | artifacts {
36 | archives javadocJar, sourcesJar
37 | }
38 |
39 | signing {
40 | sign configurations.archives
41 | }
42 |
43 | if (project.hasProperty("ossrhUsername")) {
44 | uploadArchives {
45 | repositories {
46 | mavenDeployer {
47 | beforeDeployment { deployment -> signing.signPom(deployment) }
48 |
49 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
50 | authentication(userName: ossrhUsername, password: ossrhPassword)
51 | }
52 |
53 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
54 | authentication(userName: ossrhUsername, password: ossrhPassword)
55 | }
56 |
57 | pom.project {
58 | name 'MoshiPack'
59 | packaging 'jar'
60 | artifactId "moshipack"
61 | description 'MessagePack implementation built on top of Moshi in Kotlin'
62 | url 'https://github.com/davethomas11/MoshiPack'
63 |
64 | scm {
65 | connection 'git@github.com:davethomas11/MoshiPack.git'
66 | developerConnection 'git@github.com:davethomas11/MoshiPack.git'
67 | url 'https://github.com/davethomas11/MoshiPack/tree/master/moshipack'
68 | }
69 |
70 | licenses {
71 | license {
72 | name 'The Apache License, Version 2.0'
73 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
74 | }
75 | }
76 |
77 | developers {
78 | developer {
79 | id 'davethomas11'
80 | name 'Dave Anthony Thomas'
81 | email 'davethomas11@icloud.com'
82 | }
83 | }
84 | }
85 | }
86 | }
87 | }
88 | }
--------------------------------------------------------------------------------
/moshipack/src/main/kotlin/com/daveanthonythomas/moshipack/FormatInterchange.kt:
--------------------------------------------------------------------------------
1 | package com.daveanthonythomas.moshipack
2 |
3 | import com.squareup.moshi.*
4 | import okio.Buffer
5 | import okio.BufferedSink
6 | import okio.BufferedSource
7 |
8 | class FormatInterchange(val formatIn: Format, val formatOut: Format) {
9 |
10 | private fun transform(reader: JsonReader, writer: JsonWriter) {
11 | doValue(reader, writer)
12 | writer.close()
13 | reader.close()
14 | }
15 |
16 | private fun doValue(reader: JsonReader, writer: JsonWriter) {
17 | when(reader.peek()) {
18 | JsonReader.Token.BEGIN_ARRAY -> doArray(reader, writer)
19 | JsonReader.Token.BEGIN_OBJECT -> doObject(reader, writer)
20 | JsonReader.Token.STRING -> writer.value(reader.nextString())
21 | JsonReader.Token.NUMBER -> writer.value(reader.nextDouble())
22 | JsonReader.Token.BOOLEAN -> writer.value(reader.nextBoolean())
23 | JsonReader.Token.NULL -> writer.nullValue().also { reader.nextNull() }
24 | }
25 | }
26 |
27 | private fun doObject(reader: JsonReader, writer: JsonWriter) {
28 | reader.beginObject()
29 | writer.beginObject()
30 | while (reader.hasNext()) {
31 | writer.name(reader.nextName())
32 | doValue(reader, writer)
33 | }
34 | reader.endObject()
35 | writer.endObject()
36 | }
37 |
38 | private fun doArray(reader: JsonReader, writer: JsonWriter) {
39 | reader.beginArray()
40 | writer.beginArray()
41 | while (reader.hasNext()) {
42 | doValue(reader, writer)
43 | }
44 | reader.endArray()
45 | writer.endArray()
46 | }
47 |
48 | fun transform(source: BufferedSource) = Buffer().also {
49 | transform(formatIn.reader(source), formatOut.writer(it))
50 | }
51 | }
52 |
53 | sealed class Format {
54 | class Json: Format() {
55 | override fun reader(source: BufferedSource) = JsonReader.of(source).apply { isLenient = true }
56 | override fun writer(sink: BufferedSink) = JsonWriter.of(sink)
57 | }
58 | class Msgpack(val writerOptions: MsgpackWriterOptions = MsgpackWriterOptions()): Format() {
59 | override fun reader(source: BufferedSource) = MsgpackReader(source)
60 | override fun writer(sink: BufferedSink) = MsgpackWriter(sink).apply { writerOptions }
61 | }
62 |
63 | abstract fun reader(source: BufferedSource): JsonReader
64 | abstract fun writer(sink: BufferedSink): JsonWriter
65 | }
66 |
--------------------------------------------------------------------------------
/moshipack/src/main/kotlin/com/daveanthonythomas/moshipack/MoshiPack.kt:
--------------------------------------------------------------------------------
1 | package com.daveanthonythomas.moshipack
2 |
3 | import com.squareup.moshi.*
4 | import okio.Buffer
5 | import okio.BufferedSource
6 | import java.lang.reflect.Type
7 |
8 | class MoshiPack(private var builder: Moshi.Builder.() -> kotlin.Unit = {},
9 | var moshi: Moshi = MoshiPack.moshi(builder),
10 | var writerOptions: MsgpackWriterOptions = MsgpackWriterOptions()) {
11 |
12 | private val mpToJson by lazy {
13 | FormatInterchange(Format.Msgpack(), Format.Json())
14 | }
15 |
16 | private val jsonToMp by lazy {
17 | FormatInterchange(Format.Json(), Format.Msgpack())
18 | }
19 |
20 | companion object {
21 | inline fun pack(value: T, moshiPack: MoshiPack): BufferedSource =
22 | Buffer().also {
23 | moshiPack.moshi.adapter(T::class.java)
24 | .toJson(MsgpackWriter(it).apply { options = moshiPack.writerOptions }, value)
25 | }
26 |
27 | inline fun pack(value: T,
28 | moshi: Moshi,
29 | writerOptions: MsgpackWriterOptions = MsgpackWriterOptions()): BufferedSource =
30 | Buffer().also {
31 | moshi.adapter(T::class.java)
32 | .toJson(MsgpackWriter(it).apply { options = writerOptions }, value)
33 | }
34 |
35 | inline fun pack(value: T,
36 | crossinline builder: Moshi.Builder.() -> Unit = {},
37 | writerOptions: MsgpackWriterOptions = MsgpackWriterOptions()): BufferedSource =
38 | pack(value, moshi(builder), writerOptions)
39 |
40 | inline fun unpack(source: BufferedSource, moshi: Moshi): T {
41 | val type: Type = object : TypeReference() {}.type
42 | return moshi.adapter(type).fromJson(MsgpackReader(source)) as T
43 | }
44 |
45 | inline fun unpack(source: BufferedSource, crossinline builder: Moshi.Builder.() -> Unit = {}): T =
46 | unpack(source, moshi(builder))
47 |
48 | inline fun unpack(bytes: ByteArray, moshi: Moshi): T =
49 | unpack(Buffer().apply { write(bytes) }, moshi)
50 |
51 | inline fun unpack(bytes: ByteArray, crossinline builder: Moshi.Builder.() -> Unit = {}): T =
52 | unpack(Buffer().apply { write(bytes) }, builder)
53 |
54 | inline fun moshi(crossinline builder: Moshi.Builder.() -> Unit = {}) =
55 | Moshi.Builder().apply(builder).add(KotlinJsonAdapterFactory()).build()
56 |
57 | fun msgpackToJson(bytes: ByteArray,
58 | writerOptions: MsgpackWriterOptions = MsgpackWriterOptions()): String =
59 | msgpackToJson(Buffer().apply { write(bytes) }, writerOptions)
60 |
61 | fun msgpackToJson(source: BufferedSource,
62 | writerOptions: MsgpackWriterOptions = MsgpackWriterOptions()) =
63 | FormatInterchange(Format.Msgpack(writerOptions), Format.Json())
64 | .transform(source).readUtf8()
65 |
66 | fun jsonToMsgpack(jsonString: String,
67 | writerOptions: MsgpackWriterOptions = MsgpackWriterOptions()) =
68 | jsonToMsgpack(Buffer().apply { writeUtf8(jsonString) })
69 |
70 | fun jsonToMsgpack(source: BufferedSource,
71 | writerOptions: MsgpackWriterOptions = MsgpackWriterOptions()): BufferedSource =
72 | FormatInterchange(Format.Json(), Format.Msgpack(writerOptions))
73 | .transform(source)
74 | }
75 |
76 | inline fun pack(value: T) = MoshiPack.pack(value, this)
77 | inline fun packToByteArray(value: T): ByteArray = pack(value).readByteArray()
78 | inline fun unpack(bytes: ByteArray): T = unpack(Buffer().apply { write(bytes) })
79 | inline fun unpack(source: BufferedSource): T = MoshiPack.unpack(source, moshi)
80 |
81 | fun msgpackToJson(bytes: ByteArray): String = msgpackToJson(Buffer().apply { write(bytes) })
82 | fun msgpackToJson(source: BufferedSource) = mpToJson.transform(source).readUtf8()
83 |
84 | fun jsonToMsgpack(jsonString: String) = jsonToMsgpack(Buffer().apply { writeUtf8(jsonString) })
85 | fun jsonToMsgpack(source: BufferedSource): BufferedSource = jsonToMp.transform(source)
86 | }
87 |
--------------------------------------------------------------------------------
/moshipack/src/main/kotlin/com/daveanthonythomas/moshipack/TypeReference.kt:
--------------------------------------------------------------------------------
1 | package com.daveanthonythomas.moshipack
2 |
3 | import com.squareup.moshi.Types
4 | import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
5 | import sun.reflect.generics.reflectiveObjects.WildcardTypeImpl
6 | import java.lang.reflect.ParameterizedType
7 | import java.lang.reflect.Type
8 |
9 | /**
10 | * Base on http://gafter.blogspot.ca/2006/12/super-type-tokens.html
11 | * To help with type erasure of generics in reified types.
12 | * This class helps us so we can unpack to for example a List
13 | * with out having to supply a ParameterizedType to MoshiPack.
14 | * MoshiPack uses this to figure out the ParameterizedType iteself
15 | * for Moshi.
16 | */
17 | abstract class TypeReference {
18 | val type: Type
19 |
20 | init {
21 | val superclass = javaClass.genericSuperclass
22 | if (superclass is Class<*>) {
23 | throw RuntimeException("Missing type parameter.")
24 | }
25 |
26 | val args = (superclass as ParameterizedType).actualTypeArguments
27 | this.type = forceBounds(args[0])
28 | }
29 |
30 | private fun forceBounds(type: Type): Type = if (type is ParameterizedType) {
31 | val bounded = type.actualTypeArguments.map {
32 | forceBounds(if (it is WildcardTypeImpl) {
33 | if (it.upperBounds?.size?.compareTo(0) ?: 0 > 0) {
34 | it.upperBounds[0]
35 | } else it
36 | } else it)
37 | }
38 | Types.newParameterizedType(type.rawType, *bounded.toTypedArray())
39 | } else type
40 | }
--------------------------------------------------------------------------------
/moshipack/src/main/kotlin/com/squareup/moshi/MsgpackFormat.kt:
--------------------------------------------------------------------------------
1 | package com.squareup.moshi
2 |
3 | import okio.BufferedSink
4 | import okio.BufferedSource
5 |
6 | object MsgpackFormat {
7 |
8 | const val FIX_INT_MAX = 0x7f
9 | const val FIX_INT_MIN = -32
10 |
11 | const val SIZE_8 = 255L
12 | const val SIZE_16 = 65535L
13 | const val SIZE_32 = 4294967295
14 |
15 | const val NIL = 0xc0.toByte()
16 | const val FALSE = 0xc2.toByte()
17 | const val TRUE = 0xc3.toByte()
18 |
19 | const val FLOAT_32 = 0xca.toByte()
20 | const val FLOAT_64 = 0xcb.toByte()
21 |
22 | const val UINT_8_MIN = 128
23 | const val UINT_8_MAX = 255
24 | const val UINT_8 = 0xcc.toByte()
25 |
26 | const val UINT_16_MIN = 256
27 | const val UINT_16_MAX = 32767
28 | const val UINT_16 = 0xcd.toByte()
29 |
30 | const val UINT_32_MIN = 32768
31 | const val UINT_32_MAX = 32768*32768/2-1
32 | const val UINT_32 = 0xce.toByte()
33 |
34 | const val UINT_64 = 0xcf.toByte()
35 |
36 | const val INT_8 = 0xd0.toByte()
37 | const val INT_16 = 0xd1.toByte()
38 | const val INT_32 = 0xd2.toByte()
39 | const val INT_64 = 0xd3.toByte()
40 |
41 | val FIX_STR = MsgpackFormatType(0xa0.toByte(), 31, isFix = true)
42 |
43 | val STR_8 = MsgpackFormatType(0xd9.toByte(), SIZE_8)
44 | val STR_16 = MsgpackFormatType(0xda.toByte(), SIZE_16)
45 | val STR_32 = MsgpackFormatType(0xdb.toByte(), SIZE_32)
46 | val STR = arrayOf(FIX_STR, STR_8, STR_16, STR_32)
47 |
48 | val FIX_ARRAY = MsgpackFormatType(0x90.toByte(), 15, isFix = true)
49 | val ARRAY_16 = MsgpackFormatType(0xdc.toByte(), SIZE_16)
50 | val ARRAY_32 = MsgpackFormatType(0xdd.toByte(), SIZE_32)
51 | val ARRAY = arrayOf(FIX_ARRAY, ARRAY_16, ARRAY_32)
52 |
53 | val FIX_MAP = MsgpackFormatType(0x80.toByte(), 15, isFix = true)
54 | val MAP_16 = MsgpackFormatType(0xde.toByte(), SIZE_16)
55 | val MAP_32 = MsgpackFormatType(0xdf.toByte(), SIZE_32)
56 | val MAP = arrayOf(FIX_MAP, MAP_16, MAP_32)
57 |
58 | fun tagFor(type: Array, size: Int) =
59 | type.filter {
60 | it.maxSize > size
61 | }.minBy {
62 | it.maxSize
63 | }
64 | }
65 |
66 | operator fun Array.contains(value: Byte) = this.any { value in it }
67 | fun Array.typeFor(value: Byte) = this.firstOrNull { value in it }
68 |
69 | data class MsgpackFormatType(val tag: Byte, val maxSize: Long, val isFix: Boolean = false) {
70 |
71 | operator fun contains(value: Byte) = if (isFix) value in tag..tag+maxSize else value == tag
72 |
73 | fun writeTag(sink: BufferedSink, size: Int) {
74 | sink.writeByte(tag + if (isFix) size else 0)
75 | if (!isFix) writeSize(sink, size)
76 | }
77 |
78 | fun readSize(source: BufferedSource, value: Byte): Long = if (isFix) (value - tag).toLong() else when (maxSize) {
79 | MsgpackFormat.SIZE_8 -> source.readByte().toLong() and 0xff
80 | MsgpackFormat.SIZE_16 -> source.readShort().toLong() and 0xffff
81 | MsgpackFormat.SIZE_32 -> source.readInt().toLong() and 0xffffffff
82 | else -> throw IllegalStateException("Unable to read size for tag type: 0x" + value.toString(16))
83 | }
84 |
85 | private fun writeSize(sink: BufferedSink, size: Int) {
86 | when (maxSize) {
87 | MsgpackFormat.SIZE_8 -> sink.writeByte(size)
88 | MsgpackFormat.SIZE_16 -> sink.writeShort(size)
89 | MsgpackFormat.SIZE_32 -> sink.writeInt(size)
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/moshipack/src/main/kotlin/com/squareup/moshi/MsgpackReader.kt:
--------------------------------------------------------------------------------
1 | package com.squareup.moshi
2 |
3 | import com.squareup.moshi.JsonScope.EMPTY_DOCUMENT
4 | import com.squareup.moshi.JsonScope.NONEMPTY_OBJECT
5 | import okio.BufferedSource
6 | import java.io.IOException
7 |
8 | class MsgpackReader(private val source: BufferedSource) : JsonReader() {
9 |
10 | private val PEEKED_NONE = 0
11 | private val PEEKED_BEGIN_OBJECT = 1
12 | private val PEEKED_END_OBJECT = 2
13 | private val PEEKED_BEGIN_ARRAY = 3
14 | private val PEEKED_END_ARRAY = 4
15 | private val PEEKED_TRUE = 5
16 | private val PEEKED_FALSE = 6
17 | private val PEEKED_NULL = 7
18 | private val PEEKED_STRING = 8
19 | private val PEEKED_LONG = 16
20 | private val PEEKED_DOUBLE = 17
21 | private val PEEKED_EOF = 18
22 | private val PEEKED_BUFFERED = 19
23 | private val PEEKED_BUFFERED_NAME = 20
24 |
25 | private var promotedNameToValue = false
26 | private var peekedString: String = ""
27 | var pathSize = LongArray(32) { 0 }
28 | var currentTag: Byte = 0
29 | private val buffer = source.buffer()
30 | var peeked = PEEKED_NONE
31 |
32 | init {
33 | pushScope(EMPTY_DOCUMENT)
34 | }
35 |
36 | override fun beginArray() {
37 | val p = peeked
38 | if (p == PEEKED_NONE) doPeek()
39 | pushScope(JsonScope.EMPTY_ARRAY)
40 | peeked = PEEKED_NONE
41 | pathIndices[stackSize - 1] = 0
42 | pathSize[stackSize - 1] = MsgpackFormat.ARRAY.typeFor(currentTag)?.readSize(source, currentTag)
43 | ?: throw IllegalStateException("Current tag 0x${currentTag.toString(16)} is not an array tag.")
44 | }
45 |
46 | override fun endArray() {
47 | stackSize--
48 | pathNames[stackSize] = null // Free the last path name so that it can be garbage collected!
49 | pathIndices[stackSize - 1]++
50 | }
51 |
52 | override fun beginObject() {
53 | val p = peeked
54 | if (p == PEEKED_NONE) doPeek()
55 | pushScope(JsonScope.EMPTY_OBJECT)
56 | peeked = PEEKED_NONE
57 | pathIndices[stackSize - 1] = 0
58 | pathSize[stackSize - 1] = MsgpackFormat.MAP.typeFor(currentTag)?.readSize(source, currentTag)
59 | ?: throw IllegalStateException("Current tag 0x${currentTag.toString(16)} is not a map tag.")
60 | }
61 |
62 | override fun endObject() {
63 | stackSize--
64 | pathNames[stackSize] = null // Free the last path name so that it can be garbage collected!
65 | pathIndices[stackSize - 1]++
66 | }
67 |
68 | private fun readString(): String {
69 | if (peeked == PEEKED_NONE) doPeek()
70 |
71 | val readBytes = MsgpackFormat.STR.typeFor(currentTag)?.readSize(source, currentTag)
72 | ?: throw IllegalStateException("Current tag 0x${currentTag.toString(16)} is not a string tag.")
73 | return source.readUtf8(readBytes)
74 | }
75 |
76 | override fun nextBoolean(): Boolean {
77 | if (peeked == PEEKED_NONE) doPeek()
78 | peeked = PEEKED_NONE
79 | pathIndices[stackSize - 1]++
80 |
81 | return currentTag == MsgpackFormat.TRUE
82 | }
83 |
84 | override fun nextNull(): T? {
85 | if (peeked == PEEKED_NONE) doPeek()
86 | peeked = PEEKED_NONE
87 | pathIndices[stackSize - 1]++
88 |
89 | return null
90 | }
91 |
92 | override fun nextDouble(): Double = readNumber().toDouble()
93 |
94 | override fun nextLong(): Long = readNumber().toLong()
95 |
96 | override fun nextInt(): Int = readNumber().toInt()
97 |
98 | private fun readNumber(): Number {
99 | val p = peeked
100 | if (p == PEEKED_NONE) doPeek()
101 |
102 | pathIndices[stackSize - 1]++
103 | peeked = PEEKED_NONE
104 |
105 | return when (currentTag) {
106 | in MsgpackFormat.STR -> {
107 | val readBytes = MsgpackFormat.STR.typeFor(currentTag)?.readSize(source, currentTag)
108 | if (readBytes != null) {
109 | source.readUtf8(readBytes).toDouble()
110 | } else {
111 | throw AssertionError()
112 | }
113 | }
114 | MsgpackFormat.UINT_8 -> source.readByte().toInt() and 0xff
115 | MsgpackFormat.UINT_16 -> source.readShort().toInt() and 0xffff
116 | MsgpackFormat.UINT_32 -> source.readInt().toLong() and 0xffffffff
117 | MsgpackFormat.UINT_64 -> source.readLong()
118 | in MsgpackFormat.FIX_INT_MIN..MsgpackFormat.FIX_INT_MAX -> currentTag
119 | MsgpackFormat.FLOAT_64 -> Double.fromBits(source.readLong())
120 | MsgpackFormat.FLOAT_32 -> java.lang.Float.intBitsToFloat(source.readInt())
121 | MsgpackFormat.INT_8 -> source.readByte()
122 | MsgpackFormat.INT_32 -> source.readInt()
123 | MsgpackFormat.INT_16 -> source.readShort()
124 | MsgpackFormat.INT_64 -> source.readLong()
125 | else -> throw IllegalStateException("Current tag 0x${currentTag.toString(16)} is not a supported number tag.")
126 | }
127 | }
128 |
129 | override fun close() {
130 | peeked = PEEKED_NONE
131 | scopes[0] = JsonScope.CLOSED
132 | stackSize = 1
133 | buffer.clear()
134 | source.close()
135 | }
136 |
137 | override fun hasNext(): Boolean {
138 | val p = peeked
139 | if (p == PEEKED_NONE) doPeek()
140 | return pathIndices[stackSize - 1] < pathSize[stackSize - 1]
141 | }
142 |
143 | @Throws(IOException::class)
144 | override fun nextName(): String {
145 | var p = peeked
146 | if (p == PEEKED_NONE) {
147 | p = doPeek()
148 | }
149 | val result: String
150 | if (p == PEEKED_STRING) {
151 | result = readString()
152 | } else if (p == PEEKED_BUFFERED_NAME) {
153 | result = peekedString
154 | } else {
155 | throw JsonDataException("Expected a name but was " + peek() + " at path " + path)
156 | }
157 | peeked = PEEKED_NONE
158 | pathNames[stackSize - 1] = result
159 | return result
160 | }
161 |
162 | @Throws(IOException::class)
163 | override fun selectName(options: JsonReader.Options): Int {
164 | var p = peeked
165 | if (p == PEEKED_NONE) {
166 | p = doPeek()
167 | }
168 | if (p != PEEKED_STRING && p != PEEKED_BUFFERED_NAME) {
169 | return -1
170 | }
171 | if (p == PEEKED_BUFFERED_NAME) {
172 | return findName(peekedString, options)
173 | }
174 |
175 | // Save the last recorded path name, so that we
176 | // can restore the peek state in case we fail to find a match.
177 | val lastPathName = pathNames[stackSize - 1]
178 |
179 | val nextName = nextName()
180 | val result = findName(nextName, options)
181 |
182 | if (result == -1) {
183 | peeked = PEEKED_BUFFERED_NAME
184 | peekedString = nextName
185 | // We can't push the path further, make it seem like nothing happened.
186 | pathNames[stackSize - 1] = lastPathName
187 | }
188 |
189 | return result
190 | }
191 |
192 | /**
193 | * If `name` is in `options` this consumes it and returns it's index.
194 | * Otherwise this returns -1 and no name is consumed.
195 | */
196 | private fun findName(name: String, options: JsonReader.Options): Int {
197 | var i = 0
198 | val size = options.strings.size
199 | while (i < size) {
200 | if (name == options.strings[i]) {
201 | peeked = PEEKED_NONE
202 | pathNames[stackSize - 1] = name
203 |
204 | return i
205 | }
206 | i++
207 | }
208 | return -1
209 | }
210 |
211 | @Throws(IOException::class)
212 | override fun nextString(): String {
213 | var p = peeked
214 | if (p == PEEKED_NONE) {
215 | p = doPeek()
216 | }
217 | val result: String
218 | if (p == PEEKED_STRING) {
219 | result = readString()
220 | } else if (p == PEEKED_BUFFERED) {
221 | result = peekedString
222 | peekedString = ""
223 | } else if (p == PEEKED_LONG) {
224 | result = nextDouble().toString()
225 | } else {
226 | throw JsonDataException("Expected a string but was " + peek() + " at path " + path)
227 | }
228 | peeked = PEEKED_NONE
229 | if (!promotedNameToValue) pathIndices[stackSize - 1]++
230 | else promotedNameToValue = false
231 | return result
232 | }
233 |
234 | @Throws(IOException::class)
235 | override fun selectString(options: JsonReader.Options): Int {
236 | var p = peeked
237 | if (p == PEEKED_NONE) {
238 | p = doPeek()
239 | }
240 | if (p != PEEKED_STRING && p != PEEKED_BUFFERED) {
241 | return -1
242 | }
243 | if (p == PEEKED_BUFFERED) {
244 | return findString(peekedString, options)
245 | }
246 |
247 | val nextString = nextString()
248 | val result = findString(nextString, options)
249 |
250 | if (result == -1) {
251 | peeked = PEEKED_BUFFERED
252 | peekedString = nextString
253 | pathIndices[stackSize - 1]--
254 | }
255 |
256 | return result
257 | }
258 |
259 | /**
260 | * If `string` is in `options` this consumes it and returns it's index.
261 | * Otherwise this returns -1 and no string is consumed.
262 | */
263 | private fun findString(string: String, options: JsonReader.Options): Int {
264 | var i = 0
265 | val size = options.strings.size
266 | while (i < size) {
267 | if (string == options.strings[i]) {
268 | peeked = PEEKED_NONE
269 | pathIndices[stackSize - 1]++
270 |
271 | return i
272 | }
273 | i++
274 | }
275 | return -1
276 | }
277 |
278 | override fun promoteNameToValue() {
279 | if (hasNext()) {
280 | peekedString = nextName()
281 | peeked = PEEKED_BUFFERED
282 | promotedNameToValue = true
283 | }
284 | }
285 |
286 | override fun skipValue() {
287 | if (peeked == PEEKED_NONE) doPeek()
288 | when (peek()) {
289 | JsonReader.Token.BEGIN_ARRAY -> skipArray()
290 | JsonReader.Token.BEGIN_OBJECT -> skipObject()
291 | JsonReader.Token.STRING -> nextString()
292 | JsonReader.Token.NUMBER -> readNumber()
293 | JsonReader.Token.BOOLEAN -> nextBoolean()
294 | JsonReader.Token.NULL -> {
295 | peeked = PEEKED_NONE
296 | pathIndices[stackSize - 1]++
297 | }
298 | else -> return
299 | }
300 | }
301 |
302 | private fun skipObject() {
303 | beginObject()
304 | while(hasNext()) {
305 | nextName()
306 | skipValue()
307 | }
308 | endObject()
309 | }
310 |
311 | private fun skipArray() {
312 | beginArray()
313 | while(hasNext()) {
314 | skipValue()
315 | }
316 | endArray()
317 | }
318 |
319 | override fun peek(): Token {
320 | var p = peeked
321 | if (p == PEEKED_NONE) {
322 | doPeek()
323 | p = peeked
324 | }
325 |
326 | return when (p) {
327 | PEEKED_BEGIN_OBJECT -> Token.BEGIN_OBJECT
328 | PEEKED_END_OBJECT -> Token.END_OBJECT
329 | PEEKED_BEGIN_ARRAY -> Token.BEGIN_ARRAY
330 | PEEKED_END_ARRAY -> Token.END_ARRAY
331 | PEEKED_STRING, PEEKED_BUFFERED -> Token.STRING
332 | PEEKED_TRUE, PEEKED_FALSE -> Token.BOOLEAN
333 | PEEKED_NULL -> Token.NULL
334 | PEEKED_DOUBLE, PEEKED_LONG -> Token.NUMBER
335 | else -> throw AssertionError()
336 | }
337 | }
338 |
339 | @Throws(IOException::class)
340 | private fun doPeek(): Int {
341 | val peekStack = scopes[stackSize - 1]
342 | if (peekStack == JsonScope.EMPTY_ARRAY) {
343 | scopes[stackSize - 1] = JsonScope.NONEMPTY_ARRAY
344 | } else if (peekStack == JsonScope.EMPTY_OBJECT || peekStack == JsonScope.NONEMPTY_OBJECT) {
345 | scopes[stackSize - 1] = JsonScope.DANGLING_NAME
346 | } else if (peekStack == JsonScope.DANGLING_NAME) {
347 | scopes[stackSize - 1] = JsonScope.NONEMPTY_OBJECT
348 | } else if (peekStack == JsonScope.EMPTY_DOCUMENT) {
349 | scopes[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT
350 | } else if (peekStack == JsonScope.CLOSED) {
351 | throw IllegalStateException("JsonReader is closed")
352 | }
353 |
354 | if (buffer.size() == 0L) {
355 | peeked = PEEKED_EOF
356 | return peeked
357 | }
358 |
359 | val c = buffer.readByte()
360 | when (c) {
361 | in MsgpackFormat.ARRAY -> peeked = PEEKED_BEGIN_ARRAY
362 | in MsgpackFormat.MAP -> peeked = PEEKED_BEGIN_OBJECT
363 | in MsgpackFormat.STR -> peeked = PEEKED_STRING
364 | in MsgpackFormat.FIX_INT_MIN..MsgpackFormat.FIX_INT_MAX,
365 | MsgpackFormat.UINT_8,
366 | MsgpackFormat.UINT_16,
367 | MsgpackFormat.UINT_32,
368 | MsgpackFormat.UINT_64,
369 | MsgpackFormat.INT_8,
370 | MsgpackFormat.INT_16,
371 | MsgpackFormat.INT_32,
372 | MsgpackFormat.INT_64 -> peeked = PEEKED_LONG
373 | MsgpackFormat.FLOAT_32,
374 | MsgpackFormat.FLOAT_64 -> peeked = PEEKED_DOUBLE
375 | MsgpackFormat.NIL -> peeked = PEEKED_NULL
376 | MsgpackFormat.TRUE -> peeked = PEEKED_TRUE
377 | MsgpackFormat.FALSE -> peeked = PEEKED_FALSE
378 | else -> throw IllegalStateException("Msgpack format tag not yet supported: 0x${String.format("%02X", c)}")
379 | }
380 |
381 | currentTag = c
382 | return peeked
383 | }
384 | }
385 |
--------------------------------------------------------------------------------
/moshipack/src/main/kotlin/com/squareup/moshi/MsgpackWriter.kt:
--------------------------------------------------------------------------------
1 | package com.squareup.moshi
2 |
3 | import okio.BufferedSink
4 | import com.squareup.moshi.JsonScope.DANGLING_NAME
5 | import com.squareup.moshi.JsonScope.EMPTY_ARRAY
6 | import com.squareup.moshi.JsonScope.EMPTY_DOCUMENT
7 | import com.squareup.moshi.JsonScope.EMPTY_OBJECT
8 | import com.squareup.moshi.JsonScope.NONEMPTY_ARRAY
9 | import com.squareup.moshi.JsonScope.NONEMPTY_DOCUMENT
10 | import com.squareup.moshi.JsonScope.NONEMPTY_OBJECT
11 | import java.io.IOException
12 | import okio.Buffer
13 |
14 | class MsgpackWriter(private val sink: BufferedSink) : JsonWriter() {
15 |
16 | var options = MsgpackWriterOptions()
17 |
18 | private var deferredName: String? = null
19 | private val pathBuffers = Array(32) { null }
20 |
21 | private val currentIndex get() = stackSize - 1
22 | private val currentBuffer
23 | get() = if (currentIndex == 0) sink else pathBuffers[currentIndex]
24 | ?: throw IllegalStateException("Path buffer not initialized.")
25 |
26 | init {
27 | pushScope(EMPTY_DOCUMENT)
28 | }
29 |
30 | override fun nullValue(): JsonWriter {
31 | if (deferredName != null) {
32 | if (serializeNulls) {
33 | writeDeferredName()
34 | } else {
35 | deferredName = null
36 | return this
37 | }
38 | }
39 | beforeValue()
40 | currentBuffer.writeByte(MsgpackFormat.NIL.toInt())
41 | pathIndices[currentIndex]++
42 | return this
43 | }
44 |
45 | override fun value(value: String?): JsonWriter = when {
46 | value == null -> nullValue()
47 | promoteValueToName -> name(value)
48 | else -> {
49 | writeDeferredName()
50 | beforeValue()
51 | string(currentBuffer, value)
52 | pathIndices[currentIndex]++
53 | this
54 | }
55 | }
56 |
57 | override fun value(value: Boolean): JsonWriter {
58 | writeDeferredName()
59 | beforeValue()
60 | currentBuffer.writeByte(if (value) MsgpackFormat.TRUE.toInt() else MsgpackFormat.FALSE.toInt())
61 | pathIndices[currentIndex]++
62 | return this
63 | }
64 |
65 | override fun value(value: Boolean?): JsonWriter {
66 | return if (value == null) nullValue() else value(value)
67 | }
68 |
69 | override fun value(value: Double): JsonWriter {
70 | if (!lenient && (value.isNaN() || value.isInfinite())) {
71 | throw IllegalArgumentException("Numeric values must be finite, but was " + value)
72 | }
73 | return value(value as Number)
74 | }
75 |
76 | override fun value(value: Long): JsonWriter {
77 | if (promoteValueToName) {
78 | return name(value.toString())
79 | }
80 | if (options.writeAllIntsAsFloats) {
81 | return value(value.toDouble())
82 | }
83 | writeDeferredName()
84 | beforeValue()
85 | if (options.writeAllIntsAs != null) {
86 | options.writeAllIntsAs?.let {
87 | it.writer.invoke(currentBuffer, it.byte, value)
88 | }
89 | } else {
90 | when (value) {
91 | in MsgpackFormat.FIX_INT_MIN..MsgpackFormat.FIX_INT_MAX -> {
92 | currentBuffer.writeByte(value.toInt())
93 | }
94 | in MsgpackFormat.UINT_8_MIN..MsgpackFormat.UINT_8_MAX -> {
95 | currentBuffer.writeByte(MsgpackFormat.UINT_8.toInt())
96 | currentBuffer.writeByte(value.toInt())
97 | }
98 | in MsgpackFormat.UINT_16_MIN..MsgpackFormat.UINT_16_MAX -> {
99 | currentBuffer.writeByte(MsgpackFormat.UINT_16.toInt())
100 | currentBuffer.writeShort(value.toInt())
101 | }
102 | in MsgpackFormat.UINT_32_MIN..MsgpackFormat.UINT_32_MAX -> {
103 | currentBuffer.writeByte(MsgpackFormat.UINT_32.toInt())
104 | currentBuffer.writeInt(value.toInt())
105 | }
106 | in MsgpackFormat.UINT_32_MAX + 1..Long.MAX_VALUE -> {
107 | currentBuffer.writeByte(MsgpackFormat.UINT_64.toInt())
108 | currentBuffer.writeLong(value)
109 | }
110 | in Short.MIN_VALUE..Short.MAX_VALUE -> {
111 | currentBuffer.writeByte(MsgpackFormat.INT_16.toInt())
112 | currentBuffer.writeShort(value.toInt())
113 | }
114 | in Int.MIN_VALUE..Int.MAX_VALUE -> {
115 | currentBuffer.writeByte(MsgpackFormat.INT_32.toInt())
116 | currentBuffer.writeInt(value.toInt())
117 | }
118 | in Long.MIN_VALUE..Long.MAX_VALUE -> {
119 | currentBuffer.writeByte(MsgpackFormat.INT_64.toInt())
120 | currentBuffer.writeLong(value)
121 | }
122 | }
123 | }
124 | pathIndices[stackSize - 1]++
125 | return this
126 | }
127 |
128 | override fun value(value: Number?): JsonWriter {
129 | if (value == null) return nullValue()
130 |
131 | // If its a whole number store it as an int type
132 | if (value.toDouble() % 1 == 0.0 && !options.writeAllIntsAsFloats) {
133 | return value(value.toLong())
134 | }
135 |
136 | if (promoteValueToName) {
137 | return name(value.toString())
138 | }
139 | writeDeferredName()
140 | beforeValue()
141 | val writeFloatAs = options.writeAllFloatsAs
142 | when {
143 | (writeFloatAs == null && value.toDouble() in -Float.MAX_VALUE..Float.MAX_VALUE) ||
144 | writeFloatAs == MsgpackFloatByte.FLOAT_32 -> {
145 | currentBuffer.writeByte(MsgpackFormat.FLOAT_32.toInt())
146 | currentBuffer.writeInt(java.lang.Float.floatToIntBits(value.toFloat()))
147 | }
148 | value.toDouble() in -Double.MAX_VALUE..Double.MAX_VALUE ||
149 | writeFloatAs == MsgpackFloatByte.FLOAT_64 -> {
150 | currentBuffer.writeByte(MsgpackFormat.FLOAT_64.toInt())
151 | currentBuffer.writeLong(value.toDouble().toRawBits())
152 | }
153 | }
154 |
155 | pathIndices[stackSize - 1]++
156 | return this
157 | }
158 |
159 | override fun beginArray(): JsonWriter {
160 | writeDeferredName()
161 | return open(EMPTY_ARRAY)
162 | }
163 |
164 | override fun endArray(): JsonWriter {
165 | return close(EMPTY_ARRAY, NONEMPTY_ARRAY)
166 | }
167 |
168 | override fun beginObject(): JsonWriter {
169 | writeDeferredName()
170 | return open(EMPTY_OBJECT)
171 | }
172 |
173 | override fun endObject(): JsonWriter {
174 | promoteValueToName = false
175 | return close(EMPTY_OBJECT, NONEMPTY_OBJECT)
176 | }
177 |
178 | override fun name(name: String?): JsonWriter {
179 | require(name != null) { "name == null " }
180 | require(stackSize > 0) { "MsgpackWriter is closed." }
181 | require(deferredName == null) { "Nesting problem" }
182 | deferredName = name
183 | pathNames[currentIndex] = name
184 | promoteValueToName = false
185 | return this
186 | }
187 |
188 | override fun flush() {
189 | if (stackSize == 0) {
190 | throw IllegalStateException("JsonWriter is closed.")
191 | }
192 | sink.flush()
193 | }
194 |
195 | override fun close() {
196 | sink.close()
197 |
198 | val size = stackSize
199 | if (size > 1 || size == 1 && scopes[size - 1] != NONEMPTY_DOCUMENT) {
200 | throw IOException("Incomplete document")
201 | }
202 | stackSize = 0
203 | }
204 |
205 | @Throws(IOException::class)
206 | private fun writeDeferredName() {
207 | if (deferredName != null) {
208 | beforeName()
209 | string(currentBuffer, deferredName ?: throw IllegalStateException("Null name."))
210 | deferredName = null
211 | }
212 | }
213 |
214 | /**
215 | * Check scope and adjusts the stack to expect the name's value.
216 | */
217 | @Throws(IOException::class)
218 | private fun beforeName() {
219 | val context = peekScope()
220 | require(context == EMPTY_OBJECT || context == NONEMPTY_OBJECT) {
221 | "Nesting problem, not in object."
222 | }
223 | replaceTop(DANGLING_NAME)
224 | }
225 |
226 | /**
227 | * Inserts any necessary separators and whitespace before a literal value,
228 | * inline array, or inline object. Also adjusts the stack to expect either a
229 | * closing bracket or another element.
230 | */
231 | @Throws(IOException::class)
232 | private fun beforeValue() {
233 | when (peekScope()) {
234 | NONEMPTY_DOCUMENT,
235 | EMPTY_DOCUMENT -> replaceTop(NONEMPTY_DOCUMENT)
236 | EMPTY_ARRAY -> replaceTop(NONEMPTY_ARRAY)
237 | NONEMPTY_ARRAY -> return
238 | DANGLING_NAME -> replaceTop(NONEMPTY_OBJECT)
239 | else -> throw IllegalStateException("Nesting problem.")
240 | }
241 | }
242 |
243 | /**
244 | * Enters a new scope by appending any necessary whitespace and the given
245 | * bracket.
246 | */
247 | @Throws(IOException::class)
248 | private fun open(empty: Int): JsonWriter {
249 | beforeValue()
250 | //checkStack() - Grows stack in newer version of Moshi under development.
251 | //pathBuffers will have to grow too if this is supported.
252 | pushScope(empty)
253 | pathBuffers[currentIndex] = Buffer()
254 | pathIndices[currentIndex] = 0
255 | return this
256 | }
257 |
258 | /**
259 | * Closes the current scope by appending any necessary whitespace and the
260 | * given bracket.
261 | */
262 | @Throws(IOException::class)
263 | private fun close(empty: Int, nonempty: Int): JsonWriter {
264 | val context = peekScope()
265 | if (context != nonempty && context != empty) {
266 | throw IllegalStateException("Nesting problem.")
267 | }
268 | if (deferredName != null) {
269 | throw IllegalStateException("Dangling name: " + deferredName)
270 | }
271 |
272 | val msgType = when (nonempty) {
273 | NONEMPTY_ARRAY -> MsgpackFormat.ARRAY
274 | NONEMPTY_OBJECT -> MsgpackFormat.MAP
275 | else -> throw IllegalStateException("Wrong nonempty value used.")
276 | }
277 | val tagType = MsgpackFormat.tagFor(msgType, pathIndices[currentIndex])
278 | ?: throw IllegalArgumentException("Size too long for msgpack format.")
279 | val previousBuffer = currentBuffer as Buffer
280 | val previousSize = pathIndices[currentIndex]
281 |
282 | stackSize--
283 | tagType.writeTag(currentBuffer, previousSize)
284 | previousBuffer.copyTo(currentBuffer.outputStream())
285 | pathNames[stackSize] = null // Free the last path name so that it can be garbage collected!
286 | pathIndices[currentIndex]++
287 |
288 | if (stackSize == 1) {
289 | sink.emitCompleteSegments()
290 | }
291 | return this
292 | }
293 |
294 | /**
295 | * Writes `value` as a string literal to `sink`.
296 | */
297 | @Throws(IOException::class)
298 | private fun string(sink: BufferedSink, value: String) {
299 | val bytes = value.toByteArray()
300 | val tagType = MsgpackFormat.tagFor(MsgpackFormat.STR, bytes.size)
301 | ?: throw IllegalArgumentException("String size too long for msgpack format.")
302 |
303 | tagType.writeTag(sink, bytes.size)
304 | sink.writeUtf8(value)
305 | }
306 | }
307 |
--------------------------------------------------------------------------------
/moshipack/src/main/kotlin/com/squareup/moshi/MsgpackWriterOptions.kt:
--------------------------------------------------------------------------------
1 | package com.squareup.moshi
2 |
3 | import okio.BufferedSink
4 |
5 | private val FIX_WRITER: BufferedSink.(byte: Byte, value: Number) -> Unit = { byte, value ->
6 | writeByte(value.toInt())
7 | }
8 |
9 | private val BYTE_WRITER: BufferedSink.(byte: Byte, value: Number) -> Unit = { byte, value ->
10 | writeByte(byte.toInt())
11 | writeByte(value.toInt())
12 | }
13 |
14 | private val SHORT_WRITER: BufferedSink.(byte: Byte, value: Number) -> Unit = { byte, value ->
15 | writeByte(byte.toInt())
16 | writeShort(value.toInt())
17 | }
18 |
19 | private val INT_WRITER: BufferedSink.(byte: Byte, value: Number) -> Unit = { byte, value ->
20 | writeByte(byte.toInt())
21 | writeInt(value.toInt())
22 | }
23 |
24 | private val LONG_WRITER: BufferedSink.(byte: Byte, value: Number) -> Unit = { byte, value ->
25 | writeByte(byte.toInt())
26 | writeLong(value.toLong())
27 | }
28 |
29 | enum class MsgpackIntByte(val byte: Byte,
30 | val writer: BufferedSink.(byte: Byte, value: Number) -> Unit) {
31 | FIX_INT(0x0, FIX_WRITER),
32 | INT_8(MsgpackFormat.INT_8, BYTE_WRITER),
33 | INT_16(MsgpackFormat.INT_16, SHORT_WRITER),
34 | INT_32(MsgpackFormat.INT_32, INT_WRITER),
35 | INT_64(MsgpackFormat.INT_64, LONG_WRITER),
36 | UINT_8(MsgpackFormat.UINT_8, BYTE_WRITER),
37 | UINT_16(MsgpackFormat.UINT_16, SHORT_WRITER),
38 | UINT_32(MsgpackFormat.UINT_32, INT_WRITER),
39 | UINT_64(MsgpackFormat.UINT_64, LONG_WRITER)
40 | }
41 |
42 | enum class MsgpackFloatByte(val byte: Byte) {
43 | FLOAT_32(MsgpackFormat.FLOAT_32),
44 | FLOAT_64(MsgpackFormat.FLOAT_64)
45 | }
46 |
47 | class MsgpackWriterOptions(
48 | var writeAllIntsAs: MsgpackIntByte? = null,
49 | var writeAllFloatsAs: MsgpackFloatByte? = null,
50 | var writeAllIntsAsFloats: Boolean = false
51 | )
52 |
--------------------------------------------------------------------------------
/moshipack/src/test/kotlin/TestAgainstMessagePackJava.kt:
--------------------------------------------------------------------------------
1 | import com.daveanthonythomas.moshipack.MoshiPack
2 | import com.squareup.moshi.MsgpackFormat
3 | import okio.Buffer
4 | import org.junit.Assert.assertEquals
5 | import org.junit.Test
6 | import org.msgpack.core.MessagePack
7 |
8 | class TestAgainstMessagePackJava {
9 |
10 | @Test
11 | fun comparison() {
12 | val packer = MessagePack.newDefaultBufferPacker()
13 | packer.packMapHeader(2)
14 | packer.packString("compact")
15 | packer.packBoolean(true)
16 | packer.packString("schema")
17 | packer.packShort(0)
18 |
19 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
20 | val moshiPackResult = MoshiPack.pack(ThePlug())
21 |
22 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
23 | }
24 |
25 | @Test
26 | fun comparisonNegative() {
27 | val packer = MessagePack.newDefaultBufferPacker()
28 | packer.packMapHeader(2)
29 | packer.packString("compact")
30 | packer.packBoolean(true)
31 | packer.packString("schema")
32 | packer.packShort(-9)
33 |
34 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
35 | val moshiPackResult = MoshiPack.pack(ThePlug().apply { schema = -9 })
36 |
37 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
38 | }
39 |
40 | @Test
41 | fun comparisonNegativeOneByteMax() {
42 | val packer = MessagePack.newDefaultBufferPacker()
43 | packer.packMapHeader(2)
44 | packer.packString("compact")
45 | packer.packBoolean(true)
46 | packer.packString("schema")
47 | packer.packShort(-32)
48 |
49 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
50 | val moshiPackResult = MoshiPack.pack(ThePlug().apply { schema = -32 })
51 |
52 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
53 | }
54 |
55 | @Test
56 | fun comparisonBoolean() {
57 | val packer = MessagePack.newDefaultBufferPacker()
58 | packer.packMapHeader(2)
59 | packer.packString("stuffed")
60 | packer.packBoolean(false)
61 | packer.packString("topping")
62 | packer.packString("Stuff")
63 |
64 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
65 | val moshiPackResult = MoshiPack.pack(PizzaPlus().apply { stuffed = false })
66 |
67 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
68 | }
69 |
70 | @Test
71 | fun comparisonUInt8() {
72 | val packer = MessagePack.newDefaultBufferPacker()
73 | packer.packMapHeader(2)
74 | packer.packString("compact")
75 | packer.packBoolean(true)
76 | packer.packString("schema")
77 | packer.packShort(200)
78 |
79 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
80 | val moshiPackResult = MoshiPack.pack(ThePlug().apply { schema = 200 })
81 |
82 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
83 | }
84 |
85 | @Test
86 | fun comparisonUInt16() {
87 | val packer = MessagePack.newDefaultBufferPacker()
88 | packer.packMapHeader(2)
89 | packer.packString("compact")
90 | packer.packBoolean(true)
91 | packer.packString("schema")
92 | packer.packShort(32767)
93 |
94 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
95 | val moshiPackResult = MoshiPack.pack(ThePlug().apply { schema = 32767 })
96 |
97 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
98 | }
99 |
100 | @Test
101 | fun comparisonNegativeTwoByte() {
102 | val packer = MessagePack.newDefaultBufferPacker()
103 | packer.packMapHeader(2)
104 | packer.packString("compact")
105 | packer.packBoolean(true)
106 | packer.packString("schema")
107 | packer.packShort(-202)
108 |
109 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
110 | val moshiPackResult = MoshiPack.pack(ThePlug().apply { schema = -202 })
111 |
112 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
113 | }
114 |
115 | @Test
116 | fun comparisonNegativeFourByte() {
117 | val packer = MessagePack.newDefaultBufferPacker()
118 | packer.packMapHeader(2)
119 | packer.packString("compact")
120 | packer.packBoolean(true)
121 | packer.packString("schema")
122 | packer.packInt(-202090)
123 |
124 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
125 | val moshiPackResult = MoshiPack.pack(ThePlug().apply { schema = -202090 })
126 |
127 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
128 | }
129 |
130 | @Test
131 | fun comparisonNegativeEightByte() {
132 | val packer = MessagePack.newDefaultBufferPacker()
133 | packer.packMapHeader(2)
134 | packer.packString("compact")
135 | packer.packBoolean(true)
136 | packer.packString("schema")
137 | packer.packLong(-2020900943243289)
138 |
139 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
140 | val moshiPackResult = MoshiPack.jsonToMsgpack("{'compact':true,'schema':-2020900943243289}")
141 |
142 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
143 | }
144 |
145 | @Test
146 | fun comparisonBigPositiveNumber() {
147 | val packer = MessagePack.newDefaultBufferPacker()
148 | packer.packMapHeader(1)
149 | packer.packString("bigNumber")
150 | packer.packLong(2020900943243289543)
151 |
152 | data class TestClass(var bigNumber: Long = 2020900943243289543)
153 |
154 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
155 | val moshiPackResult = MoshiPack.pack(TestClass())
156 |
157 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
158 | }
159 |
160 | @Test
161 | fun comparisonFloatingPoint() {
162 | val packer = MessagePack.newDefaultBufferPacker()
163 | packer.packMapHeader(1)
164 | packer.packString("float")
165 | packer.packFloat(202.202F)
166 |
167 | data class TestClass(var float: Float = 202.202F)
168 |
169 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
170 | val moshiPackResult = MoshiPack.pack(TestClass())
171 |
172 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
173 | }
174 |
175 | @Test
176 | fun comparisonNegativeFloatingPoint() {
177 | val packer = MessagePack.newDefaultBufferPacker()
178 | packer.packMapHeader(1)
179 | packer.packString("float")
180 | packer.packFloat(-202.202F)
181 |
182 | data class TestClass(var float: Float = -202.202F)
183 |
184 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
185 | val moshiPackResult = MoshiPack.pack(TestClass())
186 |
187 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
188 | }
189 |
190 | @Test
191 | fun comparisonDouble() {
192 | val packer = MessagePack.newDefaultBufferPacker()
193 | packer.packMapHeader(1)
194 | packer.packString("double")
195 | packer.packDouble(202.202)
196 |
197 | data class TestClass(var double: Double)
198 |
199 | val result = MoshiPack.unpack(packer.toByteArray())
200 |
201 |
202 | assertEquals(result.double, 202.202, 0.0)
203 | }
204 |
205 | @Test
206 | fun comparisonDoubleLarge() {
207 | val packer = MessagePack.newDefaultBufferPacker()
208 | packer.packMapHeader(1)
209 | packer.packString("double")
210 | packer.packDouble(202.20223432432422)
211 |
212 | data class TestClass(var double: Double)
213 |
214 | val result = MoshiPack.unpack(packer.toByteArray())
215 |
216 |
217 | assertEquals(result.double, 202.20223432432422, 0.0)
218 | }
219 |
220 | @Test
221 | fun string() {
222 | val string = "Nice little string value!"
223 | val packer = MessagePack.newDefaultBufferPacker()
224 | packer.packString(string)
225 |
226 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
227 | val moshiPackResult = MoshiPack.pack(string)
228 |
229 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
230 | }
231 |
232 | @Test
233 | fun stringDecode() {
234 | val string = "Nice little string value!"
235 | val packer = MessagePack.newDefaultBufferPacker()
236 | packer.packString(string)
237 |
238 | val moshiPackResult: String = MoshiPack.unpack(packer.toByteArray())
239 |
240 | assertEquals(string, moshiPackResult)
241 | }
242 |
243 | @Test
244 | fun stringLong() {
245 | val string = "Nice little string value! Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
246 | val packer = MessagePack.newDefaultBufferPacker()
247 | packer.packString(string)
248 |
249 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
250 | val moshiPackResult = MoshiPack.pack(string)
251 |
252 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
253 | }
254 |
255 | @Test
256 | fun stringDecodeLong() {
257 | val string = "Nice little string value! Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
258 | val packer = MessagePack.newDefaultBufferPacker()
259 | packer.packString(string)
260 |
261 | val moshiPackResult: String = MoshiPack.unpack(packer.toByteArray())
262 |
263 | assertEquals(string, moshiPackResult)
264 | }
265 |
266 | @Test
267 | fun string8() {
268 | val string = "1234567890123456789012345678901234567890"
269 | val packer = MessagePack.newDefaultBufferPacker()
270 | packer.packString(string)
271 |
272 | val messagePackResult = Buffer().apply { write(packer.toByteArray()) }
273 | val moshiPackResult = MoshiPack.pack(string)
274 |
275 | assertEquals(messagePackResult.readByteString().hex(), moshiPackResult.readByteString().hex())
276 | }
277 |
278 | @Test
279 | fun string8Decode() {
280 | val string = "1234567890123456789012345678901234567890"
281 | val packer = MessagePack.newDefaultBufferPacker()
282 | packer.packString(string)
283 |
284 | val moshiPackResult: String = MoshiPack.unpack(packer.toByteArray())
285 |
286 | assertEquals(string, moshiPackResult)
287 | }
288 |
289 | @Test
290 | fun string32Decode() {
291 | val longString = StringBuilder("Long long string")
292 | (0..MsgpackFormat.SIZE_16).forEach { longString.append("a") }
293 | val packer = MessagePack.newDefaultBufferPacker()
294 | packer.packString(longString.toString())
295 |
296 | val moshiPackResult: String = MoshiPack.unpack(packer.toByteArray())
297 |
298 | assertEquals(longString.toString(), moshiPackResult)
299 | }
300 |
301 | @Test
302 | fun lotsOfParams() {
303 | val packer = MessagePack.newDefaultBufferPacker()
304 | packer.packMapHeader(25)
305 | (0 until 25).forEach {
306 | packer.packString("abc" + it)
307 | packer.packInt(it)
308 | }
309 |
310 | val moshiPackResult: Map = MoshiPack.unpack(packer.toByteArray())
311 |
312 | assertEquals(25, moshiPackResult.size)
313 |
314 | var x = 0
315 | moshiPackResult.forEach {
316 | assertEquals(it.value, x)
317 | assertEquals(it.key, "abc" + x)
318 | x++
319 | }
320 | }
321 | }
--------------------------------------------------------------------------------
/moshipack/src/test/kotlin/TestCatData.kt:
--------------------------------------------------------------------------------
1 | import com.daveanthonythomas.moshipack.MoshiPack
2 | import org.junit.Test
3 |
4 | class TestCatData {
5 |
6 | @Test
7 | fun testCatData() {
8 | val fileContent = TestCatData::class.java.getResource("cats").readBytes()
9 |
10 | val cats: List = MoshiPack.unpack(fileContent)
11 | }
12 | }
--------------------------------------------------------------------------------
/moshipack/src/test/kotlin/TestClasses.kt:
--------------------------------------------------------------------------------
1 | data class Pizza(var topping: String = "Stuff")
2 |
3 | class PizzaPlus {
4 | var topping = "Stuff"
5 | var stuffed = true
6 | }
7 |
8 | data class ThePlug(var compact: Boolean = true, var schema: Int = 0)
9 |
10 | data class SomeNumbers(var num1: Int, var num2: Float, var num3: Short, var num4: Double, var num5: Long)
11 |
12 | data class Nest(var eggs: List)
13 |
14 | data class Egg(var size: Int = 2)
15 |
16 | data class Transients(var one: String, var three: String) {
17 | @Transient var two: String = "Transient"
18 | }
19 |
20 | // Does not work with KotlinJsonAdapterFactory
21 | data class Transients2(var one:String, @Transient var two: String, var three: String)
22 |
23 | class Cat {
24 | var breed: String = ""
25 | var country: String? = null
26 | var origin: String? = null
27 | var bodytype: String? = null
28 | var coat: String? = null
29 | var pattern: String? = null
30 | var image: String? = null
31 | }
32 |
--------------------------------------------------------------------------------
/moshipack/src/test/kotlin/TestMessagePackReader.kt:
--------------------------------------------------------------------------------
1 | import com.daveanthonythomas.moshipack.MoshiPack
2 | import com.squareup.moshi.Moshi
3 | import com.squareup.moshi.MsgpackFormat
4 | import com.squareup.moshi.MsgpackReader
5 | import com.sun.xml.internal.ws.org.objectweb.asm.ClassAdapter
6 | import okio.Buffer
7 | import okio.ByteString
8 | import org.hamcrest.CoreMatchers
9 | import org.hamcrest.CoreMatchers.hasItems
10 | import org.junit.Assert.assertEquals
11 | import org.junit.Assert.assertThat
12 | import org.junit.Test
13 |
14 | class TestMessagePackReader {
15 |
16 | @Test
17 | fun doesMyReaderEvenWorkYet() {
18 | val moshi = Moshi.Builder().build()
19 | val buffer = Buffer()
20 |
21 | // First test
22 | // Expect fix map 81 with size of 1
23 | // Then fix string a7 with size of 7 bytes ( topping ) 74 6f 70 70 69 6e 67
24 | // Then fix string a9 with size of 9 bytes ( pepperoni" ) 70 65 70 70 65 72 6f 6e 69
25 | buffer.write(ByteString.decodeHex("81a7746f7070696e67a97065707065726f6e69"))
26 | val pizza = moshi.adapter(Pizza::class.java).fromJson(MsgpackReader(buffer))
27 |
28 | assertEquals(pizza?.topping, "pepperoni")
29 | }
30 |
31 | @Test
32 | fun didSomeoneOrderSomePizzas() {
33 |
34 | val pizzabytes = "81a7746f7070696e67a97065707065726f6e69" // Not bagel bytes?
35 |
36 | val buffer = Buffer()
37 | buffer.write(ByteString.decodeHex("93$pizzabytes$pizzabytes$pizzabytes"))
38 |
39 | val pizzas: List = MoshiPack.unpack(buffer)
40 |
41 | assertEquals(3, pizzas.size)
42 |
43 | assertThat(pizzas, hasItems(
44 | Pizza("pepperoni"),
45 | Pizza("pepperoni"),
46 | Pizza("pepperoni")))
47 | }
48 |
49 | @Test
50 | fun theMessagePackWebsitePlug() {
51 | // It's like JSON.
52 | // but fast and small.
53 | //https://msgpack.org/images/intro.png
54 |
55 | // 82 - 2 element map
56 | // a7 63 6f 6d 70 61 63 74 - compact
57 | // c3 - true
58 |
59 | // a6 73 63 68 65 6d 61 - schema
60 | // 00 - integer 0
61 |
62 | val buffer = Buffer()
63 | buffer.write(ByteString.decodeHex("82a7636f6d70616374c3a6736368656d6100"))
64 |
65 | val unpacked: Map = MoshiPack.unpack(buffer)
66 |
67 | assertEquals(2, unpacked.size)
68 | assertEquals(true, unpacked["compact"])
69 | assertEquals(0.0, unpacked["schema"])
70 | }
71 |
72 | @Test
73 | fun theMessagePackWebsitePlugObj() {
74 | // It's like JSON.
75 | // but fast and small.
76 | //https://msgpack.org/images/intro.png
77 |
78 | // 82 - 2 element map
79 | // a7 63 6f 6d 70 61 63 74 - compact
80 | // c3 - true
81 |
82 | // a6 73 63 68 65 6d 61 - schema
83 | // 00 - integer 0
84 |
85 | val buffer = Buffer()
86 | buffer.write(ByteString.decodeHex("82a7636f6d70616374c3a6736368656d6100"))
87 |
88 | val unpacked: ThePlug = MoshiPack.unpack(buffer)
89 |
90 | assertEquals(true, unpacked.compact)
91 | assertEquals(0, unpacked.schema)
92 | }
93 |
94 | @Test
95 | fun nestObjects() {
96 |
97 | val buffer = Buffer()
98 | buffer += "81"
99 | buffer += "a4${"eggs".hex}"
100 | buffer += "95"
101 | (1 until 6).forEach {
102 | buffer += "81"
103 | buffer += "a4${"size".hex}"
104 | buffer.writeByte(it)
105 | }
106 |
107 | val nest: Nest = MoshiPack.unpack(buffer)
108 |
109 | assertEquals(5, nest.eggs.size)
110 |
111 | (0 until 5).forEach {
112 | assertEquals(it + 1, nest.eggs[it].size)
113 | }
114 | }
115 |
116 | @Test
117 | fun testList() {
118 |
119 | val buffer = Buffer()
120 | buffer += "92"
121 |
122 | buffer += "81"
123 | buffer += "a4${"eggs".hex}"
124 | buffer += "95"
125 | (1 until 6).forEach {
126 | buffer += "81"
127 | buffer += "a4${"size".hex}"
128 | buffer.writeByte(it)
129 | }
130 |
131 | buffer += "81"
132 | buffer += "a4${"eggs".hex}"
133 | buffer += "95"
134 | (1 until 6).forEach {
135 | buffer += "81"
136 | buffer += "a4${"size".hex}"
137 | buffer.writeByte(it)
138 | }
139 |
140 | val list: List = MoshiPack().unpack(buffer)
141 | val nest: Nest = list[0]
142 |
143 | assertEquals(nest.eggs[0].size, 1)
144 | }
145 |
146 | @Test
147 | fun listAny() {
148 | val buffer = Buffer()
149 | buffer += "92"
150 |
151 | buffer += "81"
152 | buffer += "a4${"eggs".hex}"
153 | buffer += "95"
154 | (1 until 6).forEach {
155 | buffer += "81"
156 | buffer += "a4${"size".hex}"
157 | buffer.writeByte(it)
158 | }
159 |
160 | buffer += "81"
161 | buffer += "a4${"eggs".hex}"
162 | buffer += "95"
163 | (1 until 6).forEach {
164 | buffer += "81"
165 | buffer += "a4${"size".hex}"
166 | buffer.writeByte(it)
167 | }
168 |
169 | val list: List = MoshiPack().unpack(buffer)
170 |
171 | assertEquals(2, list.size)
172 | }
173 | }
--------------------------------------------------------------------------------
/moshipack/src/test/kotlin/TestMessagePackWriter.kt:
--------------------------------------------------------------------------------
1 | import com.daveanthonythomas.moshipack.MoshiPack
2 | import com.squareup.moshi.Moshi
3 | import com.squareup.moshi.MsgpackFormat
4 | import com.squareup.moshi.MsgpackIntByte
5 | import com.squareup.moshi.MsgpackWriter
6 | import okio.Buffer
7 | import org.junit.Assert.assertArrayEquals
8 | import org.junit.Assert.assertEquals
9 | import org.junit.Test
10 |
11 |
12 | class TestMessagePackWriter {
13 |
14 | @Test
15 | fun seeIfThisThingWorksOrNot() {
16 | val moshi = Moshi.Builder().build()
17 | val buffer = Buffer()
18 | moshi.adapter(Pizza::class.java).toJson(MsgpackWriter(buffer), Pizza())
19 |
20 | val msgPackString = buffer.readByteString()
21 |
22 | // First test
23 | // Expect fix map 81 with size of 1
24 | // Then fix string a7 with size of 7 bytes ( topping ) 74 6f 70 70 69 6e 67
25 | // Then fix string a5 with size of 5 bytes ( Stuff ) 53 74 75 66 66
26 |
27 | assertEquals("81a7746f7070696e67a55374756666", msgPackString.hex())
28 | }
29 |
30 | @Test
31 | fun okOneMoreTestThanYouGottaGotoSleep() {
32 | val moshi = Moshi.Builder().build()
33 | val buffer = Buffer()
34 | moshi.adapter(PizzaPlus::class.java).toJson(MsgpackWriter(buffer), PizzaPlus())
35 |
36 | val msgPackString = buffer.readByteString()
37 |
38 | // Second test
39 | // Expect fix map 82 with size of 2
40 | // Then fix string a7 with size of 7 bytes ( topping ) 74 6f 70 70 69 6e 67
41 | // Then fix string a5 with size of 5 bytes ( Stuff ) 53 74 75 66 66
42 | // Then fix string a7 with size of 5 bytes ( stuffed ) 53 74 75 66 66
43 | // Then boolean true
44 |
45 | // Well shit... s comes before t so I think stuffed goes first
46 | // should be this actually:
47 |
48 | // Expect fix map 81 with size of 2
49 | // Then fix string a7 with size of 5 bytes ( stuffed ) 73 74 75 66 66 65 64
50 | // Then boolean true c3
51 | // Then fix string a7 with size of 7 bytes ( topping ) 74 6f 70 70 69 6e 67
52 | // Then fix string a5 with size of 5 bytes ( Stuff ) 53 74 75 66 66
53 |
54 |
55 | assertEquals("82a773747566666564c3a7746f7070696e67a55374756666", msgPackString.hex())
56 | }
57 |
58 |
59 | @Test
60 | fun whoOrdersJustOnePizzaNotMe() {
61 | val pizzas = listOf(Pizza(), Pizza())
62 |
63 | val buffer = MoshiPack.pack(pizzas)
64 |
65 | val pizzabytes = "81a7746f7070696e67a55374756666"
66 |
67 | assertEquals("92$pizzabytes$pizzabytes", buffer.readByteString().hex())
68 | }
69 |
70 | @Test
71 | fun theMessagePackWebsitePlug() {
72 | // It's like JSON.
73 | // but fast and small.
74 | //https://msgpack.org/images/intro.png
75 |
76 | // 82 - 2 element map
77 | // a7 63 6f 6d 70 61 63 74 - compact
78 | // c3 - true
79 |
80 | // a6 73 63 68 65 6d 61 - schema
81 | // 00 - integer 0
82 |
83 | val map = mapOf("compact" to true, "schema" to 0)
84 | val buffer = MoshiPack.pack(map)
85 |
86 | assertEquals("82a7636f6d70616374c3a6736368656d6100", buffer.readByteString().hex())
87 | }
88 |
89 | @Test
90 | fun transientsAreNotWritten() {
91 | val transients = Transients("A", "C").apply { two = "B" }
92 | val buffer = MoshiPack().pack(transients)
93 |
94 | assertEquals("82a3${"one".hex}a141a5${"three".hex}a143", buffer.readByteString().hex())
95 | }
96 |
97 | @Test
98 | fun transientsAreNotWrittenMoshiNoKotlinSupport() {
99 | val transients = Transients2("A", "B", "C")
100 | val buffer = MoshiPack(moshi = Moshi.Builder().build()).pack(transients)
101 |
102 | assertEquals("82a3${"one".hex}a141a5${"three".hex}a143", buffer.readByteString().hex())
103 | }
104 |
105 | val uint64MoshiPack get() = MoshiPack(moshi = Moshi.Builder().build())
106 | .apply {
107 | writerOptions.writeAllIntsAs = MsgpackIntByte.UINT_64
108 | }
109 |
110 | val int64MoshiPack
111 | get() = MoshiPack(moshi = Moshi.Builder().build())
112 | .apply {
113 | writerOptions.writeAllIntsAs = MsgpackIntByte.INT_64
114 | }
115 | @Test
116 | fun fixedUint64WorksWithZero() {
117 | // Single uInt64 value
118 | val expected = byteArrayOf(
119 | 0xcf.toByte(), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
120 | )
121 | val bytes = uint64MoshiPack.packToByteArray(0x00)
122 | assertArrayEquals(expected, bytes)
123 | }
124 |
125 | @Test
126 | fun fixedUint64WorksWithMaxLong() {
127 | // uInt64 format byte followed by Long.MAX_VALUE in bytes
128 | val expected = byteArrayOf(
129 | 0xcf.toByte(),
130 | 0x7F, 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(),
131 | 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte()
132 | )
133 | val bytes = uint64MoshiPack.packToByteArray(Long.MAX_VALUE)
134 | assertArrayEquals(expected, bytes)
135 | }
136 |
137 | @Test
138 | fun fixedUint64WorksWithMaxInt() {
139 | // uInt64 format byte value followed by value Int.MAX_VALUE in bytes
140 | val expected = byteArrayOf(
141 | 0xcf.toByte(),
142 | 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte()
143 | )
144 | val bytes = uint64MoshiPack.packToByteArray(Int.MAX_VALUE)
145 | assertArrayEquals(expected, bytes)
146 | }
147 |
148 | @Test
149 | fun fixedUint64WorksWithSingleElementArray() {
150 | // fixarray format byte, uInt64 format byte, zero value bytes
151 | val expected = byteArrayOf(
152 | 0x91.toByte(),
153 | 0xcf.toByte(), 0x00, 0x00, 0x00, 0x00,
154 | 0x00, 0x00, 0x00, 0x00
155 | )
156 | val bytes = uint64MoshiPack.packToByteArray(byteArrayOf(0x00))
157 | assertArrayEquals(expected, bytes)
158 | }
159 |
160 | @Test
161 | fun arrayOfUint64WorksWithFixedSize() {
162 | // fixarray format byte, uInt64 format byte, value bytes, uInt64 format byte, value bytes
163 | val expected = byteArrayOf(
164 | 0x92.toByte(),
165 | 0xcf.toByte(), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
166 | 0xcf.toByte(), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
167 | )
168 | val bytes = uint64MoshiPack.packToByteArray(byteArrayOf(0x01, 0x01))
169 | assertArrayEquals(expected, bytes)
170 | }
171 |
172 | @Test
173 | fun mapOfUint64WorksWithFixedSize() {
174 | val expected = byteArrayOf(
175 | 0x82.toByte(),
176 | 0xA1.toByte(), 0x31,
177 | 0xcf.toByte(), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
178 | 0xA1.toByte(), 0x32,
179 | 0xcf.toByte(), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04
180 | )
181 | val bytes = uint64MoshiPack.packToByteArray(mapOf(1 to 0x03, 2 to 0x04))
182 | assertArrayEquals(expected, bytes)
183 | }
184 |
185 |
186 | @Test
187 | fun mapOfSmallestSizeWithSingleElement() {
188 | val expected = byteArrayOf(-127, -95, 49, 3)
189 | val bytes = MoshiPack(moshi = Moshi.Builder().build()).packToByteArray(
190 | mapOf(1 to 0x03)
191 | )
192 | assertArrayEquals(expected, bytes)
193 | }
194 |
195 | @Test
196 | fun mapOfSmallestSizeWithTwoElement() {
197 | val expected = byteArrayOf(-126, -95, 49, 3, -95, 50, 4)
198 | val bytes = MoshiPack(moshi = Moshi.Builder().build()).packToByteArray(
199 | mapOf(1 to 0x03, 2 to 0x04)
200 | )
201 | assertArrayEquals(expected, bytes)
202 | }
203 |
204 |
205 | @Test
206 | fun fixedInt64WorksWithZero() {
207 | // Single Int64 value
208 | val expected = byteArrayOf(
209 | 0xd3.toByte(), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
210 | )
211 | val bytes = int64MoshiPack. packToByteArray(0x00)
212 | assertArrayEquals(expected, bytes)
213 | }
214 |
215 | @Test
216 | fun fixedInt64WorksWithMaxLong() {
217 | // uInt64 format byte followed by Long.MAX_VALUE in bytes
218 | val expected = byteArrayOf(
219 | 0xd3.toByte(),
220 | 0x7F, 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(),
221 | 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte()
222 | )
223 | val bytes = int64MoshiPack.packToByteArray(Long.MAX_VALUE)
224 | assertArrayEquals(expected, bytes)
225 | }
226 |
227 | @Test
228 | fun fixedInt64WorksWithMaxInt() {
229 | // Int64 format byte value followed by value Int.MAX_VALUE in bytes
230 | val expected = byteArrayOf(
231 | 0xd3.toByte(),
232 | 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte()
233 | )
234 | val bytes = int64MoshiPack.packToByteArray(Int.MAX_VALUE)
235 | assertArrayEquals(expected, bytes)
236 | }
237 |
238 | @Test
239 | fun fixedInt64WorksWithSingleElementArray() {
240 | // fixarray format byte, Int64 format byte, zero value bytes
241 | val expected = byteArrayOf(
242 | 0x91.toByte(),
243 | 0xd3.toByte(), 0x00, 0x00, 0x00, 0x00,
244 | 0x00, 0x00, 0x00, 0x00
245 | )
246 | val bytes = int64MoshiPack.packToByteArray(byteArrayOf(0x00))
247 | assertArrayEquals(expected, bytes)
248 | }
249 | }
250 |
--------------------------------------------------------------------------------
/moshipack/src/test/kotlin/TestReadAndWrite.kt:
--------------------------------------------------------------------------------
1 | import com.daveanthonythomas.moshipack.MoshiPack
2 | import org.junit.Assert.assertEquals
3 | import org.junit.Test
4 |
5 | class TestReadAndWrite {
6 |
7 | @Test
8 | fun writeAndReadSomeNumbers() {
9 |
10 | val numbers = SomeNumbers(255, 55.5F, 3, 500.25, 1536094776000L)
11 |
12 | val buffer = MoshiPack.pack(numbers)
13 |
14 | val unmarshalled = MoshiPack.unpack(buffer)
15 |
16 | assertEquals(255, unmarshalled.num1)
17 | assertEquals(55.5F, unmarshalled.num2)
18 | assertEquals(3.toShort(), unmarshalled.num3)
19 | assertEquals(500.25, unmarshalled.num4, 0.0)
20 | assertEquals(1536094776000L, unmarshalled.num5)
21 | }
22 |
23 | @Test
24 | fun writeAndReadSomeNegativeNumbers() {
25 |
26 | val numbers = SomeNumbers(-255, -55.5F, -3, -500.25, -1536094776123L)
27 |
28 | val buffer = MoshiPack.pack(numbers)
29 |
30 | val unmarshalled = MoshiPack.unpack(buffer)
31 |
32 | assertEquals(-255, unmarshalled.num1)
33 | assertEquals(-55.5F, unmarshalled.num2)
34 | assertEquals((-3).toShort(), unmarshalled.num3)
35 | assertEquals(-500.25, unmarshalled.num4, 0.0)
36 | assertEquals(-1536094776123L, unmarshalled.num5)
37 | }
38 |
39 | @Test
40 | fun nestReadAndWrite() {
41 | val nest = Nest(listOf(Egg(2), Egg(9)))
42 | val moshiPack = MoshiPack()
43 | val byteArray = moshiPack.packToByteArray(nest)
44 | val unpackedNest: Nest = moshiPack.unpack(byteArray)
45 |
46 | assertEquals(nest, unpackedNest)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/moshipack/src/test/kotlin/TestTransform.kt:
--------------------------------------------------------------------------------
1 | import com.daveanthonythomas.moshipack.MoshiPack
2 | import okio.ByteString
3 | import org.junit.Assert.assertEquals
4 | import org.junit.Test
5 |
6 | class TestTransform {
7 |
8 | @Test
9 | fun fromJsonToMsgpack() {
10 | val pack = MoshiPack.jsonToMsgpack("{\"compact\":true,\"schema\":0}")
11 | assertEquals("82a7${"compact".hex}c3a6${"schema".hex}00", pack.readByteString().hex())
12 | }
13 |
14 | @Test
15 | fun fromMsgpackToJson() {
16 | val json = MoshiPack.msgpackToJson(ByteString.decodeHex("82a7${"compact".hex}c3a6${"schema".hex}00").toByteArray())
17 | assertEquals("{\"compact\":true,\"schema\":0.0}", json)
18 | }
19 |
20 | @Test
21 | fun fromJsonToMsgpack2() {
22 | val pack = MoshiPack().jsonToMsgpack("{\"compact\":true,\"schema\":0,\"name\":\"MoshiPack\"}")
23 | assertEquals("83a7${"compact".hex}c3a6${"schema".hex}00a4${"name".hex}a9${"MoshiPack".hex}",
24 | pack.readByteString().hex())
25 | }
26 |
27 | @Test
28 | fun fromMsgpackToJson2() {
29 | val json = MoshiPack().msgpackToJson(ByteString.decodeHex("83a7${"compact".hex}c3a6${"schema".hex}00a4${"name".hex}a9${"MoshiPack".hex}").toByteArray())
30 | assertEquals("{\"compact\":true,\"schema\":0.0,\"name\":\"MoshiPack\"}", json)
31 | }
32 | }
--------------------------------------------------------------------------------
/moshipack/src/test/kotlin/TestUtil.kt:
--------------------------------------------------------------------------------
1 | import okio.Buffer
2 | import okio.ByteString
3 |
4 | operator fun Buffer.plusAssign(string: String) {
5 | this.write(okio.ByteString.decodeHex(string))
6 | }
7 |
8 | val String.hex: String get() = ByteString.encodeUtf8(this).hex()
9 |
--------------------------------------------------------------------------------
/moshipack/src/test/resources/cats:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/davethomas11/MoshiPack/5f30e820923b5fde92e36a6fccf748dec8830504/moshipack/src/test/resources/cats
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include 'moshipack-retrofit'
2 | include 'moshipack'
3 |
--------------------------------------------------------------------------------