serde_test-1.0.177/.cargo_vcs_info.json0000644000000001360000000000100133520ustar { "git": { "sha1": "bbb18e2db032ec5da07e07368e4d55647cf10229" }, "path_in_vcs": "" }serde_test-1.0.177/.github/workflows/ci.yml000064400000000000000000000032631046102023000166610ustar 00000000000000name: CI on: push: pull_request: workflow_dispatch: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: test: name: Rust ${{matrix.rust}} runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [stable, beta, nightly, 1.56.0] timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - run: cargo build - run: cargo test --features serde/derive,serde/rc minimal: name: Minimal versions runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@nightly - run: cargo generate-lockfile -Z minimal-versions - run: cargo check --locked doc: name: Documentation runs-on: ubuntu-latest timeout-minutes: 45 env: RUSTDOCFLAGS: -Dwarnings steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly - uses: dtolnay/install@cargo-docs-rs - run: cargo docs-rs clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy -- -Dclippy::all -Dclippy::pedantic outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@stable - uses: dtolnay/install@cargo-outdated - run: cargo outdated --workspace --exit-code 1 serde_test-1.0.177/.gitignore000064400000000000000000000000241046102023000141260ustar 00000000000000/target /Cargo.lock serde_test-1.0.177/Cargo.toml0000644000000026410000000000100113530ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.56" name = "serde_test" version = "1.0.177" authors = [ "Erick Tryzelaar ", "David Tolnay ", ] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Token De/Serializer for testing De/Serialize implementations" documentation = "https://docs.rs/serde_test" readme = "README.md" keywords = [ "serde", "serialization", "testing", "dev-dependencies", ] categories = ["development-tools::testing"] license = "MIT OR Apache-2.0" repository = "https://github.com/serde-rs/test" [package.metadata.docs.rs] rustdoc-args = ["--generate-link-to-definition"] targets = ["x86_64-unknown-linux-gnu"] [lib] name = "serde_test" path = "src/lib.rs" doc-scrape-examples = false [dependencies.serde] version = "1.0.69" [dev-dependencies.serde] version = "1" features = ["rc"] [dev-dependencies.serde_derive] version = "1" serde_test-1.0.177/Cargo.toml.orig000064400000000000000000000013741046102023000150360ustar 00000000000000[package] name = "serde_test" version = "1.0.177" authors = ["Erick Tryzelaar ", "David Tolnay "] categories = ["development-tools::testing"] description = "Token De/Serializer for testing De/Serialize implementations" documentation = "https://docs.rs/serde_test" edition = "2021" keywords = ["serde", "serialization", "testing", "dev-dependencies"] license = "MIT OR Apache-2.0" repository = "https://github.com/serde-rs/test" rust-version = "1.56" [dependencies] serde = "1.0.69" [dev-dependencies] serde = { version = "1", features = ["rc"] } serde_derive = "1" [lib] doc-scrape-examples = false [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] serde_test-1.0.177/LICENSE-APACHE000064400000000000000000000227731046102023000141010ustar 00000000000000 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 serde_test-1.0.177/LICENSE-MIT000064400000000000000000000017771046102023000136120ustar 00000000000000Permission 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.177/README.md000064400000000000000000000047411046102023000134270ustar 00000000000000# serde\_test   [![Build Status]][actions] [![Latest Version]][crates.io] [Build Status]: https://img.shields.io/github/actions/workflow/status/serde-rs/test/ci.yml?branch=master [actions]: https://github.com/serde-rs/test/actions?query=branch%3Amaster [Latest Version]: https://img.shields.io/crates/v/serde_test.svg [crates.io]: https://crates.io/crates/serde\_test This crate provides a convenient concise way to write unit tests for implementations of [`Serialize`] and [`Deserialize`]. [`Serialize`]: serde::ser::Serialize [`Deserialize`]: serde::de::Deserialize 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`]: serde::ser::Serializer Here is an example from the [`linked-hash-map`] crate. [`linked-hash-map`]: https://github.com/contain-rs/linked-hash-map ```rust use linked_hash_map::LinkedHashMap; use serde_test::{assert_tokens, Token}; #[test] fn test_ser_de_empty() { let map = LinkedHashMap::::new(); assert_tokens( &map, &[ Token::Map { len: Some(0) }, Token::MapEnd, ], ); } #[test] 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, ], ); } ```
#### 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 this crate 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.177/src/assert.rs000064400000000000000000000137721046102023000146120ustar 00000000000000use crate::de::Deserializer; use crate::ser::Serializer; use crate::token::Token; use serde::{Deserialize, Serialize}; use std::fmt::Debug; /// Runs both `assert_ser_tokens` and `assert_de_tokens`. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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, /// ], /// ); /// ``` #[track_caller] 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`. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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, /// ], /// ); /// ``` #[track_caller] pub fn assert_ser_tokens(value: &T, tokens: &[Token]) where T: ?Sized + 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`. /// /// ``` /// use serde_derive::Serialize; /// use serde_test::{assert_ser_tokens_error, Token}; /// use std::sync::{Arc, Mutex}; /// use std::thread; /// /// #[derive(Serialize)] /// struct Example { /// lock: Arc>, /// } /// /// fn main() { /// let example = Example { /// lock: Arc::new(Mutex::new(0)), /// }; /// let lock = example.lock.clone(); /// /// let thread = 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!() /// }); /// thread.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); /// } /// ``` #[track_caller] pub fn assert_ser_tokens_error(value: &T, tokens: &[Token], error: &str) where T: ?Sized + 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`. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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, /// ], /// ); /// ``` #[track_caller] 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. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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`", /// ); /// ``` #[track_caller] 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.177/src/configure.rs000064400000000000000000000661461046102023000152750ustar 00000000000000use serde::de::{ Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, VariantAccess, Visitor, }; use serde::ser::{ Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, Serializer, }; use std::fmt::{self, Display}; #[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. /// /// ``` /// 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 where T: ?Sized {} impl Serialize for Readable where T: ?Sized + Serialize, { #[inline] fn serialize(&self, serializer: S) -> Result where S: Serializer, { self.0.serialize(Readable(serializer)) } } impl Serialize for Compact where T: ?Sized + 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) } fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> where D: Deserializer<'de>, { T::deserialize_in_place(Readable(deserializer), &mut place.0) } } 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) } fn deserialize_in_place(deserializer: D, place: &mut Self) -> Result<(), D::Error> where D: Deserializer<'de>, { T::deserialize_in_place(Compact(deserializer), &mut place.0) } } 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_i128 i128, serialize_u8 u8, serialize_u16 u16, serialize_u32 u32, serialize_u64 u64, serialize_u128 u128, 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: ?Sized + 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: ?Sized + 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: ?Sized + 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) } fn collect_seq(self, iter: I) -> Result where I: IntoIterator, ::Item: Serialize, { self.0 .collect_seq(iter.into_iter().map(|item| $wrapper(item))) } fn collect_map(self, iter: I) -> Result where K: Serialize, V: Serialize, I: IntoIterator, { self.0.collect_map( iter.into_iter() .map(|(key, value)| ($wrapper(key), $wrapper(value))), ) } fn collect_str(self, value: &T) -> Result where T: ?Sized + Display, { self.0.collect_str(value) } } 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: ?Sized + 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: ?Sized + 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: ?Sized + 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: ?Sized + 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: ?Sized + Serialize, { self.0.serialize_key(&$wrapper(key)) } fn serialize_value(&mut self, value: &T) -> Result<(), S::Error> where T: ?Sized + Serialize, { self.0.serialize_value(&$wrapper(value)) } fn serialize_entry(&mut self, key: &K, value: &V) -> Result<(), S::Error> where K: ?Sized + Serialize, V: ?Sized + Serialize, { self.0.serialize_entry(&$wrapper(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: ?Sized + Serialize, { self.0.serialize_field(name, &$wrapper(field)) } fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { self.0.skip_field(key) } 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: ?Sized + Serialize, { self.0.serialize_field(name, &$wrapper(field)) } fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { self.0.skip_field(key) } fn end(self) -> Result { self.0.end() } } }; } impl_serializer!(Readable, true); impl_serializer!(Compact, false); 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_u128, deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64, deserialize_i128, 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_i128(self, v: i128) -> Result where E: Error, { self.0.visit_i128(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_u128(self, v: u128) -> Result where E: Error, { self.0.visit_u128(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 next_entry_seed( &mut self, kseed: K, vseed: V, ) -> Result, D::Error> where K: DeserializeSeed<'de>, V: DeserializeSeed<'de>, { self.0.next_entry_seed($wrapper(kseed), $wrapper(vseed)) } 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.177/src/de.rs000064400000000000000000000513371046102023000137000ustar 00000000000000use crate::error::Error; use crate::token::Token; use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer}; use serde::de::{ self, Deserialize, DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor, }; use serde::forward_to_deserialize_any; #[derive(Debug)] pub struct Deserializer<'de> { tokens: &'de [Token], } fn assert_next_token(de: &mut Deserializer, expected: Token) -> Result<(), Error> { match de.next_token_opt() { Some(token) if token == expected => Ok(()), Some(other) => Err(de::Error::custom(format!( "expected Token::{} but deserialization wants Token::{}", other, expected, ))), None => Err(de::Error::custom(format!( "end of tokens but deserialization wants Token::{}", expected, ))), } } fn unexpected(token: Token) -> Error { de::Error::custom(format!( "deserialization did not expect this token: {}", token, )) } fn end_of_tokens() -> Error { de::Error::custom("ran out of tokens to deserialize") } impl<'de> Deserializer<'de> { pub fn new(tokens: &'de [Token]) -> Self { Deserializer { tokens } } fn peek_token_opt(&self) -> Option { self.tokens.first().copied() } fn peek_token(&self) -> Result { self.peek_token_opt().ok_or_else(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) -> Result { let (&first, rest) = self.tokens.split_first().ok_or_else(end_of_tokens)?; self.tokens = rest; Ok(first) } 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, 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, 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::BorrowedStr(variant), Token::Unit) => { self.next_token()?; visitor.visit_borrowed_str(variant) } (Token::String(variant), Token::Unit) => { self.next_token()?; visitor.visit_string(variant.to_string()) } (Token::Bytes(variant), Token::Unit) => { self.next_token()?; visitor.visit_bytes(variant) } (Token::BorrowedBytes(variant), Token::Unit) => { self.next_token()?; visitor.visit_borrowed_bytes(variant) } (Token::ByteBuf(variant), Token::Unit) => { self.next_token()?; visitor.visit_byte_buf(variant.to_vec()) } (Token::U8(variant), Token::Unit) => { self.next_token()?; visitor.visit_u8(variant) } (Token::U16(variant), Token::Unit) => { self.next_token()?; visitor.visit_u16(variant) } (Token::U32(variant), Token::Unit) => { self.next_token()?; visitor.visit_u32(variant) } (Token::U64(variant), Token::Unit) => { self.next_token()?; visitor.visit_u64(variant) } (variant, Token::Unit) => Err(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 => Err(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 }) } _ => self.deserialize_any(visitor), } } 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 })?; 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 })?; 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 })?; 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, 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, 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 { Err(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 { Err(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 { Err(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 { Err(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, variant: Some(variant), 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) => Err(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.177/src/error.rs000064400000000000000000000013661046102023000144360ustar 00000000000000use serde::{de, ser}; use std::error; use std::fmt::{self, Display}; #[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.177/src/lib.rs000064400000000000000000000115331046102023000140500ustar 00000000000000//! This crate provides a convenient concise way to write unit tests for //! implementations of [`Serialize`] and [`Deserialize`]. //! //! [`Serialize`]: serde::ser::Serialize //! [`Deserialize`]: serde::de::Deserialize //! //! 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`]: serde::ser::Serializer //! //! Here is an example from the [`linked-hash-map`] crate. //! //! [`linked-hash-map`]: https://github.com/contain-rs/linked-hash-map //! //! ``` //! # const IGNORE: &str = stringify! { //! use linked_hash_map::LinkedHashMap; //! # }; //! use serde_test::{assert_tokens, Token}; //! //! # 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.177")] // Ignored clippy lints #![allow(clippy::float_cmp, clippy::needless_doctest_main)] // Ignored clippy_pedantic lints #![allow( clippy::manual_assert, clippy::missing_panics_doc, clippy::module_name_repetitions, clippy::too_many_lines )] mod assert; mod configure; mod de; mod error; mod ser; mod token; pub use crate::assert::{ assert_de_tokens, assert_de_tokens_error, assert_ser_tokens, assert_ser_tokens_error, assert_tokens, }; pub use crate::configure::{Compact, Configure, Readable}; pub use crate::token::Token; serde_test-1.0.177/src/ser.rs000064400000000000000000000301601046102023000140700ustar 00000000000000use crate::error::Error; use crate::token::Token; use serde::ser::{self, Serialize}; /// 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 } } /// 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, $actual:ident) => {{ assert_next_token!($ser, stringify!($actual), Token::$actual, true); }}; ($ser:expr, $actual:ident($v:expr)) => {{ assert_next_token!( $ser, format_args!(concat!(stringify!($actual), "({:?})"), $v), Token::$actual(v), v == $v ); }}; ($ser:expr, $actual: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!($actual), " {{ {}}}"), field_format()), Token::$actual { $($k),* }, ($($k,)*) == compare ); }}; ($ser:expr, $actual:expr, $pat:pat, $guard:expr) => { match $ser.next_token() { Some($pat) if $guard => {} Some(expected) => return Err(ser::Error::custom( format!("expected Token::{} but serialized as {}", expected, $actual) )), None => return Err(ser::Error::custom( format!("expected end of tokens, but {} was serialized", $actual) )), } }; } 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 }) { 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: ?Sized + 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: ?Sized + Serialize, { if self.tokens.first() == Some(&Token::Enum { 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: ?Sized + 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 }) { 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 }) { 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: ?Sized + 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: ?Sized + 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: ?Sized + 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: ?Sized + 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: ?Sized + Serialize, { key.serialize(&mut **self) } fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> where T: ?Sized + 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: ?Sized + 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: ?Sized + 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.177/src/token.rs000064400000000000000000000322711046102023000144240ustar 00000000000000use std::fmt::{self, Debug, Display}; #[derive(Copy, Clone, PartialEq, Debug)] pub enum Token { /// A serialized `bool`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&true, &[Token::Bool(true)]); /// ``` Bool(bool), /// A serialized `i8`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0i8, &[Token::I8(0)]); /// ``` I8(i8), /// A serialized `i16`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0i16, &[Token::I16(0)]); /// ``` I16(i16), /// A serialized `i32`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0i32, &[Token::I32(0)]); /// ``` I32(i32), /// A serialized `i64`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0i64, &[Token::I64(0)]); /// ``` I64(i64), /// A serialized `u8`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0u8, &[Token::U8(0)]); /// ``` U8(u8), /// A serialized `u16`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0u16, &[Token::U16(0)]); /// ``` U16(u16), /// A serialized `u32`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0u32, &[Token::U32(0)]); /// ``` U32(u32), /// A serialized `u64`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0u64, &[Token::U64(0)]); /// ``` U64(u64), /// A serialized `f32`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0f32, &[Token::F32(0.0)]); /// ``` F32(f32), /// A serialized `f64`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&0f64, &[Token::F64(0.0)]); /// ``` F64(f64), /// A serialized `char`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&'\n', &[Token::Char('\n')]); /// ``` Char(char), /// A serialized `str`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// let s = String::from("transient"); /// assert_tokens(&s, &[Token::Str("transient")]); /// ``` Str(&'static str), /// A borrowed `str`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// let s: &str = "borrowed"; /// assert_tokens(&s, &[Token::BorrowedStr("borrowed")]); /// ``` BorrowedStr(&'static str), /// A serialized `String`. /// /// ``` /// # 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. /// /// ``` /// # 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. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// let opt = Some('c'); /// assert_tokens(&opt, &[Token::Some, Token::Char('c')]); /// ``` Some, /// A serialized `()`. /// /// ``` /// # use serde_test::{assert_tokens, Token}; /// # /// assert_tokens(&(), &[Token::Unit]); /// ``` Unit, /// A serialized unit struct of the given name. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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`. /// /// ``` /// # 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`. /// /// ``` /// # 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`. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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`. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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`. /// /// ``` /// # 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`. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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`. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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. /// /// ``` /// # use serde_derive::{Deserialize, Serialize}; /// # 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) } }