serde_test-1.0.102/Cargo.toml.orig010066400017500001750000000015541355540015400151350ustar0000000000000000[package] name = "serde_test" version = "1.0.102" # remember to update html_root_url authors = ["Erick Tryzelaar ", "David Tolnay "] license = "MIT OR Apache-2.0" description = "Token De/Serializer for testing De/Serialize implementations" homepage = "https://serde.rs" repository = "https://github.com/serde-rs/serde" documentation = "https://docs.serde.rs/serde_test/" keywords = ["serde", "serialization"] readme = "crates-io.md" include = ["Cargo.toml", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] [dependencies] serde = { version = "1.0.60", path = "../serde" } [dev-dependencies] serde = { version = "1.0", path = "../serde" } serde_derive = { version = "1.0", path = "../serde_derive" } [badges] travis-ci = { repository = "serde-rs/serde" } appveyor = { repository = "serde-rs/serde" } serde_test-1.0.102/Cargo.toml0000644000000024231355540030300114310ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "serde_test" version = "1.0.102" authors = ["Erick Tryzelaar ", "David Tolnay "] include = ["Cargo.toml", "src/**/*.rs", "crates-io.md", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] description = "Token De/Serializer for testing De/Serialize implementations" homepage = "https://serde.rs" documentation = "https://docs.serde.rs/serde_test/" readme = "crates-io.md" keywords = ["serde", "serialization"] license = "MIT OR Apache-2.0" repository = "https://github.com/serde-rs/serde" [dependencies.serde] version = "1.0.60" [dev-dependencies.serde] version = "1.0" [dev-dependencies.serde_derive] version = "1.0" [badges.appveyor] repository = "serde-rs/serde" [badges.travis-ci] repository = "serde-rs/serde" serde_test-1.0.102/LICENSE-APACHE010064400017500001750000000251371346021212500141650ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. serde_test-1.0.102/LICENSE-MIT010064400017500001750000000017771346021212500137010ustar0000000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. serde_test-1.0.102/README.md010066400017500001750000000064361352637575700135530ustar0000000000000000# Serde   [![Build Status]][travis] [![Latest Version]][crates.io] [![serde: rustc 1.13+]][Rust 1.13] [![serde_derive: rustc 1.31+]][Rust 1.31] [Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master [travis]: https://travis-ci.org/serde-rs/serde [Latest Version]: https://img.shields.io/crates/v/serde.svg [crates.io]: https://crates.io/crates/serde [serde: rustc 1.13+]: https://img.shields.io/badge/serde-rustc_1.13+-lightgray.svg [serde_derive: rustc 1.31+]: https://img.shields.io/badge/serde_derive-rustc_1.31+-lightgray.svg [Rust 1.13]: https://blog.rust-lang.org/2016/11/10/Rust-1.13.html [Rust 1.31]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html **Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** --- You may be looking for: - [An overview of Serde](https://serde.rs/) - [Data formats supported by Serde](https://serde.rs/#data-formats) - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) - [Examples](https://serde.rs/examples.html) - [API documentation](https://docs.serde.rs/serde/) - [Release notes](https://github.com/serde-rs/serde/releases) ## Serde in action
Click to show Cargo.toml. Run this code in the playground. ```toml [dependencies] # The core APIs, including the Serialize and Deserialize traits. Always # required when using Serde. The "derive" feature is only required when # using #[derive(Serialize, Deserialize)] to make Serde work with structs # and enums defined in your crate. serde = { version = "1.0", features = ["derive"] } # Each data format lives in its own crate; the sample code below uses JSON # but you may be using a different one. serde_json = "1.0" ```

```rust use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 1, y: 2 }; // Convert the Point to a JSON string. let serialized = serde_json::to_string(&point).unwrap(); // Prints serialized = {"x":1,"y":2} println!("serialized = {}", serialized); // Convert the JSON string back to a Point. let deserialized: Point = serde_json::from_str(&serialized).unwrap(); // Prints deserialized = Point { x: 1, y: 2 } println!("deserialized = {:?}", deserialized); } ``` ## Getting help Serde developers live in the #serde channel on [`irc.mozilla.org`][irc]. The \#rust channel is also a good resource with generally faster response time but less specific knowledge about Serde. If IRC is not your thing or you don't get a good response, we are happy to respond to [GitHub issues][issues] as well. [irc]: https://wiki.mozilla.org/IRC [issues]: https://github.com/serde-rs/serde/issues/new/choose
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Serde by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. serde_test-1.0.102/crates-io.md010064400017500001750000000030711346021212500144420ustar0000000000000000 **Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** --- You may be looking for: - [An overview of Serde](https://serde.rs/) - [Data formats supported by Serde](https://serde.rs/#data-formats) - [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/derive.html) - [Examples](https://serde.rs/examples.html) - [API documentation](https://docs.serde.rs/serde/) - [Release notes](https://github.com/serde-rs/serde/releases) ## Serde in action ```rust use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Point { x: i32, y: i32, } fn main() { let point = Point { x: 1, y: 2 }; // Convert the Point to a JSON string. let serialized = serde_json::to_string(&point).unwrap(); // Prints serialized = {"x":1,"y":2} println!("serialized = {}", serialized); // Convert the JSON string back to a Point. let deserialized: Point = serde_json::from_str(&serialized).unwrap(); // Prints deserialized = Point { x: 1, y: 2 } println!("deserialized = {:?}", deserialized); } ``` ## Getting help Serde developers live in the #serde channel on [`irc.mozilla.org`][irc]. The \#rust channel is also a good resource with generally faster response time but less specific knowledge about Serde. If IRC is not your thing or you don't get a good response, we are happy to respond to [GitHub issues][issues] as well. [irc]: https://wiki.mozilla.org/IRC [issues]: https://github.com/serde-rs/serde/issues/new/choose serde_test-1.0.102/src/assert.rs010064400017500001750000000132531354726022000147000ustar0000000000000000use serde::{Deserialize, Serialize}; use de::Deserializer; use ser::Serializer; use token::Token; use std::fmt::Debug; /// Runs both `assert_ser_tokens` and `assert_de_tokens`. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// struct S { /// a: u8, /// b: u8, /// } /// /// let s = S { a: 0, b: 0 }; /// assert_tokens(&s, &[ /// Token::Struct { name: "S", len: 2 }, /// Token::Str("a"), /// Token::U8(0), /// Token::Str("b"), /// Token::U8(0), /// Token::StructEnd, /// ]); /// ``` pub fn assert_tokens<'de, T>(value: &T, tokens: &'de [Token]) where T: Serialize + Deserialize<'de> + PartialEq + Debug, { assert_ser_tokens(value, tokens); assert_de_tokens(value, tokens); } /// Asserts that `value` serializes to the given `tokens`. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_ser_tokens, Token}; /// # /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// struct S { /// a: u8, /// b: u8, /// } /// /// let s = S { a: 0, b: 0 }; /// assert_ser_tokens(&s, &[ /// Token::Struct { name: "S", len: 2 }, /// Token::Str("a"), /// Token::U8(0), /// Token::Str("b"), /// Token::U8(0), /// Token::StructEnd, /// ]); /// ``` pub fn assert_ser_tokens(value: &T, tokens: &[Token]) where T: Serialize, { let mut ser = Serializer::new(tokens); match value.serialize(&mut ser) { Ok(_) => {} Err(err) => panic!("value failed to serialize: {}", err), } if ser.remaining() > 0 { panic!("{} remaining tokens", ser.remaining()); } } /// Asserts that `value` serializes to the given `tokens`, and then yields /// `error`. /// /// ```edition2018 /// use std::sync::{Arc, Mutex}; /// use std::thread; /// /// use serde::Serialize; /// use serde_test::{assert_ser_tokens_error, Token}; /// /// #[derive(Serialize)] /// struct Example { /// lock: Arc>, /// } /// /// fn main() { /// let example = Example { lock: Arc::new(Mutex::new(0)) }; /// let lock = example.lock.clone(); /// /// let _ = thread::spawn(move || { /// // This thread will acquire the mutex first, unwrapping the result /// // of `lock` because the lock has not been poisoned. /// let _guard = lock.lock().unwrap(); /// /// // This panic while holding the lock (`_guard` is in scope) will /// // poison the mutex. /// panic!() /// }).join(); /// /// let expected = &[ /// Token::Struct { name: "Example", len: 1 }, /// Token::Str("lock"), /// ]; /// let error = "lock poison error while serializing"; /// assert_ser_tokens_error(&example, expected, error); /// } /// ``` pub fn assert_ser_tokens_error(value: &T, tokens: &[Token], error: &str) where T: Serialize, { let mut ser = Serializer::new(tokens); match value.serialize(&mut ser) { Ok(_) => panic!("value serialized successfully"), Err(e) => assert_eq!(e, *error), } if ser.remaining() > 0 { panic!("{} remaining tokens", ser.remaining()); } } /// Asserts that the given `tokens` deserialize into `value`. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_de_tokens, Token}; /// # /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// struct S { /// a: u8, /// b: u8, /// } /// /// let s = S { a: 0, b: 0 }; /// assert_de_tokens(&s, &[ /// Token::Struct { name: "S", len: 2 }, /// Token::Str("a"), /// Token::U8(0), /// Token::Str("b"), /// Token::U8(0), /// Token::StructEnd, /// ]); /// ``` pub fn assert_de_tokens<'de, T>(value: &T, tokens: &'de [Token]) where T: Deserialize<'de> + PartialEq + Debug, { let mut de = Deserializer::new(tokens); let mut deserialized_val = match T::deserialize(&mut de) { Ok(v) => { assert_eq!(v, *value); v } Err(e) => panic!("tokens failed to deserialize: {}", e), }; if de.remaining() > 0 { panic!("{} remaining tokens", de.remaining()); } // Do the same thing for deserialize_in_place. This isn't *great* because a // no-op impl of deserialize_in_place can technically succeed here. Still, // this should catch a lot of junk. let mut de = Deserializer::new(tokens); match T::deserialize_in_place(&mut de, &mut deserialized_val) { Ok(()) => { assert_eq!(deserialized_val, *value); } Err(e) => panic!("tokens failed to deserialize_in_place: {}", e), } if de.remaining() > 0 { panic!("{} remaining tokens", de.remaining()); } } /// Asserts that the given `tokens` yield `error` when deserializing. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_de_tokens_error, Token}; /// # /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// #[serde(deny_unknown_fields)] /// struct S { /// a: u8, /// b: u8, /// } /// /// assert_de_tokens_error::( /// &[ /// Token::Struct { name: "S", len: 2 }, /// Token::Str("x"), /// ], /// "unknown field `x`, expected `a` or `b`", /// ); /// ``` pub fn assert_de_tokens_error<'de, T>(tokens: &'de [Token], error: &str) where T: Deserialize<'de>, { let mut de = Deserializer::new(tokens); match T::deserialize(&mut de) { Ok(_) => panic!("tokens deserialized successfully"), Err(e) => assert_eq!(e, *error), } // There may be one token left if a peek caused the error de.next_token_opt(); if de.remaining() > 0 { panic!("{} remaining tokens", de.remaining()); } } serde_test-1.0.102/src/configure.rs010064400017500001750000000613551346021212500153610ustar0000000000000000use std::fmt; use serde::ser::{ SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Readable(T); #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Compact(T); /// Trait to determine whether a value is represented in human-readable or /// compact form. /// /// ```edition2018 /// use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// use serde_test::{assert_tokens, Configure, Token}; /// /// #[derive(Debug, PartialEq)] /// struct Example(u8, u8); /// /// impl Serialize for Example { /// fn serialize(&self, serializer: S) -> Result /// where /// S: Serializer, /// { /// if serializer.is_human_readable() { /// format!("{}.{}", self.0, self.1).serialize(serializer) /// } else { /// (self.0, self.1).serialize(serializer) /// } /// } /// } /// /// impl<'de> Deserialize<'de> for Example { /// fn deserialize(deserializer: D) -> Result /// where /// D: Deserializer<'de>, /// { /// use serde::de::Error; /// if deserializer.is_human_readable() { /// let s = String::deserialize(deserializer)?; /// let parts: Vec<_> = s.split('.').collect(); /// Ok(Example( /// parts[0].parse().map_err(D::Error::custom)?, /// parts[1].parse().map_err(D::Error::custom)?, /// )) /// } else { /// let (x, y) = Deserialize::deserialize(deserializer)?; /// Ok(Example(x, y)) /// } /// } /// } /// /// fn main() { /// assert_tokens( /// &Example(1, 0).compact(), /// &[ /// Token::Tuple { len: 2 }, /// Token::U8(1), /// Token::U8(0), /// Token::TupleEnd, /// ], /// ); /// assert_tokens(&Example(1, 0).readable(), &[Token::Str("1.0")]); /// } /// ``` pub trait Configure { /// Marks `self` as using `is_human_readable == true` fn readable(self) -> Readable where Self: Sized, { Readable(self) } /// Marks `self` as using `is_human_readable == false` fn compact(self) -> Compact where Self: Sized, { Compact(self) } } impl Configure for T {} impl Serialize for Readable where T: Serialize, { #[inline] fn serialize(&self, serializer: S) -> Result where S: Serializer, { self.0.serialize(Readable(serializer)) } } impl Serialize for Compact where T: Serialize, { #[inline] fn serialize(&self, serializer: S) -> Result where S: Serializer, { self.0.serialize(Compact(serializer)) } } impl<'de, T> Deserialize<'de> for Readable where T: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { T::deserialize(Readable(deserializer)).map(Readable) } } impl<'de, T> Deserialize<'de> for Compact where T: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { T::deserialize(Compact(deserializer)).map(Compact) } } impl<'de, T> DeserializeSeed<'de> for Readable where T: DeserializeSeed<'de>, { type Value = T::Value; fn deserialize(self, deserializer: D) -> Result where D: Deserializer<'de>, { self.0.deserialize(Readable(deserializer)) } } impl<'de, T> DeserializeSeed<'de> for Compact where T: DeserializeSeed<'de>, { type Value = T::Value; fn deserialize(self, deserializer: D) -> Result where D: Deserializer<'de>, { self.0.deserialize(Compact(deserializer)) } } macro_rules! forward_method { ($name: ident (self $(, $arg: ident : $arg_type: ty)* ) -> $return_type: ty) => { fn $name (self $(, $arg : $arg_type)* ) -> $return_type { (self.0).$name( $($arg),* ) } }; } macro_rules! forward_serialize_methods { ( $( $name: ident $arg_type: ty ),* ) => { $( forward_method!($name(self, v : $arg_type) -> Result); )* }; } macro_rules! impl_serializer { ($wrapper:ident, $is_human_readable:expr) => { impl Serializer for $wrapper where S: Serializer, { type Ok = S::Ok; type Error = S::Error; type SerializeSeq = $wrapper; type SerializeTuple = $wrapper; type SerializeTupleStruct = $wrapper; type SerializeTupleVariant = $wrapper; type SerializeMap = $wrapper; type SerializeStruct = $wrapper; type SerializeStructVariant = $wrapper; fn is_human_readable(&self) -> bool { $is_human_readable } forward_serialize_methods! { serialize_bool bool, serialize_i8 i8, serialize_i16 i16, serialize_i32 i32, serialize_i64 i64, serialize_u8 u8, serialize_u16 u16, serialize_u32 u32, serialize_u64 u64, serialize_f32 f32, serialize_f64 f64, serialize_char char, serialize_str &str, serialize_bytes &[u8], serialize_unit_struct &'static str } fn serialize_unit(self) -> Result { self.0.serialize_unit() } fn serialize_unit_variant( self, name: &'static str, variant_index: u32, variant: &'static str, ) -> Result { self.0.serialize_unit_variant(name, variant_index, variant) } fn serialize_newtype_struct( self, name: &'static str, value: &T, ) -> Result where T: Serialize, { self.0.serialize_newtype_struct(name, &$wrapper(value)) } fn serialize_newtype_variant( self, name: &'static str, variant_index: u32, variant: &'static str, value: &T, ) -> Result where T: Serialize, { self.0 .serialize_newtype_variant(name, variant_index, variant, &$wrapper(value)) } fn serialize_none(self) -> Result { self.0.serialize_none() } fn serialize_some(self, value: &T) -> Result where T: Serialize, { self.0.serialize_some(&$wrapper(value)) } fn serialize_seq(self, len: Option) -> Result { self.0.serialize_seq(len).map($wrapper) } fn serialize_tuple(self, len: usize) -> Result { self.0.serialize_tuple(len).map($wrapper) } fn serialize_tuple_struct( self, name: &'static str, len: usize, ) -> Result { self.0.serialize_tuple_struct(name, len).map($wrapper) } fn serialize_tuple_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result { self.0 .serialize_tuple_variant(name, variant_index, variant, len) .map($wrapper) } fn serialize_map(self, len: Option) -> Result { self.0.serialize_map(len).map($wrapper) } fn serialize_struct( self, name: &'static str, len: usize, ) -> Result { self.0.serialize_struct(name, len).map($wrapper) } fn serialize_struct_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result { self.0 .serialize_struct_variant(name, variant_index, variant, len) .map($wrapper) } } impl SerializeSeq for $wrapper where S: SerializeSeq, { type Ok = S::Ok; type Error = S::Error; fn serialize_element(&mut self, value: &T) -> Result<(), S::Error> where T: Serialize, { self.0.serialize_element(&$wrapper(value)) } fn end(self) -> Result { self.0.end() } } impl SerializeTuple for $wrapper where S: SerializeTuple, { type Ok = S::Ok; type Error = S::Error; fn serialize_element(&mut self, value: &T) -> Result<(), S::Error> where T: Serialize, { self.0.serialize_element(&$wrapper(value)) } fn end(self) -> Result { self.0.end() } } impl SerializeTupleStruct for $wrapper where S: SerializeTupleStruct, { type Ok = S::Ok; type Error = S::Error; fn serialize_field(&mut self, value: &T) -> Result<(), S::Error> where T: Serialize, { self.0.serialize_field(&$wrapper(value)) } fn end(self) -> Result { self.0.end() } } impl SerializeTupleVariant for $wrapper where S: SerializeTupleVariant, { type Ok = S::Ok; type Error = S::Error; fn serialize_field(&mut self, value: &T) -> Result<(), S::Error> where T: Serialize, { self.0.serialize_field(&$wrapper(value)) } fn end(self) -> Result { self.0.end() } } impl SerializeMap for $wrapper where S: SerializeMap, { type Ok = S::Ok; type Error = S::Error; fn serialize_key(&mut self, key: &T) -> Result<(), S::Error> where T: Serialize, { self.0.serialize_key(&$wrapper(key)) } fn serialize_value(&mut self, value: &T) -> Result<(), S::Error> where T: Serialize, { self.0.serialize_value(&$wrapper(value)) } fn serialize_entry( &mut self, key: &K, value: &V, ) -> Result<(), S::Error> where K: Serialize, V: Serialize, { self.0.serialize_entry(key, &$wrapper(value)) } fn end(self) -> Result { self.0.end() } } impl SerializeStruct for $wrapper where S: SerializeStruct, { type Ok = S::Ok; type Error = S::Error; fn serialize_field( &mut self, name: &'static str, field: &T, ) -> Result<(), S::Error> where T: Serialize, { self.0.serialize_field(name, &$wrapper(field)) } fn end(self) -> Result { self.0.end() } } impl SerializeStructVariant for $wrapper where S: SerializeStructVariant, { type Ok = S::Ok; type Error = S::Error; fn serialize_field( &mut self, name: &'static str, field: &T, ) -> Result<(), S::Error> where T: Serialize, { self.0.serialize_field(name, &$wrapper(field)) } fn end(self) -> Result { self.0.end() } } }; } impl_serializer!(Readable, true); impl_serializer!(Compact, false); use serde::de::{DeserializeSeed, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor}; macro_rules! forward_deserialize_methods { ( $wrapper : ident ( $( $name: ident ),* ) ) => { $( fn $name(self, visitor: V) -> Result where V: Visitor<'de>, { (self.0).$name($wrapper(visitor)) } )* }; } macro_rules! impl_deserializer { ($wrapper:ident, $is_human_readable:expr) => { impl<'de, D> Deserializer<'de> for $wrapper where D: Deserializer<'de>, { type Error = D::Error; forward_deserialize_methods! { $wrapper ( deserialize_any, deserialize_bool, deserialize_u8, deserialize_u16, deserialize_u32, deserialize_u64, deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_f32, deserialize_f64, deserialize_char, deserialize_str, deserialize_string, deserialize_bytes, deserialize_byte_buf, deserialize_option, deserialize_unit, deserialize_seq, deserialize_map, deserialize_identifier, deserialize_ignored_any ) } fn deserialize_unit_struct( self, name: &'static str, visitor: V, ) -> Result where V: Visitor<'de>, { self.0.deserialize_unit_struct(name, $wrapper(visitor)) } fn deserialize_newtype_struct( self, name: &'static str, visitor: V, ) -> Result where V: Visitor<'de>, { self.0.deserialize_newtype_struct(name, $wrapper(visitor)) } fn deserialize_tuple(self, len: usize, visitor: V) -> Result where V: Visitor<'de>, { self.0.deserialize_tuple(len, $wrapper(visitor)) } fn deserialize_tuple_struct( self, name: &'static str, len: usize, visitor: V, ) -> Result where V: Visitor<'de>, { self.0 .deserialize_tuple_struct(name, len, $wrapper(visitor)) } fn deserialize_struct( self, name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result where V: Visitor<'de>, { self.0.deserialize_struct(name, fields, $wrapper(visitor)) } fn deserialize_enum( self, name: &'static str, variants: &'static [&'static str], visitor: V, ) -> Result where V: Visitor<'de>, { self.0.deserialize_enum(name, variants, $wrapper(visitor)) } fn is_human_readable(&self) -> bool { $is_human_readable } } impl<'de, D> Visitor<'de> for $wrapper where D: Visitor<'de>, { type Value = D::Value; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.0.expecting(formatter) } fn visit_bool(self, v: bool) -> Result where E: Error, { self.0.visit_bool(v) } fn visit_i8(self, v: i8) -> Result where E: Error, { self.0.visit_i8(v) } fn visit_i16(self, v: i16) -> Result where E: Error, { self.0.visit_i16(v) } fn visit_i32(self, v: i32) -> Result where E: Error, { self.0.visit_i32(v) } fn visit_i64(self, v: i64) -> Result where E: Error, { self.0.visit_i64(v) } fn visit_u8(self, v: u8) -> Result where E: Error, { self.0.visit_u8(v) } fn visit_u16(self, v: u16) -> Result where E: Error, { self.0.visit_u16(v) } fn visit_u32(self, v: u32) -> Result where E: Error, { self.0.visit_u32(v) } fn visit_u64(self, v: u64) -> Result where E: Error, { self.0.visit_u64(v) } fn visit_f32(self, v: f32) -> Result where E: Error, { self.0.visit_f32(v) } fn visit_f64(self, v: f64) -> Result where E: Error, { self.0.visit_f64(v) } fn visit_char(self, v: char) -> Result where E: Error, { self.0.visit_char(v) } fn visit_str(self, v: &str) -> Result where E: Error, { self.0.visit_str(v) } fn visit_borrowed_str(self, v: &'de str) -> Result where E: Error, { self.0.visit_borrowed_str(v) } fn visit_string(self, v: String) -> Result where E: Error, { self.0.visit_string(v) } fn visit_bytes(self, v: &[u8]) -> Result where E: Error, { self.0.visit_bytes(v) } fn visit_borrowed_bytes(self, v: &'de [u8]) -> Result where E: Error, { self.0.visit_borrowed_bytes(v) } fn visit_byte_buf(self, v: Vec) -> Result where E: Error, { self.0.visit_byte_buf(v) } fn visit_none(self) -> Result where E: Error, { self.0.visit_none() } fn visit_some(self, deserializer: D2) -> Result where D2: Deserializer<'de>, { self.0.visit_some($wrapper(deserializer)) } fn visit_unit(self) -> Result where E: Error, { self.0.visit_unit() } fn visit_newtype_struct(self, deserializer: D2) -> Result where D2: Deserializer<'de>, { self.0.visit_newtype_struct($wrapper(deserializer)) } fn visit_seq(self, seq: V) -> Result where V: SeqAccess<'de>, { self.0.visit_seq($wrapper(seq)) } fn visit_map(self, map: V) -> Result where V: MapAccess<'de>, { self.0.visit_map($wrapper(map)) } fn visit_enum(self, data: V) -> Result where V: EnumAccess<'de>, { self.0.visit_enum($wrapper(data)) } } impl<'de, D> SeqAccess<'de> for $wrapper where D: SeqAccess<'de>, { type Error = D::Error; fn next_element_seed(&mut self, seed: T) -> Result, D::Error> where T: DeserializeSeed<'de>, { self.0.next_element_seed($wrapper(seed)) } fn size_hint(&self) -> Option { self.0.size_hint() } } impl<'de, D> MapAccess<'de> for $wrapper where D: MapAccess<'de>, { type Error = D::Error; fn next_key_seed(&mut self, seed: K) -> Result, D::Error> where K: DeserializeSeed<'de>, { self.0.next_key_seed($wrapper(seed)) } fn next_value_seed(&mut self, seed: V) -> Result where V: DeserializeSeed<'de>, { self.0.next_value_seed($wrapper(seed)) } fn size_hint(&self) -> Option { self.0.size_hint() } } impl<'de, D> EnumAccess<'de> for $wrapper where D: EnumAccess<'de>, { type Error = D::Error; type Variant = $wrapper; fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: DeserializeSeed<'de>, { self.0 .variant_seed($wrapper(seed)) .map(|(value, variant)| (value, $wrapper(variant))) } } impl<'de, D> VariantAccess<'de> for $wrapper where D: VariantAccess<'de>, { type Error = D::Error; fn unit_variant(self) -> Result<(), D::Error> { self.0.unit_variant() } fn newtype_variant_seed(self, seed: T) -> Result where T: DeserializeSeed<'de>, { self.0.newtype_variant_seed($wrapper(seed)) } fn tuple_variant(self, len: usize, visitor: V) -> Result where V: Visitor<'de>, { self.0.tuple_variant(len, $wrapper(visitor)) } fn struct_variant( self, fields: &'static [&'static str], visitor: V, ) -> Result where V: Visitor<'de>, { self.0.struct_variant(fields, $wrapper(visitor)) } } }; } impl_deserializer!(Readable, true); impl_deserializer!(Compact, false); serde_test-1.0.102/src/de.rs010066400017500001750000000472001352557314300137770ustar0000000000000000use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer}; use serde::de::{ self, Deserialize, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor, }; use error::Error; use token::Token; #[derive(Debug)] pub struct Deserializer<'de> { tokens: &'de [Token], } macro_rules! assert_next_token { ($de:expr, $expected:expr) => { match $de.next_token_opt() { Some(token) if token == $expected => {} Some(other) => panic!( "expected Token::{} but deserialization wants Token::{}", other, $expected ), None => panic!( "end of tokens but deserialization wants Token::{}", $expected ), } }; } macro_rules! unexpected { ($token:expr) => { panic!("deserialization did not expect this token: {}", $token) }; } macro_rules! end_of_tokens { () => { panic!("ran out of tokens to deserialize") }; } impl<'de> Deserializer<'de> { pub fn new(tokens: &'de [Token]) -> Self { Deserializer { tokens: tokens } } fn peek_token_opt(&self) -> Option { self.tokens.first().cloned() } fn peek_token(&self) -> Token { match self.peek_token_opt() { Some(token) => token, None => end_of_tokens!(), } } pub fn next_token_opt(&mut self) -> Option { match self.tokens.split_first() { Some((&first, rest)) => { self.tokens = rest; Some(first) } None => None, } } fn next_token(&mut self) -> Token { match self.tokens.split_first() { Some((&first, rest)) => { self.tokens = rest; first } None => end_of_tokens!(), } } pub fn remaining(&self) -> usize { self.tokens.len() } fn visit_seq( &mut self, len: Option, end: Token, visitor: V, ) -> Result where V: Visitor<'de>, { let value = visitor.visit_seq(DeserializerSeqVisitor { de: self, len: len, end: end, })?; assert_next_token!(self, end); Ok(value) } fn visit_map( &mut self, len: Option, end: Token, visitor: V, ) -> Result where V: Visitor<'de>, { let value = visitor.visit_map(DeserializerMapVisitor { de: self, len: len, end: end, })?; assert_next_token!(self, end); Ok(value) } } impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> { type Error = Error; forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf unit seq map identifier ignored_any } fn deserialize_any(self, visitor: V) -> Result where V: Visitor<'de>, { let token = self.next_token(); match token { Token::Bool(v) => visitor.visit_bool(v), Token::I8(v) => visitor.visit_i8(v), Token::I16(v) => visitor.visit_i16(v), Token::I32(v) => visitor.visit_i32(v), Token::I64(v) => visitor.visit_i64(v), Token::U8(v) => visitor.visit_u8(v), Token::U16(v) => visitor.visit_u16(v), Token::U32(v) => visitor.visit_u32(v), Token::U64(v) => visitor.visit_u64(v), Token::F32(v) => visitor.visit_f32(v), Token::F64(v) => visitor.visit_f64(v), Token::Char(v) => visitor.visit_char(v), Token::Str(v) => visitor.visit_str(v), Token::BorrowedStr(v) => visitor.visit_borrowed_str(v), Token::String(v) => visitor.visit_string(v.to_owned()), Token::Bytes(v) => visitor.visit_bytes(v), Token::BorrowedBytes(v) => visitor.visit_borrowed_bytes(v), Token::ByteBuf(v) => visitor.visit_byte_buf(v.to_vec()), Token::None => visitor.visit_none(), Token::Some => visitor.visit_some(self), Token::Unit | Token::UnitStruct { .. } => visitor.visit_unit(), Token::NewtypeStruct { .. } => visitor.visit_newtype_struct(self), Token::Seq { len } => self.visit_seq(len, Token::SeqEnd, visitor), Token::Tuple { len } => self.visit_seq(Some(len), Token::TupleEnd, visitor), Token::TupleStruct { len, .. } => { self.visit_seq(Some(len), Token::TupleStructEnd, visitor) } Token::Map { len } => self.visit_map(len, Token::MapEnd, visitor), Token::Struct { len, .. } => self.visit_map(Some(len), Token::StructEnd, visitor), Token::Enum { .. } => { let variant = self.next_token(); let next = self.peek_token(); match (variant, next) { (Token::Str(variant), Token::Unit) => { self.next_token(); visitor.visit_str(variant) } (Token::Bytes(variant), Token::Unit) => { self.next_token(); visitor.visit_bytes(variant) } (Token::U32(variant), Token::Unit) => { self.next_token(); visitor.visit_u32(variant) } (variant, Token::Unit) => unexpected!(variant), (variant, _) => { visitor.visit_map(EnumMapVisitor::new(self, variant, EnumFormat::Any)) } } } Token::UnitVariant { variant, .. } => visitor.visit_str(variant), Token::NewtypeVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new( self, Token::Str(variant), EnumFormat::Any, )), Token::TupleVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new( self, Token::Str(variant), EnumFormat::Seq, )), Token::StructVariant { variant, .. } => visitor.visit_map(EnumMapVisitor::new( self, Token::Str(variant), EnumFormat::Map, )), Token::SeqEnd | Token::TupleEnd | Token::TupleStructEnd | Token::MapEnd | Token::StructEnd | Token::TupleVariantEnd | Token::StructVariantEnd => { unexpected!(token); } } } fn deserialize_option(self, visitor: V) -> Result where V: Visitor<'de>, { match self.peek_token() { Token::Unit | Token::None => { self.next_token(); visitor.visit_none() } Token::Some => { self.next_token(); visitor.visit_some(self) } _ => self.deserialize_any(visitor), } } fn deserialize_enum( self, name: &'static str, _variants: &'static [&'static str], visitor: V, ) -> Result where V: Visitor<'de>, { match self.peek_token() { Token::Enum { name: n } if name == n => { self.next_token(); visitor.visit_enum(DeserializerEnumVisitor { de: self }) } Token::UnitVariant { name: n, .. } | Token::NewtypeVariant { name: n, .. } | Token::TupleVariant { name: n, .. } | Token::StructVariant { name: n, .. } if name == n => { visitor.visit_enum(DeserializerEnumVisitor { de: self }) } _ => { unexpected!(self.next_token()); } } } fn deserialize_unit_struct(self, name: &'static str, visitor: V) -> Result where V: Visitor<'de>, { match self.peek_token() { Token::UnitStruct { .. } => { assert_next_token!(self, Token::UnitStruct { name: name }); visitor.visit_unit() } _ => self.deserialize_any(visitor), } } fn deserialize_newtype_struct( self, name: &'static str, visitor: V, ) -> Result where V: Visitor<'de>, { match self.peek_token() { Token::NewtypeStruct { .. } => { assert_next_token!(self, Token::NewtypeStruct { name: name }); visitor.visit_newtype_struct(self) } _ => self.deserialize_any(visitor), } } fn deserialize_tuple(self, len: usize, visitor: V) -> Result where V: Visitor<'de>, { match self.peek_token() { Token::Unit | Token::UnitStruct { .. } => { self.next_token(); visitor.visit_unit() } Token::Seq { .. } => { self.next_token(); self.visit_seq(Some(len), Token::SeqEnd, visitor) } Token::Tuple { .. } => { self.next_token(); self.visit_seq(Some(len), Token::TupleEnd, visitor) } Token::TupleStruct { .. } => { self.next_token(); self.visit_seq(Some(len), Token::TupleStructEnd, visitor) } _ => self.deserialize_any(visitor), } } fn deserialize_tuple_struct( self, name: &'static str, len: usize, visitor: V, ) -> Result where V: Visitor<'de>, { match self.peek_token() { Token::Unit => { self.next_token(); visitor.visit_unit() } Token::UnitStruct { .. } => { assert_next_token!(self, Token::UnitStruct { name: name }); visitor.visit_unit() } Token::Seq { .. } => { self.next_token(); self.visit_seq(Some(len), Token::SeqEnd, visitor) } Token::Tuple { .. } => { self.next_token(); self.visit_seq(Some(len), Token::TupleEnd, visitor) } Token::TupleStruct { len: n, .. } => { assert_next_token!(self, Token::TupleStruct { name: name, len: n }); self.visit_seq(Some(len), Token::TupleStructEnd, visitor) } _ => self.deserialize_any(visitor), } } fn deserialize_struct( self, name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result where V: Visitor<'de>, { match self.peek_token() { Token::Struct { len: n, .. } => { assert_next_token!(self, Token::Struct { name: name, len: n }); self.visit_map(Some(fields.len()), Token::StructEnd, visitor) } Token::Map { .. } => { self.next_token(); self.visit_map(Some(fields.len()), Token::MapEnd, visitor) } _ => self.deserialize_any(visitor), } } fn is_human_readable(&self) -> bool { panic!( "Types which have different human-readable and compact representations \ must explicitly mark their test cases with `serde_test::Configure`" ); } } ////////////////////////////////////////////////////////////////////////// struct DeserializerSeqVisitor<'a, 'de: 'a> { de: &'a mut Deserializer<'de>, len: Option, end: Token, } impl<'de, 'a> SeqAccess<'de> for DeserializerSeqVisitor<'a, 'de> { type Error = Error; fn next_element_seed(&mut self, seed: T) -> Result, Error> where T: DeserializeSeed<'de>, { if self.de.peek_token_opt() == Some(self.end) { return Ok(None); } self.len = self.len.map(|len| len.saturating_sub(1)); seed.deserialize(&mut *self.de).map(Some) } fn size_hint(&self) -> Option { self.len } } ////////////////////////////////////////////////////////////////////////// struct DeserializerMapVisitor<'a, 'de: 'a> { de: &'a mut Deserializer<'de>, len: Option, end: Token, } impl<'de, 'a> MapAccess<'de> for DeserializerMapVisitor<'a, 'de> { type Error = Error; fn next_key_seed(&mut self, seed: K) -> Result, Error> where K: DeserializeSeed<'de>, { if self.de.peek_token_opt() == Some(self.end) { return Ok(None); } self.len = self.len.map(|len| len.saturating_sub(1)); seed.deserialize(&mut *self.de).map(Some) } fn next_value_seed(&mut self, seed: V) -> Result where V: DeserializeSeed<'de>, { seed.deserialize(&mut *self.de) } fn size_hint(&self) -> Option { self.len } } ////////////////////////////////////////////////////////////////////////// struct DeserializerEnumVisitor<'a, 'de: 'a> { de: &'a mut Deserializer<'de>, } impl<'de, 'a> EnumAccess<'de> for DeserializerEnumVisitor<'a, 'de> { type Error = Error; type Variant = Self; fn variant_seed(self, seed: V) -> Result<(V::Value, Self), Error> where V: DeserializeSeed<'de>, { match self.de.peek_token() { Token::UnitVariant { variant: v, .. } | Token::NewtypeVariant { variant: v, .. } | Token::TupleVariant { variant: v, .. } | Token::StructVariant { variant: v, .. } => { let de = v.into_deserializer(); let value = seed.deserialize(de)?; Ok((value, self)) } _ => { let value = seed.deserialize(&mut *self.de)?; Ok((value, self)) } } } } impl<'de, 'a> VariantAccess<'de> for DeserializerEnumVisitor<'a, 'de> { type Error = Error; fn unit_variant(self) -> Result<(), Error> { match self.de.peek_token() { Token::UnitVariant { .. } => { self.de.next_token(); Ok(()) } _ => Deserialize::deserialize(self.de), } } fn newtype_variant_seed(self, seed: T) -> Result where T: DeserializeSeed<'de>, { match self.de.peek_token() { Token::NewtypeVariant { .. } => { self.de.next_token(); seed.deserialize(self.de) } _ => seed.deserialize(self.de), } } fn tuple_variant(self, len: usize, visitor: V) -> Result where V: Visitor<'de>, { match self.de.peek_token() { Token::TupleVariant { len: enum_len, .. } => { let token = self.de.next_token(); if len == enum_len { self.de .visit_seq(Some(len), Token::TupleVariantEnd, visitor) } else { unexpected!(token); } } Token::Seq { len: Some(enum_len), } => { let token = self.de.next_token(); if len == enum_len { self.de.visit_seq(Some(len), Token::SeqEnd, visitor) } else { unexpected!(token); } } _ => de::Deserializer::deserialize_any(self.de, visitor), } } fn struct_variant( self, fields: &'static [&'static str], visitor: V, ) -> Result where V: Visitor<'de>, { match self.de.peek_token() { Token::StructVariant { len: enum_len, .. } => { let token = self.de.next_token(); if fields.len() == enum_len { self.de .visit_map(Some(fields.len()), Token::StructVariantEnd, visitor) } else { unexpected!(token); } } Token::Map { len: Some(enum_len), } => { let token = self.de.next_token(); if fields.len() == enum_len { self.de .visit_map(Some(fields.len()), Token::MapEnd, visitor) } else { unexpected!(token); } } _ => de::Deserializer::deserialize_any(self.de, visitor), } } } ////////////////////////////////////////////////////////////////////////// struct EnumMapVisitor<'a, 'de: 'a> { de: &'a mut Deserializer<'de>, variant: Option, format: EnumFormat, } enum EnumFormat { Seq, Map, Any, } impl<'a, 'de> EnumMapVisitor<'a, 'de> { fn new(de: &'a mut Deserializer<'de>, variant: Token, format: EnumFormat) -> Self { EnumMapVisitor { de: de, variant: Some(variant), format: format, } } } impl<'de, 'a> MapAccess<'de> for EnumMapVisitor<'a, 'de> { type Error = Error; fn next_key_seed(&mut self, seed: K) -> Result, Error> where K: DeserializeSeed<'de>, { match self.variant.take() { Some(Token::Str(variant)) => seed.deserialize(variant.into_deserializer()).map(Some), Some(Token::Bytes(variant)) => seed .deserialize(BytesDeserializer { value: variant }) .map(Some), Some(Token::U32(variant)) => seed.deserialize(variant.into_deserializer()).map(Some), Some(other) => unexpected!(other), None => Ok(None), } } fn next_value_seed(&mut self, seed: V) -> Result where V: DeserializeSeed<'de>, { match self.format { EnumFormat::Seq => { let value = { let visitor = DeserializerSeqVisitor { de: self.de, len: None, end: Token::TupleVariantEnd, }; seed.deserialize(SeqAccessDeserializer::new(visitor))? }; assert_next_token!(self.de, Token::TupleVariantEnd); Ok(value) } EnumFormat::Map => { let value = { let visitor = DeserializerMapVisitor { de: self.de, len: None, end: Token::StructVariantEnd, }; seed.deserialize(MapAccessDeserializer::new(visitor))? }; assert_next_token!(self.de, Token::StructVariantEnd); Ok(value) } EnumFormat::Any => seed.deserialize(&mut *self.de), } } } struct BytesDeserializer { value: &'static [u8], } impl<'de> de::Deserializer<'de> for BytesDeserializer { type Error = Error; fn deserialize_any(self, visitor: V) -> Result where V: de::Visitor<'de>, { visitor.visit_bytes(self.value) } forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum identifier ignored_any } } serde_test-1.0.102/src/error.rs010064400017500001750000000013671346021212500145260ustar0000000000000000use std::error; use std::fmt::{self, Display}; use serde::{de, ser}; #[derive(Clone, Debug)] pub struct Error { msg: String, } impl ser::Error for Error { fn custom(msg: T) -> Self { Error { msg: msg.to_string(), } } } impl de::Error for Error { fn custom(msg: T) -> Self { Error { msg: msg.to_string(), } } } impl fmt::Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(&self.msg) } } impl error::Error for Error { fn description(&self) -> &str { &self.msg } } impl PartialEq for Error { fn eq(&self, other: &str) -> bool { self.msg == other } } serde_test-1.0.102/src/lib.rs010064400017500001750000000127771355540015500141610ustar0000000000000000//! This crate provides a convenient concise way to write unit tests for //! implementations of [`Serialize`] and [`Deserialize`]. //! //! [`Serialize`]: https://docs.serde.rs/serde/ser/trait.Serialize.html //! [`Deserialize`]: https://docs.serde.rs/serde/de/trait.Deserialize.html //! //! The `Serialize` impl for a value can be characterized by the sequence of //! [`Serializer`] calls that are made in the course of serializing the value, //! so `serde_test` provides a [`Token`] abstraction which corresponds roughly //! to `Serializer` method calls. There is an [`assert_ser_tokens`] function to //! test that a value serializes to a particular sequence of method calls, an //! [`assert_de_tokens`] function to test that a value can be deserialized from //! a particular sequence of method calls, and an [`assert_tokens`] function to //! test both directions. There are also functions to test expected failure //! conditions. //! //! [`Serializer`]: https://docs.serde.rs/serde/ser/trait.Serializer.html //! [`Token`]: https://docs.serde.rs/serde_test/enum.Token.html //! [`assert_ser_tokens`]: https://docs.serde.rs/serde_test/fn.assert_ser_tokens.html //! [`assert_de_tokens`]: https://docs.serde.rs/serde_test/fn.assert_de_tokens.html //! [`assert_tokens`]: https://docs.serde.rs/serde_test/fn.assert_tokens.html //! //! Here is an example from the [`linked-hash-map`] crate. //! //! [`linked-hash-map`]: https://github.com/contain-rs/linked-hash-map //! //! ```edition2018 //! # const IGNORE: &str = stringify! { //! use linked_hash_map::LinkedHashMap; //! # }; //! use serde_test::{Token, assert_tokens}; //! //! # use std::fmt; //! # use std::marker::PhantomData; //! # //! # use serde::ser::{Serialize, Serializer, SerializeMap}; //! # use serde::de::{Deserialize, Deserializer, Visitor, MapAccess}; //! # //! # // Dumb imitation of LinkedHashMap. //! # #[derive(PartialEq, Debug)] //! # struct LinkedHashMap(Vec<(K, V)>); //! # //! # impl LinkedHashMap { //! # fn new() -> Self { //! # LinkedHashMap(Vec::new()) //! # } //! # //! # fn insert(&mut self, k: K, v: V) { //! # self.0.push((k, v)); //! # } //! # } //! # //! # impl Serialize for LinkedHashMap //! # where //! # K: Serialize, //! # V: Serialize, //! # { //! # fn serialize(&self, serializer: S) -> Result //! # where //! # S: Serializer, //! # { //! # let mut map = serializer.serialize_map(Some(self.0.len()))?; //! # for &(ref k, ref v) in &self.0 { //! # map.serialize_entry(k, v)?; //! # } //! # map.end() //! # } //! # } //! # //! # struct LinkedHashMapVisitor(PhantomData<(K, V)>); //! # //! # impl<'de, K, V> Visitor<'de> for LinkedHashMapVisitor //! # where //! # K: Deserialize<'de>, //! # V: Deserialize<'de>, //! # { //! # type Value = LinkedHashMap; //! # //! # fn expecting(&self, _: &mut fmt::Formatter) -> fmt::Result { //! # unimplemented!() //! # } //! # //! # fn visit_map(self, mut access: M) -> Result //! # where //! # M: MapAccess<'de>, //! # { //! # let mut map = LinkedHashMap::new(); //! # while let Some((key, value)) = access.next_entry()? { //! # map.insert(key, value); //! # } //! # Ok(map) //! # } //! # } //! # //! # impl<'de, K, V> Deserialize<'de> for LinkedHashMap //! # where //! # K: Deserialize<'de>, //! # V: Deserialize<'de>, //! # { //! # fn deserialize(deserializer: D) -> Result //! # where //! # D: Deserializer<'de>, //! # { //! # deserializer.deserialize_map(LinkedHashMapVisitor(PhantomData)) //! # } //! # } //! # //! #[test] //! # fn not_a_test_ser_de_empty() {} //! fn test_ser_de_empty() { //! let map = LinkedHashMap::::new(); //! //! assert_tokens(&map, &[ //! Token::Map { len: Some(0) }, //! Token::MapEnd, //! ]); //! } //! //! #[test] //! # fn not_a_test_ser_de() {} //! fn test_ser_de() { //! let mut map = LinkedHashMap::new(); //! map.insert('b', 20); //! map.insert('a', 10); //! map.insert('c', 30); //! //! assert_tokens(&map, &[ //! Token::Map { len: Some(3) }, //! Token::Char('b'), //! Token::I32(20), //! //! Token::Char('a'), //! Token::I32(10), //! //! Token::Char('c'), //! Token::I32(30), //! Token::MapEnd, //! ]); //! } //! # //! # fn main() { //! # test_ser_de_empty(); //! # test_ser_de(); //! # } //! ``` #![doc(html_root_url = "https://docs.rs/serde_test/1.0.102")] #![cfg_attr(feature = "cargo-clippy", allow(renamed_and_removed_lints))] #![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))] // Ignored clippy lints #![cfg_attr(feature = "cargo-clippy", allow(float_cmp, needless_doctest_main))] // Ignored clippy_pedantic lints #![cfg_attr( feature = "cargo-clippy", allow( empty_line_after_outer_attr, missing_docs_in_private_items, module_name_repetitions, must_use_candidate, redundant_field_names, use_debug, use_self ) )] #[macro_use] extern crate serde; mod de; mod error; mod ser; mod assert; mod configure; mod token; pub use assert::{ assert_de_tokens, assert_de_tokens_error, assert_ser_tokens, assert_ser_tokens_error, assert_tokens, }; pub use token::Token; pub use configure::{Compact, Configure, Readable}; // Not public API. #[doc(hidden)] pub use de::Deserializer; serde_test-1.0.102/src/ser.rs010066400017500001750000000302601352557314300141760ustar0000000000000000use serde::{ser, Serialize}; use error::Error; use token::Token; /// A `Serializer` that ensures that a value serializes to a given list of /// tokens. #[derive(Debug)] pub struct Serializer<'a> { tokens: &'a [Token], } impl<'a> Serializer<'a> { /// Creates the serializer. pub fn new(tokens: &'a [Token]) -> Self { Serializer { tokens: tokens } } /// Pulls the next token off of the serializer, ignoring it. fn next_token(&mut self) -> Option { if let Some((&first, rest)) = self.tokens.split_first() { self.tokens = rest; Some(first) } else { None } } pub fn remaining(&self) -> usize { self.tokens.len() } } macro_rules! assert_next_token { ($ser:expr, $expected:ident) => { assert_next_token!($ser, stringify!($expected), Token::$expected, true); }; ($ser:expr, $expected:ident($v:expr)) => { assert_next_token!( $ser, format_args!(concat!(stringify!($expected), "({:?})"), $v), Token::$expected(v), v == $v ); }; ($ser:expr, $expected:ident { $($k:ident),* }) => { let compare = ($($k,)*); let field_format = || { use std::fmt::Write; let mut buffer = String::new(); $( write!(&mut buffer, concat!(stringify!($k), ": {:?}, "), $k).unwrap(); )* buffer }; assert_next_token!( $ser, format_args!(concat!(stringify!($expected), " {{ {}}}"), field_format()), Token::$expected { $($k),* }, ($($k,)*) == compare ); }; ($ser:expr, $expected:expr, $pat:pat, $guard:expr) => { match $ser.next_token() { Some($pat) if $guard => {} Some(other) => { panic!("expected Token::{} but serialized as {}", $expected, other); } None => { panic!("expected Token::{} after end of serialized tokens", $expected); } } }; } impl<'s, 'a> ser::Serializer for &'s mut Serializer<'a> { type Ok = (); type Error = Error; type SerializeSeq = Self; type SerializeTuple = Self; type SerializeTupleStruct = Self; type SerializeTupleVariant = Variant<'s, 'a>; type SerializeMap = Self; type SerializeStruct = Self; type SerializeStructVariant = Variant<'s, 'a>; fn serialize_bool(self, v: bool) -> Result<(), Error> { assert_next_token!(self, Bool(v)); Ok(()) } fn serialize_i8(self, v: i8) -> Result<(), Error> { assert_next_token!(self, I8(v)); Ok(()) } fn serialize_i16(self, v: i16) -> Result<(), Error> { assert_next_token!(self, I16(v)); Ok(()) } fn serialize_i32(self, v: i32) -> Result<(), Error> { assert_next_token!(self, I32(v)); Ok(()) } fn serialize_i64(self, v: i64) -> Result<(), Error> { assert_next_token!(self, I64(v)); Ok(()) } fn serialize_u8(self, v: u8) -> Result<(), Error> { assert_next_token!(self, U8(v)); Ok(()) } fn serialize_u16(self, v: u16) -> Result<(), Error> { assert_next_token!(self, U16(v)); Ok(()) } fn serialize_u32(self, v: u32) -> Result<(), Error> { assert_next_token!(self, U32(v)); Ok(()) } fn serialize_u64(self, v: u64) -> Result<(), Error> { assert_next_token!(self, U64(v)); Ok(()) } fn serialize_f32(self, v: f32) -> Result<(), Error> { assert_next_token!(self, F32(v)); Ok(()) } fn serialize_f64(self, v: f64) -> Result<(), Error> { assert_next_token!(self, F64(v)); Ok(()) } fn serialize_char(self, v: char) -> Result<(), Error> { assert_next_token!(self, Char(v)); Ok(()) } fn serialize_str(self, v: &str) -> Result<(), Error> { match self.tokens.first() { Some(&Token::BorrowedStr(_)) => assert_next_token!(self, BorrowedStr(v)), Some(&Token::String(_)) => assert_next_token!(self, String(v)), _ => assert_next_token!(self, Str(v)), } Ok(()) } fn serialize_bytes(self, v: &[u8]) -> Result<(), Self::Error> { match self.tokens.first() { Some(&Token::BorrowedBytes(_)) => assert_next_token!(self, BorrowedBytes(v)), Some(&Token::ByteBuf(_)) => assert_next_token!(self, ByteBuf(v)), _ => assert_next_token!(self, Bytes(v)), } Ok(()) } fn serialize_unit(self) -> Result<(), Error> { assert_next_token!(self, Unit); Ok(()) } fn serialize_unit_struct(self, name: &'static str) -> Result<(), Error> { assert_next_token!(self, UnitStruct { name }); Ok(()) } fn serialize_unit_variant( self, name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result<(), Error> { if self.tokens.first() == Some(&Token::Enum { name: name }) { self.next_token(); assert_next_token!(self, Str(variant)); assert_next_token!(self, Unit); } else { assert_next_token!(self, UnitVariant { name, variant }); } Ok(()) } fn serialize_newtype_struct(self, name: &'static str, value: &T) -> Result<(), Error> where T: Serialize, { assert_next_token!(self, NewtypeStruct { name }); value.serialize(self) } fn serialize_newtype_variant( self, name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result<(), Error> where T: Serialize, { if self.tokens.first() == Some(&Token::Enum { name: name }) { self.next_token(); assert_next_token!(self, Str(variant)); } else { assert_next_token!(self, NewtypeVariant { name, variant }); } value.serialize(self) } fn serialize_none(self) -> Result<(), Error> { assert_next_token!(self, None); Ok(()) } fn serialize_some(self, value: &T) -> Result<(), Error> where T: Serialize, { assert_next_token!(self, Some); value.serialize(self) } fn serialize_seq(self, len: Option) -> Result { assert_next_token!(self, Seq { len }); Ok(self) } fn serialize_tuple(self, len: usize) -> Result { assert_next_token!(self, Tuple { len }); Ok(self) } fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result { assert_next_token!(self, TupleStruct { name, len }); Ok(self) } fn serialize_tuple_variant( self, name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result { if self.tokens.first() == Some(&Token::Enum { name: name }) { self.next_token(); assert_next_token!(self, Str(variant)); let len = Some(len); assert_next_token!(self, Seq { len }); Ok(Variant { ser: self, end: Token::SeqEnd, }) } else { assert_next_token!(self, TupleVariant { name, variant, len }); Ok(Variant { ser: self, end: Token::TupleVariantEnd, }) } } fn serialize_map(self, len: Option) -> Result { assert_next_token!(self, Map { len }); Ok(self) } fn serialize_struct(self, name: &'static str, len: usize) -> Result { assert_next_token!(self, Struct { name, len }); Ok(self) } fn serialize_struct_variant( self, name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result { if self.tokens.first() == Some(&Token::Enum { name: name }) { self.next_token(); assert_next_token!(self, Str(variant)); let len = Some(len); assert_next_token!(self, Map { len }); Ok(Variant { ser: self, end: Token::MapEnd, }) } else { assert_next_token!(self, StructVariant { name, variant, len }); Ok(Variant { ser: self, end: Token::StructVariantEnd, }) } } fn is_human_readable(&self) -> bool { panic!( "Types which have different human-readable and compact representations \ must explicitly mark their test cases with `serde_test::Configure`" ); } } pub struct Variant<'s, 'a: 's> { ser: &'s mut Serializer<'a>, end: Token, } impl<'s, 'a> ser::SerializeSeq for &'s mut Serializer<'a> { type Ok = (); type Error = Error; fn serialize_element(&mut self, value: &T) -> Result<(), Error> where T: Serialize, { value.serialize(&mut **self) } fn end(self) -> Result<(), Error> { assert_next_token!(self, SeqEnd); Ok(()) } } impl<'s, 'a> ser::SerializeTuple for &'s mut Serializer<'a> { type Ok = (); type Error = Error; fn serialize_element(&mut self, value: &T) -> Result<(), Error> where T: Serialize, { value.serialize(&mut **self) } fn end(self) -> Result<(), Error> { assert_next_token!(self, TupleEnd); Ok(()) } } impl<'s, 'a> ser::SerializeTupleStruct for &'s mut Serializer<'a> { type Ok = (); type Error = Error; fn serialize_field(&mut self, value: &T) -> Result<(), Error> where T: Serialize, { value.serialize(&mut **self) } fn end(self) -> Result<(), Error> { assert_next_token!(self, TupleStructEnd); Ok(()) } } impl<'s, 'a> ser::SerializeTupleVariant for Variant<'s, 'a> { type Ok = (); type Error = Error; fn serialize_field(&mut self, value: &T) -> Result<(), Error> where T: Serialize, { value.serialize(&mut *self.ser) } fn end(self) -> Result<(), Error> { match self.end { Token::TupleVariantEnd => assert_next_token!(self.ser, TupleVariantEnd), Token::SeqEnd => assert_next_token!(self.ser, SeqEnd), _ => unreachable!(), } Ok(()) } } impl<'s, 'a> ser::SerializeMap for &'s mut Serializer<'a> { type Ok = (); type Error = Error; fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize, { key.serialize(&mut **self) } fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize, { value.serialize(&mut **self) } fn end(self) -> Result<(), Self::Error> { assert_next_token!(self, MapEnd); Ok(()) } } impl<'s, 'a> ser::SerializeStruct for &'s mut Serializer<'a> { type Ok = (); type Error = Error; fn serialize_field( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize, { key.serialize(&mut **self)?; value.serialize(&mut **self) } fn end(self) -> Result<(), Self::Error> { assert_next_token!(self, StructEnd); Ok(()) } } impl<'s, 'a> ser::SerializeStructVariant for Variant<'s, 'a> { type Ok = (); type Error = Error; fn serialize_field( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize, { key.serialize(&mut *self.ser)?; value.serialize(&mut *self.ser) } fn end(self) -> Result<(), Self::Error> { match self.end { Token::StructVariantEnd => assert_next_token!(self.ser, StructVariantEnd), Token::MapEnd => assert_next_token!(self.ser, MapEnd), _ => unreachable!(), } Ok(()) } } serde_test-1.0.102/src/token.rs010064400017500001750000000312321346021212500145070ustar0000000000000000use std::fmt::{self, Debug, Display}; #[derive(Copy, Clone, PartialEq, Debug)] pub enum Token { /// A serialized `bool`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&true, &[Token::Bool(true)]); /// ``` Bool(bool), /// A serialized `i8`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0i8, &[Token::I8(0)]); /// ``` I8(i8), /// A serialized `i16`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0i16, &[Token::I16(0)]); /// ``` I16(i16), /// A serialized `i32`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0i32, &[Token::I32(0)]); /// ``` I32(i32), /// A serialized `i64`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0i64, &[Token::I64(0)]); /// ``` I64(i64), /// A serialized `u8`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0u8, &[Token::U8(0)]); /// ``` U8(u8), /// A serialized `u16`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0u16, &[Token::U16(0)]); /// ``` U16(u16), /// A serialized `u32`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0u32, &[Token::U32(0)]); /// ``` U32(u32), /// A serialized `u64`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0u64, &[Token::U64(0)]); /// ``` U64(u64), /// A serialized `f32`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0f32, &[Token::F32(0.0)]); /// ``` F32(f32), /// A serialized `f64`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0f64, &[Token::F64(0.0)]); /// ``` F64(f64), /// A serialized `char`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&'\n', &[Token::Char('\n')]); /// ``` Char(char), /// A serialized `str`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// let s = String::from("transient"); /// assert_tokens(&s, &[Token::Str("transient")]); /// ``` Str(&'static str), /// A borrowed `str`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// let s: &str = "borrowed"; /// assert_tokens(&s, &[Token::BorrowedStr("borrowed")]); /// ``` BorrowedStr(&'static str), /// A serialized `String`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// let s = String::from("owned"); /// assert_tokens(&s, &[Token::String("owned")]); /// ``` String(&'static str), /// A serialized `[u8]` Bytes(&'static [u8]), /// A borrowed `[u8]`. BorrowedBytes(&'static [u8]), /// A serialized `ByteBuf` ByteBuf(&'static [u8]), /// A serialized `Option` containing none. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// let opt = None::; /// assert_tokens(&opt, &[Token::None]); /// ``` None, /// The header to a serialized `Option` containing some value. /// /// The tokens of the value follow after this header. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// let opt = Some('c'); /// assert_tokens(&opt, &[ /// Token::Some, /// Token::Char('c'), /// ]); /// ``` Some, /// A serialized `()`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&(), &[Token::Unit]); /// ``` Unit, /// A serialized unit struct of the given name. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// struct X; /// /// assert_tokens(&X, &[Token::UnitStruct { name: "X" }]); /// # } /// ``` UnitStruct { name: &'static str }, /// A unit variant of an enum. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// enum E { /// A, /// } /// /// let a = E::A; /// assert_tokens(&a, &[Token::UnitVariant { name: "E", variant: "A" }]); /// # } /// ``` UnitVariant { name: &'static str, variant: &'static str, }, /// The header to a serialized newtype struct of the given name. /// /// After this header is the value contained in the newtype struct. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// struct N(String); /// /// let n = N("newtype".to_owned()); /// assert_tokens(&n, &[ /// Token::NewtypeStruct { name: "N" }, /// Token::String("newtype"), /// ]); /// # } /// ``` NewtypeStruct { name: &'static str }, /// The header to a newtype variant of an enum. /// /// After this header is the value contained in the newtype variant. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// enum E { /// B(u8), /// } /// /// let b = E::B(0); /// assert_tokens(&b, &[ /// Token::NewtypeVariant { name: "E", variant: "B" }, /// Token::U8(0), /// ]); /// # } /// ``` NewtypeVariant { name: &'static str, variant: &'static str, }, /// The header to a sequence. /// /// After this header are the elements of the sequence, followed by /// `SeqEnd`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// let vec = vec!['a', 'b', 'c']; /// assert_tokens(&vec, &[ /// Token::Seq { len: Some(3) }, /// Token::Char('a'), /// Token::Char('b'), /// Token::Char('c'), /// Token::SeqEnd, /// ]); /// ``` Seq { len: Option }, /// An indicator of the end of a sequence. SeqEnd, /// The header to a tuple. /// /// After this header are the elements of the tuple, followed by `TupleEnd`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// let tuple = ('a', 100); /// assert_tokens(&tuple, &[ /// Token::Tuple { len: 2 }, /// Token::Char('a'), /// Token::I32(100), /// Token::TupleEnd, /// ]); /// ``` Tuple { len: usize }, /// An indicator of the end of a tuple. TupleEnd, /// The header to a tuple struct. /// /// After this header are the fields of the tuple struct, followed by /// `TupleStructEnd`. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// struct T(u8, u8); /// /// let t = T(0, 0); /// assert_tokens(&t, &[ /// Token::TupleStruct { name: "T", len: 2 }, /// Token::U8(0), /// Token::U8(0), /// Token::TupleStructEnd, /// ]); /// # } /// ``` TupleStruct { name: &'static str, len: usize }, /// An indicator of the end of a tuple struct. TupleStructEnd, /// The header to a tuple variant of an enum. /// /// After this header are the fields of the tuple variant, followed by /// `TupleVariantEnd`. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// enum E { /// C(u8, u8), /// } /// /// let c = E::C(0, 0); /// assert_tokens(&c, &[ /// Token::TupleVariant { name: "E", variant: "C", len: 2 }, /// Token::U8(0), /// Token::U8(0), /// Token::TupleVariantEnd, /// ]); /// # } /// ``` TupleVariant { name: &'static str, variant: &'static str, len: usize, }, /// An indicator of the end of a tuple variant. TupleVariantEnd, /// The header to a map. /// /// After this header are the entries of the map, followed by `MapEnd`. /// /// ```edition2018 /// # use serde_test::{assert_tokens, Token}; /// # /// use std::collections::BTreeMap; /// /// let mut map = BTreeMap::new(); /// map.insert('A', 65); /// map.insert('Z', 90); /// /// assert_tokens(&map, &[ /// Token::Map { len: Some(2) }, /// Token::Char('A'), /// Token::I32(65), /// Token::Char('Z'), /// Token::I32(90), /// Token::MapEnd, /// ]); /// ``` Map { len: Option }, /// An indicator of the end of a map. MapEnd, /// The header of a struct. /// /// After this header are the fields of the struct, followed by `StructEnd`. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// struct S { /// a: u8, /// b: u8, /// } /// /// let s = S { a: 0, b: 0 }; /// assert_tokens(&s, &[ /// Token::Struct { name: "S", len: 2 }, /// Token::Str("a"), /// Token::U8(0), /// Token::Str("b"), /// Token::U8(0), /// Token::StructEnd, /// ]); /// # } /// ``` Struct { name: &'static str, len: usize }, /// An indicator of the end of a struct. StructEnd, /// The header of a struct variant of an enum. /// /// After this header are the fields of the struct variant, followed by /// `StructVariantEnd`. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// enum E { /// D { d: u8 }, /// } /// /// let d = E::D { d: 0 }; /// assert_tokens(&d, &[ /// Token::StructVariant { name: "E", variant: "D", len: 1 }, /// Token::Str("d"), /// Token::U8(0), /// Token::StructVariantEnd, /// ]); /// # } /// ``` StructVariant { name: &'static str, variant: &'static str, len: usize, }, /// An indicator of the end of a struct variant. StructVariantEnd, /// The header to an enum of the given name. /// /// ```edition2018 /// # use serde::{Serialize, Deserialize}; /// # use serde_test::{assert_tokens, Token}; /// # /// # fn main() { /// #[derive(Serialize, Deserialize, PartialEq, Debug)] /// enum E { /// A, /// B(u8), /// C(u8, u8), /// D { d: u8 }, /// } /// /// let a = E::A; /// assert_tokens(&a, &[ /// Token::Enum { name: "E" }, /// Token::Str("A"), /// Token::Unit, /// ]); /// /// let b = E::B(0); /// assert_tokens(&b, &[ /// Token::Enum { name: "E" }, /// Token::Str("B"), /// Token::U8(0), /// ]); /// /// let c = E::C(0, 0); /// assert_tokens(&c, &[ /// Token::Enum { name: "E" }, /// Token::Str("C"), /// Token::Seq { len: Some(2) }, /// Token::U8(0), /// Token::U8(0), /// Token::SeqEnd, /// ]); /// /// let d = E::D { d: 0 }; /// assert_tokens(&d, &[ /// Token::Enum { name: "E" }, /// Token::Str("D"), /// Token::Map { len: Some(1) }, /// Token::Str("d"), /// Token::U8(0), /// Token::MapEnd, /// ]); /// # } /// ``` Enum { name: &'static str }, } impl Display for Token { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(self, formatter) } } serde_test-1.0.102/.cargo_vcs_info.json0000644000000001121355540030300134240ustar00{ "git": { "sha1": "2ceabad360326a959800d14f6c5183e41b1d4c5b" } }