├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs └── test.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .idea/ 4 | *.iml 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | cache: cargo 3 | rust: 4 | - nightly 5 | - 1.15.0 6 | script: 7 | - cargo test 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "serde-transcode" 3 | version = "1.1.1" 4 | authors = ["Steven Fackler "] 5 | license = "MIT/Apache-2.0" 6 | description = "Transcode from one Serde format to another" 7 | repository = "https://github.com/sfackler/serde-transcode" 8 | documentation = "https://docs.rs/serde-transcode/1.1.0/serde_transcode" 9 | readme = "README.md" 10 | 11 | [dependencies] 12 | serde = "1.0" 13 | 14 | [dev-dependencies] 15 | serde_json = "1.0" 16 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 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 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 The serde-transcode Developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serde-transcode 2 | 3 | [![Build Status](https://travis-ci.org/sfackler/serde-transcode.svg?branch=master)](https://travis-ci.org/sfackler/serde-transcode) 4 | 5 | [Documentation](https://docs.rs/serde-transcode) 6 | 7 | Transcode from one Serde format to another. 8 | 9 | ## License 10 | 11 | Licensed under either of 12 | 13 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 14 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 15 | 16 | at your option. 17 | 18 | ### Contribution 19 | 20 | Unless you explicitly state otherwise, any contribution intentionally 21 | submitted for inclusion in the work by you, as defined in the Apache-2.0 22 | license, shall be dual licensed as above, without any additional terms or 23 | conditions. 24 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Transcode from one Serde format to another. 2 | //! 3 | //! This crate provides functionality to "transcode" from an arbitrary Serde 4 | //! `Deserializer` to an arbitrary Serde `Serializer` without needing to 5 | //! collect the entire input into an intermediate form in memory. For example, 6 | //! you could translate a stream of JSON data into a stream of CBOR data, or 7 | //! translate JSON into its pretty-printed form. 8 | //! 9 | //! # Examples 10 | //! 11 | //! Translate a JSON file to a pretty-printed version. 12 | //! 13 | //! ```no_run 14 | //! extern crate serde; 15 | //! extern crate serde_json; 16 | //! extern crate serde_transcode; 17 | //! 18 | //! use serde::Serialize; 19 | //! use serde_json::{Serializer, Deserializer}; 20 | //! use std::io::{Read, Write, BufReader, BufWriter}; 21 | //! use std::fs::File; 22 | //! 23 | //! fn main() { 24 | //! let reader = BufReader::new(File::open("input.json").unwrap()); 25 | //! let writer = BufWriter::new(File::create("output.json").unwrap()); 26 | //! 27 | //! let mut deserializer = Deserializer::from_reader(reader); 28 | //! let mut serializer = Serializer::pretty(writer); 29 | //! serde_transcode::transcode(&mut deserializer, &mut serializer).unwrap(); 30 | //! serializer.into_inner().flush().unwrap(); 31 | //! } 32 | //! ``` 33 | #![warn(missing_docs)] 34 | #![doc(html_root_url="https://docs.rs/serde-transcode/1.0.1")] 35 | 36 | #[macro_use] 37 | extern crate serde; 38 | 39 | use serde::de; 40 | use serde::ser::{self, Serialize, SerializeSeq, SerializeMap}; 41 | use std::cell::RefCell; 42 | use std::fmt; 43 | 44 | #[cfg(test)] 45 | mod test; 46 | 47 | /// Transcodes from a Serde `Deserializer` to a Serde `Serializer`. 48 | pub fn transcode<'de, D, S>(d: D, s: S) -> Result 49 | where D: de::Deserializer<'de>, 50 | S: ser::Serializer 51 | { 52 | Transcoder::new(d).serialize(s) 53 | } 54 | 55 | /// A Serde transcoder. 56 | /// 57 | /// In most cases, the `transcode` function should be used instead of this 58 | /// type. 59 | /// 60 | /// # Note 61 | /// 62 | /// Unlike traditional serializable types, `Transcoder`'s `Serialize` 63 | /// implementation is *not* idempotent, as it advances the state of its 64 | /// internal `Deserializer`. It should only ever be serialized once. 65 | pub struct Transcoder(RefCell>); 66 | 67 | impl<'de, D> Transcoder 68 | where D: de::Deserializer<'de> 69 | { 70 | /// Constructs a new `Transcoder`. 71 | pub fn new(d: D) -> Transcoder { 72 | Transcoder(RefCell::new(Some(d))) 73 | } 74 | } 75 | 76 | impl<'de, D> ser::Serialize for Transcoder 77 | where D: de::Deserializer<'de> 78 | { 79 | fn serialize(&self, s: S) -> Result 80 | where S: ser::Serializer 81 | { 82 | self.0 83 | .borrow_mut() 84 | .take() 85 | .expect("Transcoder may only be serialized once") 86 | .deserialize_any(Visitor(s)) 87 | .map_err(d2s) 88 | } 89 | } 90 | 91 | struct Visitor(S); 92 | 93 | impl<'de, S> de::Visitor<'de> for Visitor 94 | where S: ser::Serializer 95 | { 96 | type Value = S::Ok; 97 | 98 | fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 99 | write!(fmt, "any value") 100 | } 101 | 102 | fn visit_bool(self, v: bool) -> Result 103 | where E: de::Error 104 | { 105 | self.0.serialize_bool(v).map_err(s2d) 106 | } 107 | 108 | fn visit_i8(self, v: i8) -> Result 109 | where E: de::Error 110 | { 111 | self.0.serialize_i8(v).map_err(s2d) 112 | } 113 | 114 | fn visit_i16(self, v: i16) -> Result 115 | where E: de::Error 116 | { 117 | self.0.serialize_i16(v).map_err(s2d) 118 | } 119 | 120 | fn visit_i32(self, v: i32) -> Result 121 | where E: de::Error 122 | { 123 | self.0.serialize_i32(v).map_err(s2d) 124 | } 125 | 126 | fn visit_i64(self, v: i64) -> Result 127 | where E: de::Error 128 | { 129 | self.0.serialize_i64(v).map_err(s2d) 130 | } 131 | 132 | fn visit_u8(self, v: u8) -> Result 133 | where E: de::Error 134 | { 135 | self.0.serialize_u8(v).map_err(s2d) 136 | } 137 | 138 | fn visit_u16(self, v: u16) -> Result 139 | where E: de::Error 140 | { 141 | self.0.serialize_u16(v).map_err(s2d) 142 | } 143 | 144 | fn visit_u32(self, v: u32) -> Result 145 | where E: de::Error 146 | { 147 | self.0.serialize_u32(v).map_err(s2d) 148 | } 149 | 150 | fn visit_u64(self, v: u64) -> Result 151 | where E: de::Error 152 | { 153 | self.0.serialize_u64(v).map_err(s2d) 154 | } 155 | 156 | serde_if_integer128! { 157 | fn visit_i128(self, v: i128) -> Result 158 | where E: de::Error 159 | { 160 | self.0.serialize_i128(v).map_err(s2d) 161 | } 162 | 163 | fn visit_u128(self, v: u128) -> Result 164 | where E: de::Error 165 | { 166 | self.0.serialize_u128(v).map_err(s2d) 167 | } 168 | } 169 | 170 | fn visit_f32(self, v: f32) -> Result 171 | where E: de::Error 172 | { 173 | self.0.serialize_f32(v).map_err(s2d) 174 | } 175 | 176 | fn visit_f64(self, v: f64) -> Result 177 | where E: de::Error 178 | { 179 | self.0.serialize_f64(v).map_err(s2d) 180 | } 181 | 182 | fn visit_char(self, v: char) -> Result 183 | where E: de::Error 184 | { 185 | self.0.serialize_char(v).map_err(s2d) 186 | } 187 | 188 | fn visit_str(self, v: &str) -> Result 189 | where E: de::Error 190 | { 191 | self.0.serialize_str(v).map_err(s2d) 192 | } 193 | 194 | fn visit_string(self, v: String) -> Result 195 | where E: de::Error 196 | { 197 | self.0.serialize_str(&v).map_err(s2d) 198 | } 199 | 200 | fn visit_unit(self) -> Result 201 | where E: de::Error 202 | { 203 | self.0.serialize_unit().map_err(s2d) 204 | } 205 | 206 | fn visit_none(self) -> Result 207 | where E: de::Error 208 | { 209 | self.0.serialize_none().map_err(s2d) 210 | } 211 | 212 | fn visit_some(self, d: D) -> Result 213 | where D: de::Deserializer<'de> 214 | { 215 | self.0.serialize_some(&Transcoder::new(d)).map_err(s2d) 216 | } 217 | 218 | fn visit_newtype_struct(self, d: D) -> Result 219 | where D: de::Deserializer<'de> 220 | { 221 | self.0.serialize_newtype_struct("", &Transcoder::new(d)).map_err(s2d) 222 | } 223 | 224 | fn visit_seq(self, mut v: V) -> Result 225 | where V: de::SeqAccess<'de> 226 | { 227 | let mut s = self.0.serialize_seq(v.size_hint()).map_err(s2d)?; 228 | while let Some(()) = v.next_element_seed(SeqSeed(&mut s))? {} 229 | s.end().map_err(s2d) 230 | } 231 | 232 | fn visit_map(self, mut v: V) -> Result 233 | where V: de::MapAccess<'de> 234 | { 235 | let mut s = self.0.serialize_map(v.size_hint()).map_err(s2d)?; 236 | while let Some(()) = v.next_key_seed(KeySeed(&mut s))? { 237 | v.next_value_seed(ValueSeed(&mut s))?; 238 | } 239 | s.end().map_err(s2d) 240 | } 241 | 242 | fn visit_bytes(self, v: &[u8]) -> Result 243 | where E: de::Error 244 | { 245 | self.0.serialize_bytes(v).map_err(s2d) 246 | } 247 | 248 | fn visit_byte_buf(self, v: Vec) -> Result 249 | where E: de::Error 250 | { 251 | self.0.serialize_bytes(&v).map_err(s2d) 252 | } 253 | } 254 | 255 | struct SeqSeed<'a, S: 'a>(&'a mut S); 256 | 257 | impl<'de, 'a, S> de::DeserializeSeed<'de> for SeqSeed<'a, S> 258 | where S: ser::SerializeSeq 259 | { 260 | type Value = (); 261 | 262 | fn deserialize(self, deserializer: D) -> Result<(), D::Error> 263 | where D: de::Deserializer<'de> 264 | { 265 | self.0.serialize_element(&Transcoder::new(deserializer)).map_err(s2d) 266 | } 267 | } 268 | 269 | struct KeySeed<'a, S: 'a>(&'a mut S); 270 | 271 | impl<'de, 'a, S> de::DeserializeSeed<'de> for KeySeed<'a, S> 272 | where S: ser::SerializeMap 273 | { 274 | type Value = (); 275 | 276 | fn deserialize(self, deserializer: D) -> Result<(), D::Error> 277 | where D: de::Deserializer<'de> 278 | { 279 | self.0.serialize_key(&Transcoder::new(deserializer)).map_err(s2d) 280 | } 281 | } 282 | 283 | struct ValueSeed<'a, S: 'a>(&'a mut S); 284 | 285 | impl<'de, 'a, S> de::DeserializeSeed<'de> for ValueSeed<'a, S> 286 | where S: ser::SerializeMap 287 | { 288 | type Value = (); 289 | 290 | fn deserialize(self, deserializer: D) -> Result<(), D::Error> 291 | where D: de::Deserializer<'de> 292 | { 293 | self.0.serialize_value(&Transcoder::new(deserializer)).map_err(s2d) 294 | } 295 | } 296 | 297 | fn d2s(d: D) -> S 298 | where D: de::Error, 299 | S: ser::Error 300 | { 301 | S::custom(d.to_string()) 302 | } 303 | 304 | fn s2d(s: S) -> D 305 | where S: ser::Error, 306 | D: de::Error 307 | { 308 | D::custom(s.to_string()) 309 | } 310 | -------------------------------------------------------------------------------- /src/test.rs: -------------------------------------------------------------------------------- 1 | extern crate serde_json; 2 | 3 | use serde::{ser, de}; 4 | use std::collections::HashMap; 5 | use std::fmt; 6 | 7 | use super::*; 8 | 9 | fn test(input: T) 10 | where T: fmt::Debug + PartialEq + ser::Serialize + de::DeserializeOwned 11 | { 12 | let json = serde_json::to_string(&input).unwrap(); 13 | println!("json: {}", json); 14 | let mut de = serde_json::Deserializer::from_str(&json); 15 | let pretty = serde_json::to_string_pretty(&Transcoder::new(&mut de)).unwrap(); 16 | println!("pretty: {}", pretty); 17 | let output: T = serde_json::from_str(&pretty).unwrap(); 18 | println!("output: {:?}", output); 19 | assert_eq!(input, output); 20 | } 21 | 22 | #[test] 23 | fn bool() { 24 | test(true); 25 | test(false); 26 | } 27 | 28 | #[test] 29 | fn isize() { 30 | test(isize::min_value()); 31 | test(0isize); 32 | test(isize::max_value()); 33 | } 34 | 35 | #[test] 36 | fn i8() { 37 | test(i8::min_value()); 38 | test(0i8); 39 | test(i8::max_value()); 40 | } 41 | 42 | #[test] 43 | fn i16() { 44 | test(i16::min_value()); 45 | test(0i16); 46 | test(i16::max_value()); 47 | } 48 | 49 | #[test] 50 | fn i32() { 51 | test(i32::min_value()); 52 | test(0i32); 53 | test(i32::max_value()); 54 | } 55 | 56 | #[test] 57 | fn i64() { 58 | test(i64::min_value()); 59 | test(0i64); 60 | test(i64::max_value()); 61 | } 62 | 63 | #[test] 64 | fn usize() { 65 | test(0usize); 66 | test(u32::max_value() as usize + 1); 67 | } 68 | 69 | #[test] 70 | fn u8() { 71 | test(0u8); 72 | test(u8::max_value()); 73 | } 74 | 75 | #[test] 76 | fn u16() { 77 | test(0u16); 78 | test(u16::max_value()); 79 | } 80 | 81 | #[test] 82 | fn u32() { 83 | test(0u32); 84 | test(u32::max_value()); 85 | } 86 | 87 | #[test] 88 | fn u64() { 89 | test(0u64); 90 | test(u32::max_value() as u64 + 1); 91 | } 92 | 93 | serde_if_integer128! { 94 | #[test] 95 | fn i128() { 96 | // JSON not support too large numbers 97 | test(i64::min_value() as i128); 98 | test(0i128); 99 | // JSON not support too large numbers 100 | test(i64::max_value() as i128 + 1); 101 | } 102 | 103 | #[test] 104 | fn u128() { 105 | test(0u128); 106 | // JSON not support too large numbers 107 | test(u32::max_value() as u128 + 1); 108 | } 109 | } 110 | 111 | #[test] 112 | fn f32() { 113 | test(1.3f32); 114 | test(-1e10f32); 115 | } 116 | 117 | #[test] 118 | fn f64() { 119 | test(1.3f64); 120 | test(-1e10f64); 121 | } 122 | 123 | #[test] 124 | fn char() { 125 | test('a'); 126 | test('\0'); 127 | } 128 | 129 | #[test] 130 | fn str() { 131 | test("hello world".to_string()); 132 | test("".to_string()); 133 | } 134 | 135 | #[test] 136 | fn unit() { 137 | test(()); 138 | } 139 | 140 | #[test] 141 | fn none() { 142 | test(None::); 143 | } 144 | 145 | #[test] 146 | fn some() { 147 | test(Some(0i32)); 148 | test(Some("hi".to_string())); 149 | } 150 | 151 | #[test] 152 | fn newtype_struct() { 153 | #[derive(PartialEq, Debug)] 154 | struct Foo(i32); 155 | 156 | impl ser::Serialize for Foo { 157 | fn serialize(&self, s: S) -> Result 158 | where S: ser::Serializer 159 | { 160 | s.serialize_newtype_struct("Foo", &self.0) 161 | } 162 | } 163 | 164 | impl<'de> de::Deserialize<'de> for Foo { 165 | fn deserialize(d: D) -> Result 166 | where D: de::Deserializer<'de> 167 | { 168 | struct V; 169 | 170 | impl<'de> de::Visitor<'de> for V { 171 | type Value = Foo; 172 | 173 | fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 174 | write!(fmt, "a Foo struct") 175 | } 176 | 177 | fn visit_newtype_struct(self, d: D) -> Result 178 | where D: de::Deserializer<'de> 179 | { 180 | Ok(Foo(try!(de::Deserialize::deserialize(d)))) 181 | } 182 | } 183 | 184 | d.deserialize_newtype_struct("Foo", V) 185 | } 186 | } 187 | 188 | test(Foo(100)); 189 | } 190 | 191 | #[test] 192 | fn seq() { 193 | test(vec![0, 1, 2, 3]); 194 | } 195 | 196 | #[test] 197 | fn map() { 198 | let mut map = HashMap::new(); 199 | map.insert("hello".to_owned(), vec![1, 2]); 200 | map.insert("goodbye".to_owned(), vec![]); 201 | test(map); 202 | } 203 | --------------------------------------------------------------------------------