serde-untagged-0.1.1/.cargo_vcs_info.json0000644000000001360000000000100137310ustar { "git": { "sha1": "49c1db8b96f1ca540f3cf295848cb88faf22c879" }, "path_in_vcs": "" }serde-untagged-0.1.1/.github/workflows/ci.yml000064400000000000000000000044051046102023000172370ustar 00000000000000name: CI on: push: pull_request: workflow_dispatch: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: pre_ci: uses: dtolnay/.github/.github/workflows/pre_ci.yml@master test: name: Rust ${{matrix.rust}} needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.65.0] timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - name: Enable type layout randomization run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV if: matrix.rust == 'nightly' - run: cargo test msrv: name: Rust 1.56.0 needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@1.56.0 - run: cargo check --manifest-path tests/crate/Cargo.toml minimal: name: Minimal versions needs: pre_ci if: needs.pre_ci.outputs.continue 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 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 --tests -- -Dclippy::all -Dclippy::pedantic miri: name: Miri needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@miri - run: cargo miri setup - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v3 - uses: dtolnay/install@cargo-outdated - run: cargo outdated --workspace --exit-code 1 serde-untagged-0.1.1/.gitignore000064400000000000000000000000241046102023000145050ustar 00000000000000/target /Cargo.lock serde-untagged-0.1.1/Cargo.toml0000644000000025610000000000100117330ustar # 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-untagged" version = "0.1.1" authors = ["David Tolnay "] description = "Serde `Visitor` implementation for deserializing untagged enums" documentation = "https://docs.rs/serde-untagged" readme = "README.md" keywords = [ "serde", "untagged", ] categories = [ "encoding", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/serde-untagged" [package.metadata.docs.rs] rustdoc-args = ["--generate-link-to-definition"] targets = ["x86_64-unknown-linux-gnu"] [lib] doc-scrape-examples = false [dependencies.erased-serde] version = "0.3.30" features = ["alloc"] default-features = false [dependencies.serde] version = "1" features = ["alloc"] default-features = false [dev-dependencies.serde_derive] version = "1" [dev-dependencies.serde_json] version = "1" [dev-dependencies.toml] version = "0.7" serde-untagged-0.1.1/Cargo.toml.orig000064400000000000000000000014631046102023000154140ustar 00000000000000[package] name = "serde-untagged" version = "0.1.1" authors = ["David Tolnay "] categories = ["encoding", "no-std"] description = "Serde `Visitor` implementation for deserializing untagged enums" documentation = "https://docs.rs/serde-untagged" edition = "2021" keywords = ["serde", "untagged"] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/serde-untagged" rust-version = "1.56" [dependencies] erased-serde = { version = "0.3.30", default-features = false, features = ["alloc"] } serde = { version = "1", default-features = false, features = ["alloc"] } [dev-dependencies] serde_derive = "1" serde_json = "1" toml = "0.7" [lib] doc-scrape-examples = false [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] serde-untagged-0.1.1/LICENSE-APACHE000064400000000000000000000227731046102023000144600ustar 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-untagged-0.1.1/LICENSE-MIT000064400000000000000000000017771046102023000141710ustar 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-untagged-0.1.1/README.md000064400000000000000000000125071046102023000140050ustar 00000000000000serde-untagged ============== [github](https://github.com/dtolnay/serde-untagged) [crates.io](https://crates.io/crates/serde-untagged) [docs.rs](https://docs.rs/serde-untagged) [build status](https://github.com/dtolnay/serde-untagged/actions?query=branch%3Amaster) This crate provides a Serde `Visitor` implementation that is useful for deserializing untagged enums. ```toml [dependencies] serde-untagged = "0.1" ```
Untagged enum `Deserialize` impls look like this: ```rust use serde::de::{Deserialize, Deserializer}; use serde_untagged::UntaggedEnumVisitor; impl<'de> Deserialize<'de> for $MyType { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { UntaggedEnumVisitor::new() /* * */ .deserialize(deserializer) } } ``` Inside the `/* ... */`, we list each type that the untagged enum needs to support deserializing from, giving a closure that turns the input into $MyType. The following types are supported: - bool - i8, i16, i32, i64, i128, u8, u16, u32, u64, u128 - f32 - f64 - char - string - borrowed\_str - bytes - borrowed\_bytes - byte\_buf - unit - seq - map ### Example: string or struct Cargo's `http.ssl-version` configuration supports deserialization from the following two representations: ```toml [http] ssl-version = "tlsv1.3" ``` ```toml [http] ssl-version.min = "tlsv1.2" ssl-version.max = "tlsv1.3" ``` ```rust use serde::de::{Deserialize, Deserializer}; use serde_derive::Deserialize; use serde_untagged::UntaggedEnumVisitor; pub enum SslVersionConfig { Single(String), Range(SslVersionConfigRange), } impl<'de> Deserialize<'de> for SslVersionConfig { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { UntaggedEnumVisitor::new() .string(|single| Ok(SslVersionConfig::Single(single.to_owned()))) .map(|map| map.deserialize().map(SslVersionConfig::Range)) .deserialize(deserializer) } } #[derive(Deserialize)] pub struct SslVersionConfigRange { pub min: Option, pub max: Option, } ``` ### Example: unit variant or bool Cargo's LTO setting in profiles supports the 5 values `false`, `true`, `"fat"`, `"thin"`, and `"off"`. ```toml [profile.release] lto = "thin" ``` ```rust use serde::de::{Deserialize, Deserializer, IntoDeserializer}; use serde_derive::Deserialize; use serde_untagged::UntaggedEnumVisitor; pub enum LinkTimeOptimization { Enabled(bool), Enum(LinkTimeOptimizationString), } impl<'de> Deserialize<'de> for LinkTimeOptimization { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { UntaggedEnumVisitor::new() .bool(|b| Ok(LinkTimeOptimization::Enabled(b))) .string(|string| { let de = string.into_deserializer(); LinkTimeOptimizationString::deserialize(de).map(LinkTimeOptimization::Enum) }) .deserialize(deserializer) } } #[derive(Deserialize)] #[serde(rename = "lowercase")] pub enum LinkTimeOptimizationString { Fat, Thin, Off, } ``` Since `lto = true` means the same thing as `lto = "fat"` to Cargo, there are really only 4 distinct options. This type could be implemented alternatively as: ```rust use serde::de::{Deserialize, Deserializer, Unexpected}; use serde_untagged::UntaggedEnumVisitor; pub enum LinkTimeOptimization { ThinLocal, // false Fat, // true or "fat" Thin, // "thin" Off, // "off" } impl<'de> Deserialize<'de> for LinkTimeOptimization { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { UntaggedEnumVisitor::new() .bool(|b| match b { false => Ok(LinkTimeOptimization::ThinLocal), true => Ok(LinkTimeOptimization::Fat), }) .string(|string| match string { "fat" => Ok(LinkTimeOptimization::Fat), "thin" => Ok(LinkTimeOptimization::Thin), "off" => Ok(LinkTimeOptimization::Off), _ => Err(serde::de::Error::invalid_value( Unexpected::Str(string), &r#""fat" or "thin" or "off""#, )), }) .deserialize(deserializer) } } ```
#### 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-untagged-0.1.1/src/any.rs000064400000000000000000000037151046102023000144530ustar 00000000000000use alloc::boxed::Box; #[cfg(any(debug_assertions, miri))] use core::any::{self, TypeId}; #[cfg(any(debug_assertions, miri))] use core::marker::PhantomData; use core::mem; pub(crate) struct ErasedValue { ptr: *mut (), drop: unsafe fn(*mut ()), #[cfg(any(debug_assertions, miri))] type_id: TypeId, #[cfg(any(debug_assertions, miri))] type_name: &'static str, } impl ErasedValue { pub(crate) unsafe fn new(value: T) -> Self { ErasedValue { ptr: Box::into_raw(Box::new(value)).cast(), drop: { unsafe fn drop(ptr: *mut ()) { let _ = Box::from_raw(ptr.cast::()); } drop:: }, #[cfg(any(debug_assertions, miri))] type_id: non_static_type_id::(), #[cfg(any(debug_assertions, miri))] type_name: any::type_name::(), } } pub(crate) unsafe fn take(self) -> T { #[cfg(any(debug_assertions, miri))] assert_eq!( self.type_id, non_static_type_id::(), "ErasedValue mismatch: {} vs {}", self.type_name, any::type_name::(), ); let b = Box::from_raw(self.ptr.cast::()); mem::forget(self); *b } } impl Drop for ErasedValue { fn drop(&mut self) { unsafe { (self.drop)(self.ptr) } } } #[cfg(any(debug_assertions, miri))] fn non_static_type_id() -> TypeId { trait NonStaticAny { fn get_type_id(&self) -> TypeId where Self: 'static; } impl NonStaticAny for PhantomData { fn get_type_id(&self) -> TypeId where Self: 'static, { TypeId::of::() } } let phantom_data = PhantomData::; NonStaticAny::get_type_id(unsafe { mem::transmute::<&dyn NonStaticAny, &(dyn NonStaticAny + 'static)>(&phantom_data) }) } serde-untagged-0.1.1/src/error.rs000064400000000000000000000157561046102023000150250ustar 00000000000000use alloc::borrow::ToOwned; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt::{self, Debug, Display}; use serde::de::Expected; pub struct Error { imp: ErrorImpl, } pub(crate) fn convert(err: Error) -> E { err.as_serde() } impl serde::de::StdError for Error {} impl Display for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let error = self.as_serde::(); Display::fmt(&error, formatter) } } impl Debug for Error { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let error = self.as_serde::(); Debug::fmt(&error, formatter) } } enum ErrorImpl { Custom(String), InvalidType { unexpected: Unexpected, expected: String, }, InvalidValue { unexpected: Unexpected, expected: String, }, InvalidLength { len: usize, expected: String, }, UnknownVariant { variant: String, expected: &'static [&'static str], }, UnknownField { field: String, expected: &'static [&'static str], }, MissingField { field: &'static str, }, DuplicateField { field: &'static str, }, } enum Unexpected { Bool(bool), Unsigned(u64), Signed(i64), Float(f64), Char(char), Str(String), Bytes(Vec), Unit, Option, NewtypeStruct, Seq, Map, Enum, UnitVariant, NewtypeVariant, TupleVariant, StructVariant, Other(String), } impl serde::de::Error for Error { fn custom(msg: T) -> Self { let imp = ErrorImpl::Custom(msg.to_string()); Error { imp } } fn invalid_type(unexpected: serde::de::Unexpected, expected: &dyn Expected) -> Self { let imp = ErrorImpl::InvalidType { unexpected: Unexpected::from_serde(unexpected), expected: expected.to_string(), }; Error { imp } } fn invalid_value(unexpected: serde::de::Unexpected, expected: &dyn Expected) -> Self { let imp = ErrorImpl::InvalidValue { unexpected: Unexpected::from_serde(unexpected), expected: expected.to_string(), }; Error { imp } } fn invalid_length(len: usize, expected: &dyn Expected) -> Self { let imp = ErrorImpl::InvalidLength { len, expected: expected.to_string(), }; Error { imp } } fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self { let imp = ErrorImpl::UnknownVariant { variant: variant.to_owned(), expected, }; Error { imp } } fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self { let imp = ErrorImpl::UnknownField { field: field.to_owned(), expected, }; Error { imp } } fn missing_field(field: &'static str) -> Self { let imp = ErrorImpl::MissingField { field }; Error { imp } } fn duplicate_field(field: &'static str) -> Self { let imp = ErrorImpl::DuplicateField { field }; Error { imp } } } impl Error { fn as_serde(&self) -> E { match &self.imp { ErrorImpl::Custom(msg) => E::custom(msg), ErrorImpl::InvalidType { unexpected, expected, } => E::invalid_type(unexpected.as_serde(), &expected.as_str()), ErrorImpl::InvalidValue { unexpected, expected, } => E::invalid_value(unexpected.as_serde(), &expected.as_str()), ErrorImpl::InvalidLength { len, expected } => { E::invalid_length(*len, &expected.as_str()) } ErrorImpl::UnknownVariant { variant, expected } => { E::unknown_variant(variant, expected) } ErrorImpl::UnknownField { field, expected } => E::unknown_field(field, expected), ErrorImpl::MissingField { field } => E::missing_field(field), ErrorImpl::DuplicateField { field } => E::duplicate_field(field), } } } impl Unexpected { fn from_serde(unexpected: serde::de::Unexpected) -> Self { match unexpected { serde::de::Unexpected::Bool(value) => Unexpected::Bool(value), serde::de::Unexpected::Unsigned(value) => Unexpected::Unsigned(value), serde::de::Unexpected::Signed(value) => Unexpected::Signed(value), serde::de::Unexpected::Float(value) => Unexpected::Float(value), serde::de::Unexpected::Char(value) => Unexpected::Char(value), serde::de::Unexpected::Str(value) => Unexpected::Str(value.to_owned()), serde::de::Unexpected::Bytes(value) => Unexpected::Bytes(value.to_owned()), serde::de::Unexpected::Unit => Unexpected::Unit, serde::de::Unexpected::Option => Unexpected::Option, serde::de::Unexpected::NewtypeStruct => Unexpected::NewtypeStruct, serde::de::Unexpected::Seq => Unexpected::Seq, serde::de::Unexpected::Map => Unexpected::Map, serde::de::Unexpected::Enum => Unexpected::Enum, serde::de::Unexpected::UnitVariant => Unexpected::UnitVariant, serde::de::Unexpected::NewtypeVariant => Unexpected::NewtypeVariant, serde::de::Unexpected::TupleVariant => Unexpected::TupleVariant, serde::de::Unexpected::StructVariant => Unexpected::StructVariant, serde::de::Unexpected::Other(msg) => Unexpected::Other(msg.to_owned()), } } fn as_serde(&self) -> serde::de::Unexpected { match self { Unexpected::Bool(value) => serde::de::Unexpected::Bool(*value), Unexpected::Unsigned(value) => serde::de::Unexpected::Unsigned(*value), Unexpected::Signed(value) => serde::de::Unexpected::Signed(*value), Unexpected::Float(value) => serde::de::Unexpected::Float(*value), Unexpected::Char(value) => serde::de::Unexpected::Char(*value), Unexpected::Str(value) => serde::de::Unexpected::Str(value), Unexpected::Bytes(value) => serde::de::Unexpected::Bytes(value), Unexpected::Unit => serde::de::Unexpected::Unit, Unexpected::Option => serde::de::Unexpected::Option, Unexpected::NewtypeStruct => serde::de::Unexpected::NewtypeStruct, Unexpected::Seq => serde::de::Unexpected::Seq, Unexpected::Map => serde::de::Unexpected::Map, Unexpected::Enum => serde::de::Unexpected::Enum, Unexpected::UnitVariant => serde::de::Unexpected::UnitVariant, Unexpected::NewtypeVariant => serde::de::Unexpected::NewtypeVariant, Unexpected::TupleVariant => serde::de::Unexpected::TupleVariant, Unexpected::StructVariant => serde::de::Unexpected::StructVariant, Unexpected::Other(msg) => serde::de::Unexpected::Other(msg), } } } serde-untagged-0.1.1/src/int.rs000064400000000000000000000113551046102023000144550ustar 00000000000000use crate::error; use crate::UntaggedEnumVisitor; use serde::de::{Unexpected, Visitor}; pub(crate) enum IntKind { I8, I16, I32, I64, I128, U8, U16, U32, U64, U128, } pub(crate) trait Integer: Copy + TryInto + TryInto + TryInto + TryInto + TryInto + TryInto + TryInto + TryInto + TryInto + TryInto { } impl Integer for T where T: Copy, i8: TryFrom, i16: TryFrom, i32: TryFrom, i64: TryFrom, i128: TryFrom, u8: TryFrom, u16: TryFrom, u32: TryFrom, u64: TryFrom, u128: TryFrom, { } impl<'closure, 'de, Value> UntaggedEnumVisitor<'closure, 'de, Value> { pub(crate) fn dispatch_integer( self, value: I, precedence: [IntKind; 10], ) -> Result where I: Integer, E: serde::de::Error, { for kind in precedence { match kind { IntKind::I8 => { if let Some(int) = i8::int_from(value) { if let Some(visit_i8) = self.visit_i8 { return visit_i8(int).map_err(error::convert); } } } IntKind::I16 => { if let Some(int) = i16::int_from(value) { if let Some(visit_i16) = self.visit_i16 { return visit_i16(int).map_err(error::convert); } } } IntKind::I32 => { if let Some(int) = i32::int_from(value) { if let Some(visit_i32) = self.visit_i32 { return visit_i32(int).map_err(error::convert); } } } IntKind::I64 => { if let Some(int) = i64::int_from(value) { if let Some(visit_i64) = self.visit_i64 { return visit_i64(int).map_err(error::convert); } } } IntKind::I128 => { if let Some(int) = i128::int_from(value) { if let Some(visit_i128) = self.visit_i128 { return visit_i128(int).map_err(error::convert); } } } IntKind::U8 => { if let Some(int) = u8::int_from(value) { if let Some(visit_u8) = self.visit_u8 { return visit_u8(int).map_err(error::convert); } } } IntKind::U16 => { if let Some(int) = u16::int_from(value) { if let Some(visit_u16) = self.visit_u16 { return visit_u16(int).map_err(error::convert); } } } IntKind::U32 => { if let Some(int) = u32::int_from(value) { if let Some(visit_u32) = self.visit_u32 { return visit_u32(int).map_err(error::convert); } } } IntKind::U64 => { if let Some(int) = u64::int_from(value) { if let Some(visit_u64) = self.visit_u64 { return visit_u64(int).map_err(error::convert); } } } IntKind::U128 => { if let Some(int) = u128::int_from(value) { if let Some(visit_u128) = self.visit_u128 { return visit_u128(int).map_err(error::convert); } } } } } if let Some(int) = u64::int_from(value) { return Err(E::invalid_type(Unexpected::Unsigned(int), &self)); } if let Some(int) = i64::int_from(value) { return Err(E::invalid_type(Unexpected::Signed(int), &self)); } if let Some(int) = u128::int_from(value) { return crate::DefaultVisitor::new(&self).visit_u128(int); } if let Some(int) = i128::int_from(value) { return crate::DefaultVisitor::new(&self).visit_i128(int); } unreachable!() } } trait IntFrom: Sized { fn int_from(int: I) -> Option; } impl IntFrom for T where I: TryInto, { fn int_from(int: I) -> Option { int.try_into().ok() } } serde-untagged-0.1.1/src/lib.rs000064400000000000000000000722151046102023000144330ustar 00000000000000//! [![github]](https://github.com/dtolnay/serde-untagged) [![crates-io]](https://crates.io/crates/serde-untagged) [![docs-rs]](https://docs.rs/serde-untagged) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! This crate provides a Serde `Visitor` implementation that is useful for //! deserializing untagged enums. //! //! Untagged enum `Deserialize` impls look like this: //! //! ``` //! use serde::de::{Deserialize, Deserializer}; //! use serde_untagged::UntaggedEnumVisitor; //! //! # macro_rules! impl_deserialize { //! # ($MyType:ty) => { //! impl<'de> Deserialize<'de> for $MyType { //! fn deserialize(deserializer: D) -> Result //! where //! D: Deserializer<'de>, //! { //! UntaggedEnumVisitor::new() //! /* //! * //! */ //! .deserialize(deserializer) //! } //! } //! # }; //! # } //! # //! # struct MyType; //! # impl_deserialize!(MyType); //! ``` //! //! Inside the `/* ... */`, we list each type that the untagged enum needs to //! support deserializing from, giving a closure that turns the input into //! $MyType. The following types are supported: //! //! - bool //! - i8, i16, i32, i64, i128, u8, u16, u32, u64, u128 //! - f32 //! - f64 //! - char //! - string //! - borrowed\_str //! - bytes //! - borrowed\_bytes //! - byte\_buf //! - unit //! - seq //! - map //! //! # Example: string or struct //! //! Cargo's `http.ssl-version` configuration supports deserialization from the //! following two representations: //! //! ```toml //! [http] //! ssl-version = "tlsv1.3" //! ``` //! //! ```toml //! [http] //! ssl-version.min = "tlsv1.2" //! ssl-version.max = "tlsv1.3" //! ``` //! //! ``` //! use serde::de::{Deserialize, Deserializer}; //! use serde_derive::Deserialize; //! use serde_untagged::UntaggedEnumVisitor; //! //! pub enum SslVersionConfig { //! Single(String), //! Range(SslVersionConfigRange), //! } //! //! impl<'de> Deserialize<'de> for SslVersionConfig { //! fn deserialize(deserializer: D) -> Result //! where //! D: Deserializer<'de>, //! { //! UntaggedEnumVisitor::new() //! .string(|single| Ok(SslVersionConfig::Single(single.to_owned()))) //! .map(|map| map.deserialize().map(SslVersionConfig::Range)) //! .deserialize(deserializer) //! } //! } //! //! #[derive(Deserialize)] //! pub struct SslVersionConfigRange { //! pub min: Option, //! pub max: Option, //! } //! ``` //! //! # Example: unit variant or bool //! //! Cargo's LTO setting in profiles supports the 5 values `false`, `true`, //! `"fat"`, `"thin"`, and `"off"`. //! //! ```toml //! [profile.release] //! lto = "thin" //! ``` //! //! ``` //! use serde::de::{Deserialize, Deserializer, IntoDeserializer}; //! use serde_derive::Deserialize; //! use serde_untagged::UntaggedEnumVisitor; //! //! pub enum LinkTimeOptimization { //! Enabled(bool), //! Enum(LinkTimeOptimizationString), //! } //! //! impl<'de> Deserialize<'de> for LinkTimeOptimization { //! fn deserialize(deserializer: D) -> Result //! where //! D: Deserializer<'de>, //! { //! UntaggedEnumVisitor::new() //! .bool(|b| Ok(LinkTimeOptimization::Enabled(b))) //! .string(|string| { //! let de = string.into_deserializer(); //! LinkTimeOptimizationString::deserialize(de).map(LinkTimeOptimization::Enum) //! }) //! .deserialize(deserializer) //! } //! } //! //! #[derive(Deserialize)] //! #[serde(rename = "lowercase")] //! pub enum LinkTimeOptimizationString { //! Fat, //! Thin, //! Off, //! } //! ``` //! //! Since `lto = true` means the same thing as `lto = "fat"` to Cargo, there are //! really only 4 distinct options. This type could be implemented alternatively //! as: //! //! ``` //! use serde::de::{Deserialize, Deserializer, Unexpected}; //! use serde_untagged::UntaggedEnumVisitor; //! //! pub enum LinkTimeOptimization { //! ThinLocal, // false //! Fat, // true or "fat" //! Thin, // "thin" //! Off, // "off" //! } //! //! impl<'de> Deserialize<'de> for LinkTimeOptimization { //! fn deserialize(deserializer: D) -> Result //! where //! D: Deserializer<'de>, //! { //! UntaggedEnumVisitor::new() //! .bool(|b| match b { //! false => Ok(LinkTimeOptimization::ThinLocal), //! true => Ok(LinkTimeOptimization::Fat), //! }) //! .string(|string| match string { //! "fat" => Ok(LinkTimeOptimization::Fat), //! "thin" => Ok(LinkTimeOptimization::Thin), //! "off" => Ok(LinkTimeOptimization::Off), //! _ => Err(serde::de::Error::invalid_value( //! Unexpected::Str(string), //! &r#""fat" or "thin" or "off""#, //! )), //! }) //! .deserialize(deserializer) //! } //! } //! ``` #![no_std] #![doc(html_root_url = "https://docs.rs/serde-untagged/0.1.1")] #![allow( clippy::doc_markdown, clippy::enum_glob_use, clippy::manual_assert, clippy::manual_map, clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::must_use_candidate, clippy::needless_pass_by_value, clippy::new_without_default, clippy::type_complexity )] extern crate alloc; mod any; mod error; mod int; mod map; mod seed; mod seq; use crate::error::Error; use crate::map::Map; use crate::seq::Seq; use alloc::boxed::Box; use alloc::vec::Vec; use core::fmt::{self, Display}; use core::marker::PhantomData; use serde::de::{Deserializer, Expected, MapAccess, SeqAccess, Unexpected, Visitor}; pub mod de { pub use crate::error::Error; pub use crate::map::Map; pub use crate::seq::Seq; } pub struct UntaggedEnumVisitor<'closure, 'de, Value> { expecting: Option>, visit_bool: Option Result + 'closure>>, visit_i8: Option Result + 'closure>>, visit_i16: Option Result + 'closure>>, visit_i32: Option Result + 'closure>>, visit_i64: Option Result + 'closure>>, visit_i128: Option Result + 'closure>>, visit_u8: Option Result + 'closure>>, visit_u16: Option Result + 'closure>>, visit_u32: Option Result + 'closure>>, visit_u64: Option Result + 'closure>>, visit_u128: Option Result + 'closure>>, visit_f32: Option Result + 'closure>>, visit_f64: Option Result + 'closure>>, visit_char: Option Result + 'closure>>, visit_str: Option Result + 'closure>>, visit_borrowed_str: Option Result + 'closure>>, visit_bytes: Option Result + 'closure>>, visit_borrowed_bytes: Option Result + 'closure>>, visit_byte_buf: Option) -> Result + 'closure>>, visit_unit: Option Result + 'closure>>, visit_seq: Option FnOnce(Seq<'access, 'de>) -> Result + 'closure>>, visit_map: Option FnOnce(Map<'access, 'de>) -> Result + 'closure>>, } impl<'closure, 'de, Value> UntaggedEnumVisitor<'closure, 'de, Value> { pub fn new() -> Self { UntaggedEnumVisitor { expecting: None, visit_bool: None, visit_i8: None, visit_i16: None, visit_i32: None, visit_i64: None, visit_i128: None, visit_u8: None, visit_u16: None, visit_u32: None, visit_u64: None, visit_u128: None, visit_f32: None, visit_f64: None, visit_char: None, visit_str: None, visit_borrowed_str: None, visit_bytes: None, visit_borrowed_bytes: None, visit_byte_buf: None, visit_unit: None, visit_seq: None, visit_map: None, } } /// Provide a message stating what data this untagged enum expects to /// receive. /// /// This is used in error messages when deserialization fails. The message /// should complete the sentence _"This Visitor expects to receive …"_, for /// example the message could be _"an integer, or map containing the keys /// 'min' and 'max'"_. The message should not be capitalized and should not /// end with a period. /// /// ``` /// # use serde::de::Deserializer; /// # use serde_untagged::UntaggedEnumVisitor; /// # /// # fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error> /// # where /// # D: Deserializer<'de>, /// # { /// # let max = 1; /// UntaggedEnumVisitor::new() /// .expecting(format_args!("a string or number between 0 and {max}")) /// /* ... */ /// .deserialize(deserializer) /// # } /// ``` /// /// If `expecting` is not called, then `UntaggedEnumVisitor` constructs a /// default message based on the set of closures given to it. /// /// ``` /// # use serde::de::Deserializer; /// # use serde_untagged::UntaggedEnumVisitor; /// # /// # macro_rules! methods { /// # ($($construct:ident)::*() $(.$name:ident(|$arg:ident| ...))*) => { /// # $($construct)::*() /// # $( /// # .$name(|$arg| unimplemented!()) /// # )* /// # }; /// # } /// # /// # fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error> /// # where /// # D: Deserializer<'de>, /// # { /// # methods!( /// // by default, this enum expects "a boolean, string, or map" /// UntaggedEnumVisitor::new() /// .bool(|b| ...) /// .string(|s| ...) /// .map(|m| ...) /// # ) /// .deserialize(deserializer) /// # } /// ``` #[must_use] pub fn expecting(mut self, expecting: impl Display + 'closure) -> Self { if self.expecting.is_some() { panic!("UntaggedEnumVisitor::expecting already set"); } self.expecting = Some(Box::new(expecting)); self } #[must_use] pub fn bool(mut self, visit: impl FnOnce(bool) -> Result + 'closure) -> Self { if self.visit_bool.is_some() { panic!("UntaggedEnumVisitor::bool already set"); } self.visit_bool = Some(Box::new(visit)); self } #[must_use] pub fn i8(mut self, visit: impl FnOnce(i8) -> Result + 'closure) -> Self { if self.visit_i8.is_some() { panic!("UntaggedEnumVisitor::i8 already set"); } self.visit_i8 = Some(Box::new(visit)); self } #[must_use] pub fn i16(mut self, visit: impl FnOnce(i16) -> Result + 'closure) -> Self { if self.visit_i16.is_some() { panic!("UntaggedEnumVisitor::i16 already set"); } self.visit_i16 = Some(Box::new(visit)); self } #[must_use] pub fn i32(mut self, visit: impl FnOnce(i32) -> Result + 'closure) -> Self { if self.visit_i32.is_some() { panic!("UntaggedEnumVisitor::i32 already set"); } self.visit_i32 = Some(Box::new(visit)); self } #[must_use] pub fn i64(mut self, visit: impl FnOnce(i64) -> Result + 'closure) -> Self { if self.visit_i64.is_some() { panic!("UntaggedEnumVisitor::i64 already set"); } self.visit_i64 = Some(Box::new(visit)); self } #[must_use] pub fn i128(mut self, visit: impl FnOnce(i128) -> Result + 'closure) -> Self { if self.visit_i128.is_some() { panic!("UntaggedEnumVisitor::i128 already set"); } self.visit_i128 = Some(Box::new(visit)); self } #[must_use] pub fn u8(mut self, visit: impl FnOnce(u8) -> Result + 'closure) -> Self { if self.visit_u8.is_some() { panic!("UntaggedEnumVisitor::u8 already set"); } self.visit_u8 = Some(Box::new(visit)); self } #[must_use] pub fn u16(mut self, visit: impl FnOnce(u16) -> Result + 'closure) -> Self { if self.visit_u16.is_some() { panic!("UntaggedEnumVisitor::u16 already set"); } self.visit_u16 = Some(Box::new(visit)); self } #[must_use] pub fn u32(mut self, visit: impl FnOnce(u32) -> Result + 'closure) -> Self { if self.visit_u32.is_some() { panic!("UntaggedEnumVisitor::u32 already set"); } self.visit_u32 = Some(Box::new(visit)); self } #[must_use] pub fn u64(mut self, visit: impl FnOnce(u64) -> Result + 'closure) -> Self { if self.visit_u64.is_some() { panic!("UntaggedEnumVisitor::u64 already set"); } self.visit_u64 = Some(Box::new(visit)); self } #[must_use] pub fn u128(mut self, visit: impl FnOnce(u128) -> Result + 'closure) -> Self { if self.visit_u128.is_some() { panic!("UntaggedEnumVisitor::u128 already set"); } self.visit_u128 = Some(Box::new(visit)); self } #[must_use] pub fn f32(mut self, visit: impl FnOnce(f32) -> Result + 'closure) -> Self { if self.visit_f32.is_some() { panic!("UntaggedEnumVisitor::f32 already set"); } self.visit_f32 = Some(Box::new(visit)); self } #[must_use] pub fn f64(mut self, visit: impl FnOnce(f64) -> Result + 'closure) -> Self { if self.visit_f64.is_some() { panic!("UntaggedEnumVisitor::f64 already set"); } self.visit_f64 = Some(Box::new(visit)); self } #[must_use] pub fn char(mut self, visit: impl FnOnce(char) -> Result + 'closure) -> Self { if self.visit_char.is_some() { panic!("UntaggedEnumVisitor::char already set"); } self.visit_char = Some(Box::new(visit)); self } #[must_use] pub fn string(mut self, visit: impl FnOnce(&str) -> Result + 'closure) -> Self { if self.visit_str.is_some() { panic!("UntaggedEnumVisitor::string already set"); } self.visit_str = Some(Box::new(visit)); self } #[must_use] pub fn borrowed_str( mut self, visit: impl FnOnce(&'de str) -> Result + 'closure, ) -> Self { if self.visit_borrowed_str.is_some() { panic!("UntaggedEnumVisitor::borrowed_str already set"); } self.visit_borrowed_str = Some(Box::new(visit)); self } #[must_use] pub fn bytes(mut self, visit: impl FnOnce(&[u8]) -> Result + 'closure) -> Self { if self.visit_bytes.is_some() { panic!("UntaggedEnumVisitor::bytes already set"); } self.visit_bytes = Some(Box::new(visit)); self } #[must_use] pub fn borrowed_bytes( mut self, visit: impl FnOnce(&'de [u8]) -> Result + 'closure, ) -> Self { if self.visit_borrowed_bytes.is_some() { panic!("UntaggedEnumVisitor::borrowed_bytes already set"); } self.visit_borrowed_bytes = Some(Box::new(visit)); self } #[must_use] pub fn byte_buf( mut self, visit: impl FnOnce(Vec) -> Result + 'closure, ) -> Self { if self.visit_byte_buf.is_some() { panic!("UntaggedEnumVisitor::byte_buf already set"); } self.visit_byte_buf = Some(Box::new(visit)); self } #[must_use] pub fn unit(mut self, visit: impl FnOnce() -> Result + 'closure) -> Self { if self.visit_unit.is_some() { panic!("UntaggedEnumVisitor::unit already set"); } self.visit_unit = Some(Box::new(visit)); self } /// Deserialize a sequence. The argument implements /// [`serde::de::SeqAccess`]. #[must_use] pub fn seq( mut self, visit: impl for<'access> FnOnce(Seq<'access, 'de>) -> Result + 'closure, ) -> Self { if self.visit_seq.is_some() { panic!("UntaggedEnumVisitor::seq already set"); } self.visit_seq = Some(Box::new(visit)); self } /// Deserialize a key-value map. The argument implements /// [`serde::de::MapAccess`]. /// /// ``` /// # use serde::de::Deserializer; /// use serde::de::MapAccess; /// use serde_untagged::UntaggedEnumVisitor; /// use std::collections::HashMap; /// /// # fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> /// # where /// # D: Deserializer<'de>, /// # { /// UntaggedEnumVisitor::new() /// .map(|mut map| { /// let mut hashmap = HashMap::new(); /// while let Some(key) = map.next_key()? { /// let value = map.next_value()?; /// hashmap.insert(key, value); /// } /// Ok(hashmap) /// }) /// .deserialize(deserializer) /// # } /// ``` /// /// If you need to inspect the contents of the map to decide how to /// deserialize, you can buffer it into some kind of `Value` and deserialize /// from there. /// /// ``` /// # use serde::de::{Deserialize, Deserializer}; /// # use serde_untagged::UntaggedEnumVisitor; /// # /// enum Response { /// // {"failure":"..."} /// Failure(String), /// // Anything else. {"ok":200} /// Success(serde_json::Value), /// } /// /// impl<'de> Deserialize<'de> for Response { /// fn deserialize(deserializer: D) -> Result /// where /// D: Deserializer<'de>, /// { /// UntaggedEnumVisitor::new() /// .map(|map| { /// let value: serde_json::Value = map.deserialize()?; /// if let Some(failure) = value["failure"].as_str() { /// Ok(Response::Failure(failure.to_owned())) /// } else { /// Ok(Response::Success(value)) /// } /// }) /// .deserialize(deserializer) /// } /// } /// ``` #[must_use] pub fn map( mut self, visit: impl for<'access> FnOnce(Map<'access, 'de>) -> Result + 'closure, ) -> Self { if self.visit_map.is_some() { panic!("UntaggedEnumVisitor::map already set"); } self.visit_map = Some(Box::new(visit)); self } pub fn deserialize(self, deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_any(self) } } impl<'closure, 'de, Value> Visitor<'de> for UntaggedEnumVisitor<'closure, 'de, Value> { type Value = Value; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { if let Some(expecting) = &self.expecting { return expecting.fmt(formatter); } // "a string or array" // "an integer, string, or map" let mut message = Expecting::new(formatter); if self.visit_bool.is_some() { message.push("a", "boolean")?; } if self.visit_i8.is_some() || self.visit_i16.is_some() || self.visit_i32.is_some() || self.visit_i64.is_some() || self.visit_i128.is_some() || self.visit_u8.is_some() || self.visit_u16.is_some() || self.visit_u32.is_some() || self.visit_u64.is_some() || self.visit_u128.is_some() { message.push("an", "integer")?; } if self.visit_f32.is_some() || self.visit_f64.is_some() { message.push("a", "float")?; } if self.visit_char.is_some() { message.push("a", "character")?; } if self.visit_str.is_some() { message.push("a", "string")?; } if self.visit_borrowed_str.is_some() && self.visit_str.is_none() { message.push("a", "borrowed string")?; } if self.visit_bytes.is_some() || self.visit_borrowed_bytes.is_some() || self.visit_byte_buf.is_some() { message.push("a", "byte array")?; } if self.visit_unit.is_some() { message.push("", "null")?; } if self.visit_seq.is_some() { message.push("an", "array")?; } if self.visit_map.is_some() { message.push("a", "map")?; } message.flush() } fn visit_bool(self, v: bool) -> Result where E: serde::de::Error, { if let Some(visit_bool) = self.visit_bool { visit_bool(v).map_err(error::convert) } else { DefaultVisitor::new(&self).visit_bool(v) } } fn visit_i8(self, v: i8) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [I8, I16, I32, I64, I128, U8, U16, U32, U64, U128]) } fn visit_i16(self, v: i16) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [I16, I32, I64, I128, I8, U8, U16, U32, U64, U128]) } fn visit_i32(self, v: i32) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [I32, I64, I128, I8, I16, U8, U16, U32, U64, U128]) } fn visit_i64(self, v: i64) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [I64, I128, I8, I16, I32, U8, U16, U32, U64, U128]) } fn visit_i128(self, v: i128) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [I128, I8, I16, I32, I64, U8, U16, U32, U64, U128]) } fn visit_u8(self, v: u8) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [U8, U16, U32, U64, U128, I8, I16, I32, I64, I128]) } fn visit_u16(self, v: u16) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [U16, U32, U64, U128, U8, I8, I16, I32, I64, I128]) } fn visit_u32(self, v: u32) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [U32, U64, U128, U8, U16, I8, I16, I32, I64, I128]) } fn visit_u64(self, v: u64) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [U64, U128, U8, U16, U32, I8, I16, I32, I64, I128]) } fn visit_u128(self, v: u128) -> Result where E: serde::de::Error, { use crate::int::IntKind::*; self.dispatch_integer(v, [U128, U8, U16, U32, U64, I8, I16, I32, I64, I128]) } fn visit_f32(self, v: f32) -> Result where E: serde::de::Error, { if let Some(visit_f32) = self.visit_f32 { visit_f32(v).map_err(error::convert) } else { self.visit_f64(f64::from(v)) } } fn visit_f64(self, v: f64) -> Result where E: serde::de::Error, { if let Some(visit_f64) = self.visit_f64 { visit_f64(v).map_err(error::convert) } else { DefaultVisitor::new(&self).visit_f64(v) } } fn visit_char(self, v: char) -> Result where E: serde::de::Error, { if let Some(visit_char) = self.visit_char { visit_char(v).map_err(error::convert) } else if self.visit_str.is_some() { self.visit_str(v.encode_utf8(&mut [0u8; 4])) } else { Err(E::invalid_type(Unexpected::Char(v), &self)) } } fn visit_str(self, v: &str) -> Result where E: serde::de::Error, { if let Some(visit_str) = self.visit_str { visit_str(v).map_err(error::convert) } else { DefaultVisitor::new(&self).visit_str(v) } } fn visit_borrowed_str(self, v: &'de str) -> Result where E: serde::de::Error, { if let Some(visit_borrowed_str) = self.visit_borrowed_str { visit_borrowed_str(v).map_err(error::convert) } else { self.visit_str(v) } } fn visit_bytes(self, v: &[u8]) -> Result where E: serde::de::Error, { if let Some(visit_bytes) = self.visit_bytes { visit_bytes(v).map_err(error::convert) } else { DefaultVisitor::new(&self).visit_bytes(v) } } fn visit_borrowed_bytes(self, v: &'de [u8]) -> Result where E: serde::de::Error, { if let Some(visit_borrowed_bytes) = self.visit_borrowed_bytes { visit_borrowed_bytes(v).map_err(error::convert) } else { self.visit_bytes(v) } } fn visit_byte_buf(self, v: Vec) -> Result where E: serde::de::Error, { if let Some(visit_byte_buf) = self.visit_byte_buf { visit_byte_buf(v).map_err(error::convert) } else { self.visit_bytes(&v) } } fn visit_unit(self) -> Result where E: serde::de::Error, { if let Some(visit_unit) = self.visit_unit { visit_unit().map_err(error::convert) } else { DefaultVisitor::new(&self).visit_unit() } } fn visit_seq(self, seq: A) -> Result where A: SeqAccess<'de>, { if let Some(visit_seq) = self.visit_seq { visit_seq(Seq::new(seq)).map_err(error::convert) } else { DefaultVisitor::new(&self).visit_seq(seq) } } fn visit_map(self, map: A) -> Result where A: MapAccess<'de>, { if let Some(visit_map) = self.visit_map { visit_map(Map::new(map)).map_err(error::convert) } else { DefaultVisitor::new(&self).visit_map(map) } } } struct DefaultVisitor<'a, E, T> { expected: &'a E, value: PhantomData, } impl<'a, E, T> DefaultVisitor<'a, E, T> { fn new(expected: &'a E) -> Self { DefaultVisitor { expected, value: PhantomData, } } } impl<'a, 'de, V, T> Visitor<'de> for DefaultVisitor<'a, V, T> where V: Expected, { type Value = T; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { self.expected.fmt(formatter) } } struct Expecting<'e, 'a> { formatter: &'e mut fmt::Formatter<'a>, count: usize, last: Option<&'e str>, } impl<'e, 'a> Expecting<'e, 'a> { fn new(formatter: &'e mut fmt::Formatter<'a>) -> Self { Expecting { formatter, count: 0, last: None, } } fn push(&mut self, article: &str, item: &'e str) -> fmt::Result { self.count += 1; if self.count == 1 { if !article.is_empty() { self.formatter.write_str(article)?; self.formatter.write_str(" ")?; } self.formatter.write_str(item)?; } else { if let Some(last) = self.last.take() { self.formatter.write_str(", ")?; self.formatter.write_str(last)?; } self.last = Some(item); } Ok(()) } fn flush(&mut self) -> fmt::Result { if self.count == 0 { self.formatter.write_str("unspecified") // ?? } else if let Some(last) = self.last.take() { self.formatter.write_str(" or ")?; self.formatter.write_str(last) } else { Ok(()) } } } serde-untagged-0.1.1/src/map.rs000064400000000000000000000050111046102023000144300ustar 00000000000000use crate::any::ErasedValue; use crate::error::Error; use crate::seed::ErasedDeserializeSeed; use alloc::boxed::Box; use serde::de::{Deserialize, DeserializeSeed, MapAccess}; trait ErasedMapAccess<'de> { fn erased_next_key_seed( &mut self, seed: &mut dyn ErasedDeserializeSeed<'de>, ) -> Result, Error>; fn erased_next_value_seed( &mut self, seed: &mut dyn ErasedDeserializeSeed<'de>, ) -> Result; fn erased_size_hint(&self) -> Option; } pub struct Map<'access, 'de> { erased: Box + 'access>, } impl<'access, 'de> Map<'access, 'de> { pub(crate) fn new(map: A) -> Self where A: MapAccess<'de> + 'access, { Map { erased: Box::new(map), } } /// Shorthand for `T::deserialize(serde::de::value::MapAccessDeserializer::new(self))`. pub fn deserialize(self) -> Result where T: Deserialize<'de>, { T::deserialize(serde::de::value::MapAccessDeserializer::new(self)) } } impl<'access, 'de> MapAccess<'de> for Map<'access, 'de> { type Error = Error; fn next_key_seed(&mut self, seed: T) -> Result, Self::Error> where T: DeserializeSeed<'de>, { self.erased .erased_next_key_seed(&mut Some(seed)) .map(|erased_value| match erased_value { Some(value) => Some(unsafe { ErasedValue::take::(value) }), None => None, }) } fn next_value_seed(&mut self, seed: T) -> Result where T: DeserializeSeed<'de>, { self.erased .erased_next_value_seed(&mut Some(seed)) .map(|erased_value| unsafe { ErasedValue::take::(erased_value) }) } fn size_hint(&self) -> Option { self.erased.erased_size_hint() } } impl<'de, Access> ErasedMapAccess<'de> for Access where Access: MapAccess<'de>, { fn erased_next_key_seed( &mut self, seed: &mut dyn ErasedDeserializeSeed<'de>, ) -> Result, Error> { self.next_key_seed(seed).map_err(serde::de::Error::custom) } fn erased_next_value_seed( &mut self, seed: &mut dyn ErasedDeserializeSeed<'de>, ) -> Result { self.next_value_seed(seed).map_err(serde::de::Error::custom) } fn erased_size_hint(&self) -> Option { self.size_hint() } } serde-untagged-0.1.1/src/seed.rs000064400000000000000000000022221046102023000145740ustar 00000000000000use crate::any::ErasedValue; use alloc::boxed::Box; use serde::de::{DeserializeSeed, Deserializer}; pub(crate) trait ErasedDeserializeSeed<'de> { fn erased_deserialize( &mut self, deserializer: Box + '_>, ) -> Result; } impl<'de, Seed> ErasedDeserializeSeed<'de> for Option where Seed: DeserializeSeed<'de>, { fn erased_deserialize( &mut self, deserializer: Box + '_>, ) -> Result { self.take() .unwrap() .deserialize(deserializer) .map(|value| unsafe { ErasedValue::new::(value) }) } } impl<'de> DeserializeSeed<'de> for &mut dyn ErasedDeserializeSeed<'de> { type Value = ErasedValue; fn deserialize(self, deserializer: D) -> Result where D: Deserializer<'de>, { let deserializer = Box::new(::erase(deserializer)); self.erased_deserialize(deserializer) .map_err(serde::de::Error::custom) } } serde-untagged-0.1.1/src/seq.rs000064400000000000000000000036401046102023000144510ustar 00000000000000use crate::any::ErasedValue; use crate::error::Error; use crate::seed::ErasedDeserializeSeed; use alloc::boxed::Box; use serde::de::{Deserialize, DeserializeSeed, SeqAccess}; trait ErasedSeqAccess<'de> { fn erased_next_element_seed( &mut self, seed: &mut dyn ErasedDeserializeSeed<'de>, ) -> Result, Error>; fn erased_size_hint(&self) -> Option; } pub struct Seq<'access, 'de> { erased: Box + 'access>, } impl<'access, 'de> Seq<'access, 'de> { pub(crate) fn new(seq: A) -> Self where A: SeqAccess<'de> + 'access, { Seq { erased: Box::new(seq), } } /// Shorthand for `T::deserialize(serde::de::value::SeqAccessDeserializer::new(self))`. pub fn deserialize(self) -> Result where T: Deserialize<'de>, { T::deserialize(serde::de::value::SeqAccessDeserializer::new(self)) } } impl<'access, 'de> SeqAccess<'de> for Seq<'access, 'de> { type Error = Error; fn next_element_seed(&mut self, seed: T) -> Result, Self::Error> where T: DeserializeSeed<'de>, { self.erased .erased_next_element_seed(&mut Some(seed)) .map(|erased_value| match erased_value { Some(value) => Some(unsafe { ErasedValue::take::(value) }), None => None, }) } fn size_hint(&self) -> Option { self.erased.erased_size_hint() } } impl<'de, Access> ErasedSeqAccess<'de> for Access where Access: SeqAccess<'de>, { fn erased_next_element_seed( &mut self, seed: &mut dyn ErasedDeserializeSeed<'de>, ) -> Result, Error> { self.next_element_seed(seed) .map_err(serde::de::Error::custom) } fn erased_size_hint(&self) -> Option { self.size_hint() } } serde-untagged-0.1.1/tests/test.rs000064400000000000000000000116111046102023000152100ustar 00000000000000use serde::de::{Deserialize, Deserializer, SeqAccess}; use serde_json::json; use serde_untagged::UntaggedEnumVisitor; #[test] fn test_string_or_array_string() { #[derive(PartialEq, Debug)] enum Value { Single(String), Multiple(Vec), } impl<'de> Deserialize<'de> for Value { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { UntaggedEnumVisitor::new() .string(|string| Ok(Value::Single(string.to_owned()))) .seq(|mut seq| { let mut array = Vec::new(); while let Some(element) = seq.next_element()? { array.push(element); } Ok(Value::Multiple(array)) }) .deserialize(deserializer) } } let j = r#" "..." "#; let v: Value = serde_json::from_str(j).unwrap(); assert_eq!(v, Value::Single("...".to_owned())); let j = r#" ["a","z"] "#; let v: Value = serde_json::from_str(j).unwrap(); assert_eq!(v, Value::Multiple(vec!["a".to_owned(), "z".to_owned()])); } #[test] fn test_borrowed() { #[derive(PartialEq, Debug)] enum Value<'de> { Single(&'de str), Multiple(Vec<&'de str>), } impl<'de> Deserialize<'de> for Value<'de> { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { UntaggedEnumVisitor::new() .borrowed_str(|string| Ok(Value::Single(string))) .seq(|seq| seq.deserialize().map(Value::Multiple)) .deserialize(deserializer) } } let j = &r#" "..." "#.to_owned(); let v: Value = serde_json::from_str(j).unwrap(); assert_eq!(v, Value::Single("...")); let j = &r#" ["a","z"] "#.to_owned(); let v: Value = serde_json::from_str(j).unwrap(); assert_eq!(v, Value::Multiple(vec!["a", "z"])); } #[test] fn test_contains_map_key() { #[derive(PartialEq, Debug)] enum Response { Success(serde_json::Value), Failure(String), } impl<'de> Deserialize<'de> for Response { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { UntaggedEnumVisitor::new() .map(|map| { let value: serde_json::Value = map.deserialize()?; if let Ok(failure) = String::deserialize(&value["failure"]) { Ok(Response::Failure(failure)) } else { Ok(Response::Success(value)) } }) .deserialize(deserializer) } } let j = &r#" {"failure":"..."} "#.to_owned(); let v: Response = serde_json::from_str(j).unwrap(); assert_eq!(v, Response::Failure("...".to_owned())); let j = &r#" {"ok":200} "#.to_owned(); let v: Response = serde_json::from_str(j).unwrap(); assert_eq!(v, Response::Success(json!({"ok":200}))); } #[test] fn test_expecting() { let error = UntaggedEnumVisitor::new() .seq(|_seq| Ok(())) .deserialize(&serde_json::Value::Null) .unwrap_err(); let expected_message = "invalid type: null, expected an array"; assert_eq!(error.to_string(), expected_message); let error = UntaggedEnumVisitor::new() .seq(|_seq| Ok(())) .bool(|_bool| Ok(())) .deserialize(&serde_json::Value::Null) .unwrap_err(); let expected_message = "invalid type: null, expected a boolean or array"; assert_eq!(error.to_string(), expected_message); let error = UntaggedEnumVisitor::new() .seq(|_seq| Ok(())) .bool(|_bool| Ok(())) .i8(|_int| Ok(())) .deserialize(&serde_json::Value::Null) .unwrap_err(); let expected_message = "invalid type: null, expected a boolean, integer or array"; assert_eq!(error.to_string(), expected_message); let error = UntaggedEnumVisitor::new() .seq(|_seq| Ok(())) .bool(|_bool| Ok(())) .i8(|_int| Ok(())) .i16(|_int| Ok(())) .deserialize(&serde_json::Value::Null) .unwrap_err(); let expected_message = "invalid type: null, expected a boolean, integer or array"; assert_eq!(error.to_string(), expected_message); let error = UntaggedEnumVisitor::<()>::new() .deserialize(&serde_json::Value::Null) .unwrap_err(); let expected_message = "invalid type: null, expected unspecified"; assert_eq!(error.to_string(), expected_message); let ty = "T"; let error = UntaggedEnumVisitor::<()>::new() .expecting(format_args!("foo of type {ty}")) .deserialize(&serde_json::Value::Null) .unwrap_err(); let expected_message = "invalid type: null, expected foo of type T"; assert_eq!(error.to_string(), expected_message); }