Skip to main content

serde_with/
lib.rs

1#![doc(test(attr(
2    allow(
3        unknown_lints,
4        // Problematic handling for foreign From<T> impls in tests
5        // https://github.com/rust-lang/rust/issues/121621
6        non_local_definitions,
7        // Some tests use foo as name
8        clippy::disallowed_names,
9    ),
10    deny(
11        missing_debug_implementations,
12        rust_2018_idioms,
13        trivial_casts,
14        trivial_numeric_casts,
15        unused_extern_crates,
16        unused_import_braces,
17        unused_qualifications,
18        warnings,
19    ),
20    forbid(unsafe_code),
21)))]
22// Not needed for 2018 edition and conflicts with `rust_2018_idioms`
23#![doc(test(no_crate_inject))]
24#![doc(html_root_url = "https://docs.rs/serde_with/3.23.0/")]
25#![cfg_attr(docsrs, feature(doc_cfg))]
26#![no_std]
27
28//! [![crates.io badge](https://img.shields.io/crates/v/serde_with.svg)](https://crates.io/crates/serde_with/)
29//! [![Build Status](https://github.com/jonasbb/serde_with/actions/workflows/ci.yaml/badge.svg)](https://github.com/jonasbb/serde_with)
30//! [![codecov](https://codecov.io/gh/jonasbb/serde_with/branch/master/graph/badge.svg)](https://codecov.io/gh/jonasbb/serde_with)
31//! [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/4322/badge)](https://bestpractices.coreinfrastructure.org/projects/4322)
32//!
33//! ---
34//!
35//! This crate provides custom de/serialization helpers to use in combination with [serde's `with` annotation][with-annotation] and with the improved [`serde_as`][as-annotation]-annotation.
36//! Some common use cases are:
37//!
38//! * De/Serializing a type using the `Display` and `FromStr` traits, e.g., for `u8`, `url::Url`, or `mime::Mime`.
39//!   Check [`DisplayFromStr`] for details.
40//! * Support for arrays larger than 32 elements or using const generics.
41//!   With `serde_as` large arrays are supported, even if they are nested in other types.
42//!   `[bool; 64]`, `Option<[u8; M]>`, and `Box<[[u8; 64]; N]>` are all supported, as [this examples shows](#large-and-const-generic-arrays).
43//! * Skip serializing all empty `Option` types with [`#[skip_serializing_none]`][skip_serializing_none].
44//! * Apply a prefix / suffix to each field name of a struct, without changing the de/serialize implementations of the struct using [`with_prefix!`][] / [`with_suffix!`][].
45//! * Deserialize a comma separated list like `#hash,#tags,#are,#great` into a `Vec<String>`.
46//!   Check the documentation for [`serde_with::StringWithSeparator::<CommaSeparator, T>`][StringWithSeparator].
47//!
48//! ## Getting Help
49//!
50//! **Check out the [user guide][user guide] to find out more tips and tricks about this crate.**
51//!
52//! For further help using this crate you can [open a new discussion](https://github.com/jonasbb/serde_with/discussions/new) or ask on [users.rust-lang.org](https://users.rust-lang.org/).
53//! For bugs, please open a [new issue](https://github.com/jonasbb/serde_with/issues/new) on GitHub.
54//!
55//! # Use `serde_with` in your Project
56//!
57//! ```bash
58//! # Add the current version to your Cargo.toml
59//! cargo add serde_with
60//! ```
61//!
62//! The crate contains different features for integration with other common crates.
63//! Check the [feature flags][] section for information about all available features.
64//!
65//! # Examples
66//!
67//! Annotate your struct or enum to enable the custom de/serializer.
68//! The `#[serde_as]` attribute must be placed *before* the `#[derive]`.
69//!
70//! The `as` is analogous to the `with` attribute of serde.
71//! You mirror the type structure of the field you want to de/serialize.
72//! You can specify converters for the inner types of a field, e.g., `Vec<DisplayFromStr>`.
73//! The default de/serialization behavior can be restored by using `_` as a placeholder, e.g., `BTreeMap<_, DisplayFromStr>`.
74//!
75//! ## `DisplayFromStr`
76//!
77//! ```rust
78//! # #[cfg(all(feature = "macros", feature = "json"))] {
79//! # use serde::{Deserialize, Serialize};
80//! # use serde_with::{serde_as, DisplayFromStr};
81//! #[serde_as]
82//! # #[derive(Debug, Eq, PartialEq)]
83//! #[derive(Deserialize, Serialize)]
84//! struct Foo {
85//!     // Serialize with Display, deserialize with FromStr
86//!     #[serde_as(as = "DisplayFromStr")]
87//!     bar: u8,
88//! }
89//!
90//! // This will serialize
91//! # let foo =
92//! Foo {bar: 12}
93//! # ;
94//!
95//! // into this JSON
96//! # let json = r#"
97//! {"bar": "12"}
98//! # "#;
99//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
100//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
101//! # }
102//! ```
103//!
104//! ## Large and const-generic arrays
105//!
106//! serde does not support arrays with more than 32 elements or using const-generics.
107//! The `serde_as` attribute allows circumventing this restriction, even for nested types and nested arrays.
108//!
109//! On top of it, `[u8; N]` (aka, bytes) can use the specialized `"Bytes"` for efficiency much like the `serde_bytes` crate.
110//!
111//! ```rust
112//! # #[cfg(all(feature = "macros", feature = "json"))] {
113//! # use serde::{Deserialize, Serialize};
114//! # use serde_with::{serde_as, Bytes};
115//! #[serde_as]
116//! # #[derive(Debug, Eq, PartialEq)]
117//! #[derive(Deserialize, Serialize)]
118//! struct Arrays<const N: usize, const M: usize> {
119//!     #[serde_as(as = "[_; N]")]
120//!     constgeneric: [bool; N],
121//!
122//!     #[serde_as(as = "Box<[[_; 64]; N]>")]
123//!     nested: Box<[[u8; 64]; N]>,
124//!
125//!     #[serde_as(as = "Option<[_; M]>")]
126//!     optional: Option<[u8; M]>,
127//!
128//!     #[serde_as(as = "Bytes")]
129//!     bytes: [u8; M],
130//! }
131//!
132//! // This allows us to serialize a struct like this
133//! let arrays: Arrays<100, 128> = Arrays {
134//!     constgeneric: [true; 100],
135//!     nested: Box::new([[111; 64]; 100]),
136//!     optional: Some([222; 128]),
137//!     bytes: [0x42; 128],
138//! };
139//! assert!(serde_json::to_string(&arrays).is_ok());
140//! # }
141//! ```
142//!
143//! ## `skip_serializing_none`
144//!
145//! This situation often occurs with JSON, but other formats also support optional fields.
146//! If many fields are optional, putting the annotations on the structs can become tedious.
147//! The `#[skip_serializing_none]` attribute must be placed *before* the `#[derive]`.
148//!
149//! ```rust
150//! # #[cfg(all(feature = "macros", feature = "json"))] {
151//! # use serde::{Deserialize, Serialize};
152//! # use serde_with::skip_serializing_none;
153//! #[skip_serializing_none]
154//! # #[derive(Debug, Eq, PartialEq)]
155//! #[derive(Deserialize, Serialize)]
156//! struct Foo {
157//!     a: Option<usize>,
158//!     b: Option<usize>,
159//!     c: Option<usize>,
160//!     d: Option<usize>,
161//!     e: Option<usize>,
162//!     f: Option<usize>,
163//!     g: Option<usize>,
164//! }
165//!
166//! // This will serialize
167//! # let foo =
168//! Foo {a: None, b: None, c: None, d: Some(4), e: None, f: None, g: Some(7)}
169//! # ;
170//!
171//! // into this JSON
172//! # let json = r#"
173//! {"d": 4, "g": 7}
174//! # "#;
175//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
176//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
177//! # }
178//! ```
179//!
180//! ## Advanced `serde_as` usage
181//!
182//! This example is mainly supposed to highlight the flexibility of the `serde_as` annotation compared to [serde's `with` annotation][with-annotation].
183//! More details about `serde_as` can be found in the [user guide].
184//!
185//! ```rust
186//! # #[cfg(all(feature = "macros", feature = "hex"))]
187//! # use {
188//! #     serde::{Deserialize, Serialize},
189//! #     serde_with::{serde_as, DisplayFromStr, DurationSeconds, hex::Hex, Map},
190//! # };
191//! # #[cfg(all(feature = "macros", feature = "hex"))]
192//! use std::time::Duration;
193//!
194//! # #[cfg(all(feature = "macros", feature = "hex"))]
195//! #[serde_as]
196//! # #[derive(Debug, Eq, PartialEq)]
197//! #[derive(Deserialize, Serialize)]
198//! enum Foo {
199//!     Durations(
200//!         // Serialize them into a list of number as seconds
201//!         #[serde_as(as = "Vec<DurationSeconds>")]
202//!         Vec<Duration>,
203//!     ),
204//!     Bytes {
205//!         // We can treat a Vec like a map with duplicates.
206//!         // JSON only allows string keys, so convert i32 to strings
207//!         // The bytes will be hex encoded
208//!         #[serde_as(as = "Map<DisplayFromStr, Hex>")]
209//!         bytes: Vec<(i32, Vec<u8>)>,
210//!     }
211//! }
212//!
213//! # #[cfg(all(feature = "macros", feature = "json", feature = "hex"))] {
214//! // This will serialize
215//! # let foo =
216//! Foo::Durations(
217//!     vec![Duration::new(5, 0), Duration::new(3600, 0), Duration::new(0, 0)]
218//! )
219//! # ;
220//! // into this JSON
221//! # let json = r#"
222//! {
223//!     "Durations": [5, 3600, 0]
224//! }
225//! # "#;
226//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
227//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
228//!
229//! // and serializes
230//! # let foo =
231//! Foo::Bytes {
232//!     bytes: vec![
233//!         (1, vec![0, 1, 2]),
234//!         (-100, vec![100, 200, 255]),
235//!         (1, vec![0, 111, 222]),
236//!     ],
237//! }
238//! # ;
239//! // into this JSON
240//! # let json = r#"
241//! {
242//!     "Bytes": {
243//!         "bytes": {
244//!             "1": "000102",
245//!             "-100": "64c8ff",
246//!             "1": "006fde"
247//!         }
248//!     }
249//! }
250//! # "#;
251//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
252//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
253//! # }
254//! ```
255//!
256//! [`DisplayFromStr`]: https://docs.rs/serde_with/3.23.0/serde_with/struct.DisplayFromStr.html
257//! [`with_prefix!`]: https://docs.rs/serde_with/3.23.0/serde_with/macro.with_prefix.html
258//! [`with_suffix!`]: https://docs.rs/serde_with/3.23.0/serde_with/macro.with_suffix.html
259//! [feature flags]: https://docs.rs/serde_with/3.23.0/serde_with/guide/feature_flags/index.html
260//! [skip_serializing_none]: https://docs.rs/serde_with/3.23.0/serde_with/attr.skip_serializing_none.html
261//! [StringWithSeparator]: https://docs.rs/serde_with/3.23.0/serde_with/struct.StringWithSeparator.html
262//! [user guide]: https://docs.rs/serde_with/3.23.0/serde_with/guide/index.html
263//! [with-annotation]: https://serde.rs/field-attrs.html#with
264//! [as-annotation]: https://docs.rs/serde_with/3.23.0/serde_with/guide/serde_as/index.html
265
266#[cfg(feature = "alloc")]
267extern crate alloc;
268#[doc(hidden)]
269extern crate core;
270#[doc(hidden)]
271extern crate serde_core;
272#[cfg(feature = "std")]
273extern crate std;
274
275#[cfg(feature = "base58")]
276#[cfg_attr(docsrs, doc(cfg(feature = "base58")))]
277pub mod base58;
278#[cfg(feature = "base64")]
279#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
280pub mod base64;
281#[cfg(feature = "chrono_0_4")]
282#[cfg_attr(docsrs, doc(cfg(feature = "chrono_0_4")))]
283pub mod chrono_0_4;
284/// Legacy export of the [`chrono_0_4`] module.
285#[cfg(feature = "chrono")]
286#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
287pub mod chrono {
288    pub use crate::chrono_0_4::*;
289    pub use chrono_0_4::*;
290}
291#[cfg(feature = "alloc")]
292mod content;
293pub mod de;
294#[cfg(feature = "alloc")]
295mod duplicate_key_impls;
296#[cfg(feature = "alloc")]
297mod enum_map;
298#[cfg(feature = "std")]
299/// NOT PUBLIC API
300#[doc(hidden)]
301pub mod flatten_maybe;
302pub mod formats;
303#[cfg(feature = "hex")]
304#[cfg_attr(docsrs, doc(cfg(feature = "hex")))]
305pub mod hex;
306#[cfg(feature = "jiff_0_2")]
307#[cfg_attr(docsrs, doc(cfg(feature = "jiff_0_2")))]
308pub mod jiff_0_2;
309#[cfg(feature = "json")]
310#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
311pub mod json;
312#[cfg(feature = "alloc")]
313mod key_value_map;
314pub mod rust;
315#[cfg(feature = "schemars_0_8")]
316#[cfg_attr(docsrs, doc(cfg(feature = "schemars_0_8")))]
317pub mod schemars_0_8;
318#[cfg(feature = "schemars_0_9")]
319#[cfg_attr(docsrs, doc(cfg(feature = "schemars_0_9")))]
320pub mod schemars_0_9;
321#[cfg(feature = "schemars_1")]
322#[cfg_attr(docsrs, doc(cfg(feature = "schemars_1")))]
323pub mod schemars_1;
324pub mod ser;
325mod serde_conv;
326#[cfg(feature = "time_0_3")]
327#[cfg_attr(docsrs, doc(cfg(feature = "time_0_3")))]
328pub mod time_0_3;
329mod utils;
330#[cfg(feature = "std")]
331#[doc(hidden)]
332pub mod with_prefix;
333#[cfg(feature = "std")]
334#[doc(hidden)]
335pub mod with_suffix;
336
337// Taken from shepmaster/snafu
338// Originally licensed as MIT+Apache 2
339// https://github.com/shepmaster/snafu/blob/90991b609e8928ceebf7df1b040408539d21adda/src/lib.rs#L343-L376
340#[cfg(feature = "guide")]
341#[allow(unused_macro_rules)]
342macro_rules! generate_guide {
343    (pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
344        generate_guide!(@gen ".", pub mod $name { $($children)* } $($rest)*);
345    };
346    (@gen $prefix:expr, ) => {};
347    (@gen $prefix:expr, pub mod $name:ident; $($rest:tt)*) => {
348        generate_guide!(@gen $prefix, pub mod $name { } $($rest)*);
349    };
350    (@gen $prefix:expr, @code pub mod $name:ident; $($rest:tt)*) => {
351        #[cfg(feature = "guide")]
352        pub mod $name;
353
354        #[cfg(not(feature = "guide"))]
355        /// Not currently built; please add the `guide` feature flag.
356        pub mod $name {}
357
358        generate_guide!(@gen $prefix, $($rest)*);
359    };
360    (@gen $prefix:expr, pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
361        #[cfg(feature = "guide")]
362        #[doc = include_str!(concat!($prefix, "/", stringify!($name), ".md"))]
363        pub mod $name {
364            generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
365        }
366        #[cfg(not(feature = "guide"))]
367        /// Not currently built; please add the `guide` feature flag.
368        pub mod $name {
369            generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
370        }
371
372        generate_guide!(@gen $prefix, $($rest)*);
373    };
374}
375
376#[cfg(feature = "guide")]
377#[doc =
"# `serde_with` User Guide\n\nThis crate provides helper functions to extend and change how [`serde`](::serde_core) serializes different data types.\nFor example, you can serialize [a map as a sequence of tuples][crate::guide::serde_as#maps-to-vec-of-tuples], serialize [using the `Display` and `FromStr` traits][`DisplayFromStr`], or serialize [an empty `String` like `None`][NoneAsEmptyString].\n`serde_with` covers types from the Rust Standard Library and some common crates like [`chrono`][serde_with_chrono].\n\n[**A list of all supported transformations is available on this page.**](crate::guide::serde_as_transformations)\n\nThe crate offers four types of functionality.\n\n## 1. A more flexible and composable replacement for the `with` annotation, called `serde_as`\n\nThis is an alternative to [serde\'s `with` annotation][with-annotation], which adds flexibility and composability to the scheme.\nThe main downside is that it works with fewer types than [`with` annotations][with-annotation].\nHowever, all types from the Rust Standard Library should be supported in all combinations and any missing entry is a bug.\n\nYou mirror the type structure of the field you want to de/serialize.\nYou can specify converters for the inner types of a field, e.g., `Vec<DisplayFromStr>`.\nThe default de/serialization behavior can be restored by using `_` as a placeholder, e.g., `BTreeMap<_, DisplayFromStr>`.\n\nThe `serde_as` scheme is based on two new traits: [`SerializeAs`] and [`DeserializeAs`].  \n[Check out the detailed page about `serde_as` and the available features.](crate::guide::serde_as)\n\n### Example\n\n```rust\n# use serde::{Deserialize, Serialize};\n# use serde_with::{serde_as, DisplayFromStr, Map};\n# use std::net::Ipv4Addr;\n#\n#[serde_as]\n# #[derive(Debug, PartialEq, Eq)]\n#[derive(Deserialize, Serialize)]\nstruct Data {\n    // Type does not implement Serialize or Deserialize\n    #[serde_as(as = \"DisplayFromStr\")]\n    address: Ipv4Addr,\n    // Treat the Vec like a map with duplicates\n    // Convert u32 into a String and keep the String the same type\n    #[serde_as(as = \"Map<DisplayFromStr, _>\")]\n    vec_as_map: Vec<(u32, String)>,\n}\n\nlet data = Data {\n    address: Ipv4Addr::new(192, 168, 0, 1),\n    vec_as_map: vec![\n        (123, \"Hello\".into()),\n        (456, \"World\".into()),\n        (123, \"Hello\".into()),\n    ],\n};\n\nlet json = r#\"{\n  \"address\": \"192.168.0.1\",\n  \"vec_as_map\": {\n    \"123\": \"Hello\",\n    \"456\": \"World\",\n    \"123\": \"Hello\"\n  }\n}\"#;\n\n// Test Serialization\nassert_eq!(json, serde_json::to_string_pretty(&data).unwrap());\n// Test Deserialization\nassert_eq!(data, serde_json::from_str(json).unwrap());\n```\n\n## 2. proc-macros to make it easier to use both above parts\n\nThe proc-macros are an optional addition and improve the user experience for common tasks.\nWe have already seen how the `serde_as` attribute is used to define the serialization instructions.\n\nThe proc-macro attributes are defined in the [`serde_with_macros`] crate and re-exported from the root of this crate.\nThe proc-macros are optional, but enabled by default.\nFor further details, please refer to the documentation of each proc-macro.\n\n## 3. Derive macros to implement `Deserialize` and `Serialize`\n\nThe derive macros work similar to the serde provided ones, but they do implement other de/serialization schemes.\nFor example, the derives [`DeserializeFromStr`] and [`SerializeDisplay`] require that the type also implement [`FromStr`] and [`Display`] and de/serializes from/to a string instead of the usual way of iterating over all fields.\n\n[`Display`]: std::fmt::Display\n[`FromStr`]: std::str::FromStr\n[`serde_with_macros`]: ::serde_with_macros\n[serde_with_chrono]: ::chrono_0_4\n[with-annotation]: https://serde.rs/field-attrs.html#with\n"]
pub mod guide {
    pub mod feature_flags {
        //! # Available Feature Flags
        //!
        #![doc =
        " `serde_with` is fully `no_std` compatible, by depending on it with `default-features = false`.\n Support for `alloc` and `std` can be enabled with the respective features.\n Some features require `alloc` or `std` support and might not work in a `no_std` environment.\n* **`alloc`** *(enabled by default)* —  Enable support for types from the `alloc` crate when running in a `no_std` environment.\n* **`std`** *(enabled by default)* —  Enables support for various types from the std library.\n  This will enable `std` support in all dependencies too.\n  The feature enabled by default and also enables `alloc`.\n\n # Documentation\n\n The following features enhance the documentation of `serde_with`.\n* **`guide`** —  The `guide` feature enables inclusion of this user guide.\n  The feature only changes the rustdoc output and enables no other effects.\n\n # Features\n\n The following features enable support for types from other crates or enable additional functionality that requires further dependencies to be pulled in.\n These features are disabled by default to minimize the number of required dependencies.\n* **`base58`** —  The feature enables serializing data in base58 format.\n \n  This pulls in [`bs58`] as a dependency.\n* **`base64`** —  The feature enables serializing data in base64 format.\n \n  This pulls in [`base64`] as a dependency.\n* **`chrono`** —  Deprecated feature name. Use `chrono_0_4` instead.\n* **`chrono_0_4`** —  The feature enables integration of `chrono` v0.4 specific conversions.\n  This includes support for the timestamp and duration types.\n  More features are available in combination with `alloc` or `std`.\n  The legacy feature name `chrono` is still available for v1 compatibility.\n \n  This pulls in [`chrono` v0.4](::chrono_0_4) as a dependency.\n* **`hashbrown_0_14`** —  The feature enables `hashbrown::{HashMap, HashSet}` as supported containers.\n \n  This pulls in [`hashbrown` v0.14](::hashbrown_0_14) as a dependency.\n  It enables the `alloc` feature.\n  Some functionality is only available when `std` is enabled too.\n* **`hashbrown_0_15`** —  The feature enables `hashbrown::{HashMap, HashSet}` as supported containers.\n \n  This pulls in [`hashbrown` v0.15](::hashbrown_0_15) as a dependency.\n  It enables the `alloc` feature.\n  Some functionality is only available when `std` is enabled too.\n* **`hashbrown_0_16`** —  The feature enables `hashbrown::{HashMap, HashSet}` as supported containers.\n \n  This pulls in [`hashbrown` v0.16](::hashbrown_0_16) as a dependency.\n  It enables the `alloc` feature.\n  Some functionality is only available when `std` is enabled too.\n* **`hashbrown_0_17`** —  The feature enables `hashbrown::{HashMap, HashSet}` as supported containers.\n \n  This pulls in [`hashbrown` v0.17](::hashbrown_0_17) as a dependency.\n  It enables the `alloc` feature.\n  Some functionality is only available when `std` is enabled too.\n* **`hex`** —  The feature enables serializing data in hex format.\n \n  This pulls in [`hex`] as a dependency.\n  It enables the `alloc` feature.\n* **`indexmap`** —  Deprecated feature name. Use `indexmap_1` instead.\n* **`indexmap_1`** —  The feature enables implementations of `indexmap` v1 specific checks.\n  This includes support for checking duplicate keys and duplicate values.\n  The legacy feature name `indexmap` is still available for v1 compatibility.\n \n  This pulls in [`indexmap` v1](::indexmap_1) as a dependency.\n  It enables the `alloc` feature.\n  Some functionality is only available when `std` is enabled too.\n* **`indexmap_2`** —  The feature enables implementations of `indexmap` v2 specific checks.\n  This includes support for checking duplicate keys and duplicate values.\n \n  This pulls in [`indexmap` v2](::indexmap_2) as a dependency.\n  It enables the `alloc` feature.\n  Some functionality is only available when `std` is enabled too.\n* **`jiff_0_2`** —  The feature enables integration of `jiff` v0.2 specific conversions.\n  This includes support for the timestamp, duration, zoned and civil datetime types.\n \n  This pulls in [`jiff` v0.2](::jiff_0_2) as a dependency.\n  Some functionality is only available when `alloc` or `std` is enabled too.\n* **`json`** —  The feature enables JSON conversions from the `json` module.\n \n  This pulls in [`serde_json`] as a dependency.\n  It enables the `alloc` feature.\n* **`macros`** *(enabled by default)* —  The feature enables all helper macros and derives.\n  It is enabled by default, since the macros provide a usability benefit, especially for `serde_as`.\n \n  This pulls in [`serde_with_macros`] as a dependency.\n* **`schemars_0_8`** —  This feature enables integration with `schemars` v0.8.\n  This makes `#[derive(JsonSchema)]` pick up the correct schema for the type\n  used within `#[serde_as(as = ...)]`.\n \n  This pulls in [`schemars` v0.8](::schemars_0_8) as a dependency. It will also implicitly enable\n  the `std` feature as `schemars` is not `#[no_std]`.\n* **`schemars_0_9`** —  This feature enables integration with `schemars` v0.9\n  This makes `#[derive(JsonSchema)]` pick up the correct schema for the type\n  used within `#[serde_as(as = ...)]`.\n \n  This pulls in [`schemars` v0.9](::schemars_0_9) as a dependency. It will also implicitly enable\n  the `alloc` feature.\n* **`schemars_1`** —  This feature enables integration with `schemars` v1\n  This makes `#[derive(JsonSchema)]` pick up the correct schema for the type\n  used within `#[serde_as(as = ...)]`.\n \n  This pulls in [`schemars` v1](::schemars_1) as a dependency. It will also implicitly enable\n  the `alloc` feature.\n* **`smallvec_1`** —  The feature enables `SmallVec` as a supported container.\n \n  This pulls in [`smallvec` v1](::smallvec_1) as a dependency.\n* **`time_0_3`** —  The feature enables integration of `time` v0.3 specific conversions.\n  This includes support for the timestamp and duration types.\n \n  This pulls in [`time` v0.3](::time_0_3) as a dependency.\n  Some functionality is only available when `alloc` or `std` is enabled too.\n"]
    }
    #[doc =
    "# `serde_as` Annotation\n\nThis is an alternative to serde\'s `with` annotation.\nIt is more flexible and composable, but works with fewer types.\n\nThe scheme is based on two new traits, [`SerializeAs`] and [`DeserializeAs`], which need to be implemented by all types which want to be compatible with `serde_as`.\nThe proc-macro attribute [`#[serde_as]`][crate::serde_as] exists as a usability boost for users.\nThe basic design of `serde_as` was developed by [@markazmierczak](https://github.com/markazmierczak).\n\nThis page contains some general advice on the usage of `serde_as` and on implementing the necessary traits.  \n[**A list of all supported transformations enabled by `serde_as` is available on this page.**](crate::guide::serde_as_transformations)\n\n1. [Switching from serde\'s with to `serde_as`](#switching-from-serdes-with-to-serde_as)\n    1. [Deserializing Optional Fields](#deserializing-optional-fields)\n    2. [Gating `serde_as` on Features](#gating-serde_as-on-features)\n2. [Implementing `SerializeAs` / `DeserializeAs`](#implementing-serializeas--deserializeas)\n    1. [Using `#[serde_as]` on types without `SerializeAs` and `Serialize` implementations](#using-serde_as-on-types-without-serializeas-and-serialize-implementations)\n    2. [Using `#[serde_as]` with serde\'s remote derives](#using-serde_as-with-serdes-remote-derives)\n3. [Re-exporting `serde_as`](#re-exporting-serde_as)\n\n## Switching from serde\'s with to `serde_as`\n\nFor the user, the main difference is that instead of\n\n```rust,ignore\n#[serde(with = \"...\")]\n```\n\nyou now have to write\n\n```rust,ignore\n#[serde_as(as = \"...\")]\n```\n\nand place the `#[serde_as]` attribute *before* the `#[derive]` attribute.\nYou still need the `#[derive(Serialize, Deserialize)]` on the struct/enum.\nYou mirror the type structure of the field you want to de/serialize.\nYou can specify converters for the inner types of a field, e.g., `Vec<DisplayFromStr>`.\nThe default de/serialization behavior can be restored by using `_` as a placeholder, e.g., `BTreeMap<_, DisplayFromStr>`.\n\nCombined, this looks like:\n\n```rust\nuse serde::{Deserialize, Serialize};\nuse serde_with::{serde_as, DisplayFromStr};\n\n# #[allow(dead_code)]\n#[serde_as]\n#[derive(Serialize, Deserialize)]\nstruct A {\n    #[serde_as(as = \"DisplayFromStr\")]\n    mime: mime::Mime,\n}\n```\n\nThe main advantage is that you can compose `serde_as` stuff, which is impossible with the `with` annotation.\nFor example, the `mime` field from above could be nested in one or more data structures:\n\n```rust\n# use std::collections::BTreeMap;\n# use serde::{Deserialize, Serialize};\n# use serde_with::{serde_as, DisplayFromStr};\n#\n# #[allow(dead_code)]\n#[serde_as]\n#[derive(Serialize, Deserialize)]\nstruct A {\n    #[serde_as(as = \"Option<BTreeMap<_, Vec<DisplayFromStr>>>\")]\n    mime: Option<BTreeMap<String, Vec<mime::Mime>>>,\n}\n```\n\n### Deserializing Optional Fields\n\nIn many cases, using `serde_as` on a field of type `Option` should behave as expected.\nThis means the field can still be missing during deserialization and will be filled with the value `None`.\n\nThis \"magic\" can break in some cases. Then it becomes necessary to apply `#[serde(default)]` on the field in question.\nIf the field is of type `Option<T>` and the conversion type is of `Option<S>`, the default attribute is automatically applied.\nThese variants are detected as `Option`.\n\n* `Option`\n* `std::option::Option`, with or without leading `::`\n* `core::option::Option`, with or without leading `::`\n\nAny renaming will interfere with the detection, such as `use std::option::Option as StdOption;`.\nFor more information, you can inspect the documentation of the `serde_as` macro.\n\n```rust\n# use serde::{Deserialize, Serialize};\n# use serde_with::{serde_as, DisplayFromStr};\n#\n# #[allow(dead_code)]\n#[serde_as]\n#[derive(Serialize, Deserialize)]\nstruct A {\n    #[serde_as(as = \"Option<DisplayFromStr>\")]\n    // In this situation both `Option`s will be correctly identified and\n    // `#[serde(default)]` will be applied on this field.\n    val: Option<u32>,\n}\n```\n\nIn the future, this behavior might change and `default` would be applied on `Option<T>` fields.\nYou can add your feedback at [serde_with#185].\n\n### Gating `serde_as` on Features\n\nGating `serde_as` behind optional features is possible using the `cfg_eval` attribute.\nThe attribute is available via the [`cfg_eval`-crate](https://docs.rs/cfg_eval) on stable or using the [Rust attribute](https://doc.rust-lang.org/1.70.0/core/prelude/v1/attr.cfg_eval.html) on unstable nightly.\n\nThe `cfg_eval` attribute must be placed **before** the struct-level `serde_as` attribute.\nYou can combine them in a single `cfg_attr`, as long as the order is preserved.\n\n```rust,ignore\n#[cfg_attr(feature=\"serde\", cfg_eval::cfg_eval, serde_as)]\n#[cfg_attr(feature=\"serde\", derive(Serialize, Deserialize))]\nstruct Struct {\n    #[cfg_attr(feature=\"serde\", serde_as(as = \"Vec<(_, _)>\"))]\n    map: HashMap<(i32,i32), i32>,\n}\n```\n\n## Implementing `SerializeAs` / `DeserializeAs`\n\nYou can support [`SerializeAs`] / [`DeserializeAs`] on your own types too.\nMost \"leaf\" types do not need to implement these traits, since they are supported implicitly.\n\"Leaf\" types refer to types which directly serialize, like plain data types.\n[`SerializeAs`] / [`DeserializeAs`] is essential for collection types, like `Vec` or `BTreeMap`, since they need special handling for the key/value de/serialization such that the conversions can be done on the key/values.\nYou also find them implemented on the conversion types, such as the [`DisplayFromStr`] type.\nThese comprise the bulk of this crate and allow you to perform all the nice conversions to [hex strings], the [bytes to string converter], or [duration to UNIX epoch].\n\nIn many cases, conversion is only required from one serializable type to another one, without requiring the full power of the `Serialize` or `Deserialize` traits.\nIn these cases, the [`serde_conv!`] macro conveniently allows defining conversion types without the boilerplate.\nThe documentation of [`serde_conv!`] contains more details how to use it.\n\nThe trait documentations for [`SerializeAs`] and [`DeserializeAs`] describe in details how to implement them for container types like `Box` or `Vec` and other types.\n\n### Using `#[serde_as]` on types without `SerializeAs` and `Serialize` implementations\n\nThe `SerializeAs` and `DeserializeAs` traits can easily be used together with types from other crates without running into orphan rule problems.\nThis is a distinct advantage of the `serde_as` system.\nFor this example, we assume we have a type `RemoteType` from a dependency which does not implement `Serialize` nor `SerializeAs`.\nWe assume we have a module containing a `serialize` and a `deserialize` function, which can be used in the `#[serde(with = \"MODULE\")]` annotation.\nYou find an example in the [official serde documentation](https://serde.rs/custom-date-format.html).\n\nOur goal is to serialize this `Data` struct.\nCurrently, we do not have anything we can use to replace `???` with, since `_` only works if `RemoteType` would implement `Serialize`, which it does not.\n\n```rust\n# #[cfg(false)] {\n#[serde_as]\n#[derive(serde::Serialize)]\nstruct Data {\n    #[serde_as(as = \"Vec<???>\")]\n    vec: Vec<RemoteType>,\n}\n# }\n```\n\nWe need to create a new type for which we can implement `SerializeAs`, to replace the `???`.\nThe `SerializeAs` implementation is **always** written for a local type.\nThis allows it to seamlessly work with types from dependencies without running into orphan rule problems.\n\n```rust\n# #[cfg(false)] {\nstruct LocalType;\n\nimpl SerializeAs<RemoteType> for LocalType {\n    fn serialize_as<S>(value: &RemoteType, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: Serializer,\n    {  \n        MODULE::serialize(value, serializer)\n    }\n}\n\nimpl<\'de> DeserializeAs<\'de, RemoteType> for LocalType {\n    fn deserialize_as<D>(deserializer: D) -> Result<RemoteType, D::Error>\n    where\n        D: Deserializer<\'de>,\n    {  \n        MODULE::deserialize(deserializer)\n    }\n}\n# }\n```\n\nThis is what the final implementation looks like.\nWe assumed we already have a module `MODULE` with a `serialize` function, which we use here to provide the implementation.\nAs can be seen, this is mostly boilerplate, since the most part is encapsulated in `$module::serialize`.\nThe final `Data` struct will now look like:\n\n```rust\n# #[cfg(false)] {\n#[serde_as]\n#[derive(serde::Serialize)]\nstruct Data {\n    #[serde_as(as = \"Vec<LocalType>\")]\n    vec: Vec<RemoteType>,\n}\n# }\n```\n\n### Using `#[serde_as]` with serde\'s remote derives\n\nA special case of the above section is using it on remote derives.\nThis is a special functionality of serde, where it derives the de/serialization code for a type from another crate if all fields are `pub`.\nYou can find all the details in the [official serde documentation](https://serde.rs/remote-derive.html).\n\n```rust\n# #[cfg(false)] {\n// Pretend that this is somebody else\'s crate, not a module.\nmod other_crate {\n    // Neither Serde nor the other crate provides Serialize and Deserialize\n    // impls for this struct.\n    pub struct Duration {\n        pub secs: i64,\n        pub nanos: i32,\n    }\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nuse other_crate::Duration;\n\n// Serde calls this the definition of the remote type. It is just a copy of the\n// remote data structure. The `remote` attribute gives the path to the actual\n// type we intend to derive code for.\n#[derive(serde::Serialize, serde::Deserialize)]\n#[serde(remote = \"Duration\")]\nstruct DurationDef {\n    secs: i64,\n    nanos: i32,\n}\n# }\n```\n\nOur goal is now to use `Duration` within `serde_as`.\nWe use the existing `DurationDef` type and its `serialize` and `deserialize` functions.\nWe can write this implementation.\nThe implementation for `DeserializeAs` works analogue.\n\n```rust\n# #[cfg(false)] {\nimpl SerializeAs<Duration> for DurationDef {\n    fn serialize_as<S>(value: &Duration, serializer: S) -> Result<S::Ok, S::Error>\n    where\n        S: serde::Serializer,\n    {  \n        DurationDef::serialize(value, serializer)\n    }\n}\n# }\n```\n\nThis now allows us to use `Duration` for serialization.\n\n```rust\n# #[cfg(false)] {\nuse other_crate::Duration;\n\n#[serde_as]\n#[derive(serde::Serialize)]\nstruct Data {\n    #[serde_as(as = \"Vec<DurationDef>\")]\n    vec: Vec<Duration>,\n}\n# }\n```\n\n## Re-exporting `serde_as`\n\nIf `serde_as` is being used in a context where the `serde_with` crate is not available from the root\npath, but is re-exported at some other path, the `crate = \"...\"` attribute argument should be used\nto specify its path. This may be the case if `serde_as` is being used in a procedural macro -\notherwise, users of that macro would need to add `serde_with` to their own Cargo manifest.\n\nThe `crate` argument will generally be used in conjunction with [`serde`\'s own `crate` argument].\n\nFor example, a type definition may be defined in a procedural macro:\n\n```rust,ignore\n// some_other_lib_derive/src/lib.rs\n\nuse proc_macro::TokenStream;\nuse quote::quote;\n\n#[proc_macro]\npub fn define_some_type(_item: TokenStream) -> TokenStream {\n    let def = quote! {\n        #[serde(crate = \"::some_other_lib::serde\")]\n        #[::some_other_lib::serde_with::serde_as(crate = \"::some_other_lib::serde_with\")]\n        #[derive(::some_other_lib::serde::Deserialize)]\n        struct Data {\n            #[serde_as(as = \"_\")]\n            a: u32,\n        }\n    };\n\n    TokenStream::from(def)\n}\n```\n\nThis can be re-exported through a library which also re-exports `serde` and `serde_with`:\n\n```rust,ignore\n// some_other_lib/src/lib.rs\n\npub use serde;\npub use serde_with;\npub use some_other_lib_derive::define_some_type;\n```\n\nThe procedural macro can be used by other crates without any additional imports:\n\n```rust,ignore\n// consuming_crate/src/main.rs\n\nsome_other_lib::define_some_type!();\n```\n\n[`DeserializeAs`]: crate::DeserializeAs\n[`DisplayFromStr`]: crate::DisplayFromStr\n[`serde_as`]: crate::serde_as\n[`serde_conv!`]: crate::serde_conv!\n[`serde`\'s own `crate` argument]: https://serde.rs/container-attrs.html#crate\n[`SerializeAs`]: crate::SerializeAs\n[bytes to string converter]: crate::BytesOrString\n[duration to UNIX epoch]: crate::DurationSeconds\n[hex strings]: crate::hex::Hex\n[serde_with#185]: https://github.com/jonasbb/serde_with/issues/185\n"]
    pub mod serde_as { }
    #[doc =
    "# De/Serialize Transformations Available\n\nThis page lists the transformations implemented in this crate and supported by `serde_as`.\n\n1. [Base58 encode bytes](#base58-encode-bytes)\n1. [Base64 encode bytes](#base64-encode-bytes)\n2. [Big Array support](#big-array-support)\n3. [`bool` from integer](#bool-from-integer)\n4. [Borrow from the input for `Cow` type](#borrow-from-the-input-for-cow-type)\n5. [`Bytes` with more efficiency](#bytes-with-more-efficiency)\n6. [Convert to an intermediate type using `Into`](#convert-to-an-intermediate-type-using-into)\n7. [Convert to an intermediate type using `TryInto`](#convert-to-an-intermediate-type-using-tryinto)\n8. [`Default` from `null`](#default-from-null)\n9. [De/Serialize into `Vec`, ignoring errors](#deserialize-into-vec-ignoring-errors)\n10. [De/Serialize into a map, ignoring errors](#deserialize-into-a-map-ignoring-errors)\n11. [De/Serialize with `FromStr` and `Display`](#deserialize-with-fromstr-and-display)\n12. [`Duration` as seconds](#duration-as-seconds)\n13. [Hex encode bytes](#hex-encode-bytes)\n14. [Ignore deserialization errors](#ignore-deserialization-errors)\n15. [`Maps` to `Vec` of enums](#maps-to-vec-of-enums)\n16. [`Maps` to `Vec` of tuples](#maps-to-vec-of-tuples)\n17. [`NaiveDateTime` like UTC timestamp](#naivedatetime-like-utc-timestamp)\n18. [`None` as empty `String`](#none-as-empty-string)\n19. [One or many elements into `Vec`](#one-or-many-elements-into-vec)\n20. [Overwrite existing set values](#overwrite-existing-set-values)\n21. [Pick first successful deserialization](#pick-first-successful-deserialization)\n22. [Prefer the first map key when duplicates exist](#prefer-the-first-map-key-when-duplicates-exist)\n23. [Prevent duplicate map keys](#prevent-duplicate-map-keys)\n24. [Prevent duplicate set values](#prevent-duplicate-set-values)\n25. [Struct fields as map keys](#struct-fields-as-map-keys)\n26. [Timestamps as seconds since UNIX epoch](#timestamps-as-seconds-since-unix-epoch)\n27. [Value into JSON String](#value-into-json-string)\n28. [`Vec` of tuples to `Maps`](#vec-of-tuples-to-maps)\n29. [Well-known time formats for `OffsetDateTime`](#well-known-time-formats-for-offsetdatetime)\n30. [De/Serialize depending on `De/Serializer::is_human_readable`](#deserialize-depending-on-deserializeris_human_readable)\n\n## Base58 encode bytes\n\n[`Base58`]\n\nRequires the `base58` feature.\nThe character set and padding behavior can be configured.\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::base58::Base58\")]\nvalue: Vec<u8>,\n#[serde_as(as = \"Base58<Flickr>\")]\ncharset_flickr: Vec<u8>,\n\n// JSON\n\"value\": \"JxF12TrwUP45BMd\",\n\"charset_flickr\": \"iXf12sRWto45bmC\",\n```\n\n## Base64 encode bytes\n\n[`Base64`]\n\nRequires the `base64` feature.\nThe character set and padding behavior can be configured.\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::base64::Base64\")]\nvalue: Vec<u8>,\n#[serde_as(as = \"Base64<Bcrypt, Unpadded>\")]\nbcrypt_unpadded: Vec<u8>,\n\n// JSON\n\"value\": \"SGVsbG8gV29ybGQ=\",\n\"bcrypt_unpadded\": \"QETqZE6eT07wZEO\",\n```\n\n## Big Array support\n\nSupport for arrays of arbitrary size.\n\n```ignore\n// Rust\n#[serde_as(as = \"[[_; 64]; 33]\")]\nvalue: [[u8; 64]; 33],\n\n// JSON\n\"value\": [[0,0,0,0,0,...], [0,0,0,...], ...],\n```\n\n## `bool` from integer\n\nDeserialize an integer and convert it into a `bool`.\n[`BoolFromInt<Strict>`] (default) deserializes 0 to `false` and `1` to `true`, other numbers are errors.\n[`BoolFromInt<Flexible>`] deserializes any non-zero as `true`.\nSerialization only emits 0/1.\n\n```ignore\n// Rust\n#[serde_as(as = \"BoolFromInt\")] // BoolFromInt<Strict>\nb: bool,\n\n// JSON\n\"b\": 1,\n```\n\n## Borrow from the input for `Cow` type\n\nThe types `Cow<\'_, str>`, `Cow<\'_, [u8]>`, or `Cow<\'_, [u8; N]>` can borrow from the input, avoiding extra copies.\n\n```ignore\n// Rust\n#[serde_as(as = \"BorrowCow\")]\nvalue: Cow<\'a, str>,\n\n// JSON\n\"value\": \"foobar\",\n```\n\n## `Bytes` with more efficiency\n\n[`Bytes`]\n\nMore efficient serialization for byte slices and similar.\n\n```ignore\n// Rust\n#[serde_as(as = \"Bytes\")]\nvalue: Vec<u8>,\n\n// JSON\n\"value\": [0, 1, 2, 3, ...],\n```\n\n## Convert to an intermediate type using `Into`\n\n[`FromInto`]\n\n```ignore\n// Rust\n#[serde_as(as = \"FromInto<(u8, u8, u8)>\")]\nvalue: Rgb,\n\nimpl From<(u8, u8, u8)> for Rgb { ... }\nimpl From<Rgb> for (u8, u8, u8) { ... }\n\n// JSON\n\"value\": [128, 64, 32],\n```\n\n## Convert to an intermediate type using `TryInto`\n\n[`TryFromInto`]\n\n```ignore\n// Rust\n#[serde_as(as = \"TryFromInto<i8>\")]\nvalue: u8,\n\n// JSON\n\"value\": 127,\n```\n\n## `Default` from `null`\n\n[`DefaultOnNull`]\n\n```ignore\n// Rust\n#[serde_as(as = \"DefaultOnNull\")]\nvalue: u32,\n#[serde_as(as = \"DefaultOnNull<DisplayFromStr>\")]\nvalue2: u32,\n\n// JSON\n\"value\": 123,\n\"value2\": \"999\",\n\n// Deserializes null into the Default value, i.e.,\nnull => 0\n```\n\n## De/Serialize into `Vec`, ignoring errors\n\n[`VecSkipError`]\n\nFor formats with heterogeneously typed sequences, we can collect only the deserializable elements.\nThis is also useful for unknown enum variants.\n\n```ignore\n#[derive(serde::Deserialize)]\nenum Color {\n    Red,\n    Green,\n    Blue,\n}\n\n// JSON\n\"colors\": [\"Blue\", \"Yellow\", \"Green\"],\n\n// Rust\n#[serde_as(as = \"VecSkipError<_>\")]\ncolors: Vec<Color>,\n\n// => vec![Blue, Green]\n```\n\n## De/Serialize into a map, ignoring errors\n\n[`MapSkipError`]\n\nFor formats with heterogeneously typed maps, we can collect only the elements where both key and value are deserializable.\nThis is also useful in conjunction to `#[serde(flatten)]` to ignore some entries when capturing additional fields.\n\n```ignore\n// JSON\n\"value\": {\"0\": \"v0\", \"5\": \"v5\", \"str\": \"str\", \"10\": 2},\n\n// Rust\n#[serde_as(as = \"MapSkipError<DisplayFromStr, _>\")]\nvalue: BTreeMap<u32, String>,\n\n// Only deserializes entries with a numerical key and a string value, i.e.,\n{0 => \"v0\", 5 => \"v5\"}\n```\n\n## De/Serialize with `FromStr` and `Display`\n\nUseful if a type implements `FromStr` / `Display` but not `Deserialize` / `Serialize`.\n\n[`DisplayFromStr`]\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::DisplayFromStr\")]\nvalue: u128,\n#[serde_as(as = \"serde_with::DisplayFromStr\")]\nmime: mime::Mime,\n\n// JSON\n\"value\": \"340282366920938463463374607431768211455\",\n\"mime\": \"text/*\",\n```\n\n## `Duration` as seconds\n\n[`DurationSeconds`]\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::DurationSeconds<u64>\")]\nvalue: Duration,\n\n// JSON\n\"value\": 86400,\n```\n\n[`DurationSecondsWithFrac`] supports sub-second precision:\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::DurationSecondsWithFrac<f64>\")]\nvalue: Duration,\n\n// JSON\n\"value\": 1.234,\n```\n\nDifferent serialization formats are possible:\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::DurationSecondsWithFrac<String>\")]\nvalue: Duration,\n\n// JSON\n\"value\": \"1.234\",\n```\n\nThe same conversions are also implemented for [`chrono::Duration`] with the `chrono` feature.\n\nThe same conversions are also implemented for [`jiff::SignedDuration`] with the `jiff_0_2` feature.\n\nThe same conversions are also implemented for [`time::Duration`] with the `time_0_3` feature.\n\n## Hex encode bytes\n\n[`Hex`]\n\nRequires the `hex` feature.\nThe hex string can use upper- and lowercase characters.\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::hex::Hex\")]\nlowercase: Vec<u8>,\n#[serde_as(as = \"serde_with::hex::Hex<serde_with::formats::Uppercase>\")]\nuppercase: Vec<u8>,\n\n// JSON\n\"lowercase\": \"deadbeef\",\n\"uppercase\": \"DEADBEEF\",\n```\n\n## Ignore deserialization errors\n\nCheck the documentation for [`DefaultOnError`].\n\n## `Maps` to `Vec` of enums\n\n[`EnumMap`]\n\nCombine multiple enum values into a single map.\nThe key is the enum variant name, and the value is the variant value.\nThis only works with [*externally tagged*] enums, the default enum representation.\nOther forms cannot be supported.\n\n```ignore\nenum EnumValue {\n    Int(i32),\n    String(String),\n    Unit,\n    Tuple(i32, String),\n    Struct {\n        a: i32,\n        b: String,\n    },\n}\n\n// Rust\nstruct VecEnumValues (\n    #[serde_as(as = \"EnumMap\")]\n    Vec<EnumValue>,\n);\n\nVecEnumValues(vec![\n    EnumValue::Int(123),\n    EnumValue::String(\"Foo\".to_string()),\n    EnumValue::Unit,\n    EnumValue::Tuple(1, \"Bar\".to_string()),\n    EnumValue::Struct {\n        a: 666,\n        b: \"Baz\".to_string(),\n    },\n])\n\n// JSON\n{\n  \"Int\": 123,\n  \"String\": \"Foo\",\n  \"Unit\": null,\n  \"Tuple\": [\n    1,\n    \"Bar\",\n  ],\n  \"Struct\": {\n    \"a\": 666,\n    \"b\": \"Baz\",\n  }\n}\n```\n\n[*externally tagged*]: https://serde.rs/enum-representations.html#externally-tagged\n\n## `Maps` to `Vec` of tuples\n\n```ignore\n// Rust\n#[serde_as(as = \"Seq<(_, _)>\")] // also works with Vec\nvalue: HashMap<String, u32>, // also works with other maps like BTreeMap or IndexMap\n\n// JSON\n\"value\": [\n    [\"hello\", 1],\n    [\"world\", 2]\n],\n```\n\nThe [inverse operation](#vec-of-tuples-to-maps) is also available.\n\n## `NaiveDateTime` like UTC timestamp\n\nRequires the `chrono` feature.\n\n```ignore\n// Rust\n#[serde_as(as = \"chrono::DateTime<chrono::Utc>\")]\nvalue: chrono::NaiveDateTime,\n\n// JSON\n\"value\": \"1994-11-05T08:15:30Z\",\n                             ^ Pretend DateTime is UTC\n```\n\n## `None` as empty `String`\n\n[`NoneAsEmptyString`]\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::NoneAsEmptyString\")]\nvalue: Option<String>,\n\n// JSON\n\"value\": \"\", // converts to None\n\n\"value\": \"Hello World!\", // converts to Some\n```\n\n## `None` as zero for `Option<NonZero*>`\n\n[`NoneAsZero`]\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::NoneAsZero\")]\nvalue: Option<core::num::NonZeroU32>,\n\n// JSON\n\"value\": 0, // converts to None\n\n\"value\": 42, // converts to Some(NonZeroU32::new(42).unwrap())\n```\n\n## One or many elements into `Vec`\n\n[`OneOrMany`]\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::OneOrMany<_>\")]\nvalue: Vec<String>,\n\n// JSON\n\"value\": \"\", // Deserializes single elements\n\n\"value\": [\"Hello\", \"World!\"], // or lists of many\n```\n\n## Overwrite existing set values\n\n[`SetLastValueWins`]\n\nserdes default behavior for sets is to take the first value, when multiple \"equal\" values are inserted into a set.\nThis changes the logic to prefer the last value.\n\n## Pick first successful deserialization\n\n[`PickFirst`]\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::PickFirst<(_, serde_with::DisplayFromStr)>\")]\nvalue: u32,\n\n// JSON\n// serialize into\n\"value\": 666,\n// deserialize from either\n\"value\": 666,\n\"value\": \"666\",\n```\n\n## Prefer the first map key when duplicates exist\n\n[`MapFirstKeyWins`]\n\nSerde\'s default behavior is to take the last key-value combination, if multiple \"equal\" keys exist.\nThis changes the logic to instead prefer the first found key-value combination.\n\n## Prevent duplicate map keys\n\n[`MapPreventDuplicates`]\n\nError during deserialization, when duplicate map keys are detected.\n\n## Prevent duplicate set values\n\n[`SetPreventDuplicates`]\n\nError during deserialization, when duplicate set values are detected.\n\n## Struct fields as map keys\n\n[`KeyValueMap`]\n\nThis conversion is possible for structs and maps, using the `$key$` field.\nTuples, tuple structs, and sequences are supported by turning the first value into the map key.\n\nEach of the `SimpleStruct`s\n\n```ignore\n// Somewhere there is a collection:\n// #[serde_as(as = \"KeyValueMap<_>\")]\n// Vec<SimpleStruct>,\n\n#[derive(Serialize, Deserialize)]\nstruct SimpleStruct {\n    b: bool,\n    // The field named `$key$` will become the map key\n    #[serde(rename = \"$key$\")]\n    id: String,\n    i: i32,\n}\n```\n\nwill turn into a JSON snippet like this.\n\n```json\n\"id-0000\": {\n  \"b\": false,\n  \"i\": 123\n},\n```\n\n## Timestamps as seconds since UNIX epoch\n\n[`TimestampSeconds`]\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::TimestampSeconds<i64>\")]\nvalue: SystemTime,\n\n// JSON\n\"value\": 86400,\n```\n\n[`TimestampSecondsWithFrac`] supports sub-second precision:\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::TimestampSecondsWithFrac<f64>\")]\nvalue: SystemTime,\n\n// JSON\n\"value\": 1.234,\n```\n\nDifferent serialization formats are possible:\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::TimestampSecondsWithFrac<String>\")]\nvalue: SystemTime,\n\n// JSON\n\"value\": \"1.234\",\n```\n\nThe same conversions are also implemented for [`chrono::DateTime<Utc>`], [`chrono::DateTime<Local>`], and [`chrono::NaiveDateTime`] with the `chrono` feature.\n\nThe conversions are available for [`jiff::Timestamp`], [`jiff::Zoned`], and [`jiff::civil::DateTime`] with the `jiff_0_2` feature enabled.\n\nThe conversions are available for [`time::OffsetDateTime`] and [`time::PrimitiveDateTime`] with the `time_0_3` feature enabled.\n\n## Value into JSON String\n\nSome JSON APIs are weird and return a JSON encoded string in a JSON response\n\n[`JsonString`]\n\nRequires the `json` feature.\n\n```ignore\n// Rust\n#[derive(Deserialize, Serialize)]\nstruct OtherStruct {\n    value: usize,\n}\n\n#[serde_as(as = \"serde_with::json::JsonString\")]\nvalue: OtherStruct,\n\n// JSON\n\"value\": \"{\\\"value\\\":5}\",\n```\n\n```ignore\n#[serde_as(as = \"JsonString<Vec<(JsonString, _)>>\")]\nvalue: BTreeMap<[u8; 2], u32>,\n\n// JSON\n{\"value\":\"[[\\\"[1,2]\\\",3],[\\\"[4,5]\\\",6]]\"}\n```\n\n## `Vec` of tuples to `Maps`\n\n```ignore\n// Rust\n#[serde_as(as = \"Map<_, _>\")] // also works with BTreeMap and HashMap\nvalue: Vec<(String, u32)>,\n\n// JSON\n\"value\": {\n    \"hello\": 1,\n    \"world\": 2\n},\n```\n\nThis operation is also available for other sequence types.\nThis includes `BinaryHeap<(K, V)>`, `BTreeSet<(K, V)>`, `HashSet<(K, V)>`, `LinkedList<(K, V)>`, `VecDeque<(K, V)>`, `Option<(K, V)>` and `[(K, V); N]` for all sizes of N.\n\nThe [inverse operation](#maps-to-vec-of-tuples) is also available.\n\n## Well-known time formats for `OffsetDateTime`\n\n[`time::OffsetDateTime`] can be serialized in string format in different well-known formats.\nThree formats are supported, [`time::format_description::well_known::Rfc2822`], [`time::format_description::well_known::Rfc3339`], and [`time::format_description::well_known::Iso8601`].\n\n```ignore\n// Rust\n#[serde_as(as = \"time::format_description::well_known::Rfc2822\")]\nrfc_2822: OffsetDateTime,\n#[serde_as(as = \"time::format_description::well_known::Rfc3339\")]\nrfc_3339: OffsetDateTime,\n#[serde_as(as = \"time::format_description::well_known::Iso8601<Config>\")]\niso_8601: OffsetDateTime,\n\n// JSON\n\"rfc_2822\": \"Fri, 21 Nov 1997 09:55:06 -0600\",\n\"rfc_3339\": \"1997-11-21T09:55:06-06:00\",\n\"iso_8061\": \"1997-11-21T09:55:06-06:00\",\n```\n\nThese conversions are available with the `time_0_3` feature flag.\n\n## De/Serialize depending on `De/Serializer::is_human_readable`\n\nUsed to specify different transformations for text-based and binary formats.\n\n[`IfIsHumanReadable`]\n\n```ignore\n// Rust\n#[serde_as(as = \"serde_with::IfIsHumanReadable<serde_with::DisplayFromStr>\")]\nvalue: u128,\n\n// JSON\n\"value\": \"340282366920938463463374607431768211455\",\n```\n\n[`Base58`]: crate::base58::Base58\n[`Base64`]: crate::base64::Base64\n[`BoolFromInt<Flexible>`]: crate::BoolFromInt\n[`BoolFromInt<Strict>`]: crate::BoolFromInt\n[`Bytes`]: crate::Bytes\n[`chrono::DateTime<Local>`]: chrono_0_4::DateTime\n[`chrono::DateTime<Utc>`]: chrono_0_4::DateTime\n[`chrono::Duration`]: chrono_0_4::Duration\n[`chrono::NaiveDateTime`]: chrono_0_4::NaiveDateTime\n[`DefaultOnError`]: crate::DefaultOnError\n[`DefaultOnNull`]: crate::DefaultOnNull\n[`DisplayFromStr`]: crate::DisplayFromStr\n[`DurationSeconds`]: crate::DurationSeconds\n[`DurationSecondsWithFrac`]: crate::DurationSecondsWithFrac\n[`EnumMap`]: crate::EnumMap\n[`FromInto`]: crate::FromInto\n[`Hex`]: crate::hex::Hex\n[`IfIsHumanReadable`]: crate::IfIsHumanReadable\n[`jiff::civil::DateTime`]: jiff_0_2::civil::DateTime\n[`jiff::SignedDuration`]: jiff_0_2::SignedDuration\n[`jiff::Timestamp`]: jiff_0_2::Timestamp\n[`jiff::Zoned`]: jiff_0_2::Zoned\n[`JsonString`]: crate::json::JsonString\n[`KeyValueMap`]: crate::KeyValueMap\n[`MapFirstKeyWins`]: crate::MapFirstKeyWins\n[`MapPreventDuplicates`]: crate::MapPreventDuplicates\n[`NoneAsEmptyString`]: crate::NoneAsEmptyString\n[`NoneAsZero`]: crate::NoneAsZero\n[`OneOrMany`]: crate::OneOrMany\n[`PickFirst`]: crate::PickFirst\n[`SetLastValueWins`]: crate::SetLastValueWins\n[`SetPreventDuplicates`]: crate::SetPreventDuplicates\n[`time::Duration`]: time_0_3::Duration\n[`time::format_description::well_known::Iso8601`]: time_0_3::format_description::well_known::Iso8601\n[`time::format_description::well_known::Rfc2822`]: time_0_3::format_description::well_known::Rfc2822\n[`time::format_description::well_known::Rfc3339`]: time_0_3::format_description::well_known::Rfc3339\n[`time::OffsetDateTime`]: time_0_3::OffsetDateTime\n[`time::PrimitiveDateTime`]: time_0_3::PrimitiveDateTime\n[`TimestampSeconds`]: crate::TimestampSeconds\n[`TimestampSecondsWithFrac`]: crate::TimestampSecondsWithFrac\n[`TryFromInto`]: crate::TryFromInto\n[`VecSkipError`]: crate::VecSkipError\n[`MapSkipError`]: crate::MapSkipError\n"]
    pub mod serde_as_transformations { }
}generate_guide! {
378    pub mod guide {
379        @code pub mod feature_flags;
380        pub mod serde_as;
381        pub mod serde_as_transformations;
382    }
383}
384
385pub(crate) mod prelude {
386    #![allow(unused_imports)]
387
388    pub(crate) use crate::utils::duration::{DurationSigned, Sign};
389    pub use crate::{de::*, ser::*, *};
390    #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
391    pub use alloc::sync::{Arc, Weak as ArcWeak};
392    #[cfg(feature = "alloc")]
393    pub use alloc::{
394        borrow::{Cow, ToOwned},
395        boxed::Box,
396        collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque},
397        rc::{Rc, Weak as RcWeak},
398        string::{String, ToString},
399        vec::Vec,
400    };
401    pub use core::{
402        cell::{Cell, RefCell},
403        convert::{TryFrom, TryInto},
404        fmt::{self, Display},
405        hash::{BuildHasher, Hash},
406        marker::PhantomData,
407        ops::{Bound, Range, RangeFrom, RangeInclusive, RangeTo},
408        option::Option,
409        pin::Pin,
410        result::Result,
411        str::{self, FromStr},
412        time::Duration,
413    };
414    pub use serde_core::{
415        de::{
416            Deserialize, DeserializeOwned, DeserializeSeed, Deserializer, EnumAccess,
417            Error as DeError, Expected, IgnoredAny, IntoDeserializer, MapAccess, SeqAccess,
418            Unexpected, VariantAccess, Visitor,
419        },
420        forward_to_deserialize_any,
421        ser::{
422            Error as SerError, Impossible, Serialize, SerializeMap, SerializeSeq, SerializeStruct,
423            SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant,
424            Serializer,
425        },
426    };
427    #[cfg(feature = "std")]
428    pub use std::{
429        collections::{HashMap, HashSet},
430        sync::{Mutex, RwLock},
431        time::SystemTime,
432    };
433}
434
435/// This module is not part of the public API
436///
437/// Do not rely on any exports.
438#[doc(hidden)]
439pub mod __private__ {
440    pub use crate::prelude::*;
441}
442
443#[cfg(feature = "alloc")]
444#[doc(inline)]
445pub use crate::enum_map::EnumMap;
446#[cfg(feature = "alloc")]
447#[doc(inline)]
448pub use crate::key_value_map::KeyValueMap;
449#[doc(inline)]
450pub use crate::{de::DeserializeAs, ser::SerializeAs};
451use core::marker::PhantomData;
452// Re-Export all proc_macros, as these should be seen as part of the serde_with crate
453#[cfg(feature = "macros")]
454#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
455#[doc(inline)]
456pub use serde_with_macros::*;
457
458/// Adapter to convert from `serde_as` to the serde traits.
459///
460/// The `As` type adapter allows using types which implement [`DeserializeAs`] or [`SerializeAs`] in place of serde's `with` annotation.
461/// The `with` annotation allows running custom code when de/serializing, however it is quite inflexible.
462/// The traits [`DeserializeAs`]/[`SerializeAs`] are more flexible, as they allow composition and nesting of types to create more complex de/serialization behavior.
463/// However, they are not directly compatible with serde, as they are not provided by serde.
464/// The `As` type adapter makes them compatible, by forwarding the function calls to `serialize`/`deserialize` to the corresponding functions `serialize_as` and `deserialize_as`.
465///
466/// It is not required to use this type directly.
467/// Instead, it is highly encouraged to use the [`#[serde_as]`][serde_as] attribute since it includes further usability improvements.
468/// If the use of the use of the proc-macro is not acceptable, then `As` can be used directly with serde.
469///
470/// ```rust
471/// # #[cfg(feature = "alloc")] {
472/// # use serde::{Deserialize, Serialize};
473/// # use serde_with::{As, DisplayFromStr};
474/// #
475/// # #[allow(dead_code)]
476/// #[derive(Deserialize, Serialize)]
477/// # struct S {
478/// // Serialize numbers as sequence of strings, using Display and FromStr
479/// #[serde(with = "As::<Vec<DisplayFromStr>>")]
480/// field: Vec<u8>,
481/// # }
482/// # }
483/// ```
484/// If the normal `Deserialize`/`Serialize` traits should be used, the placeholder type [`Same`] can be used.
485/// It implements [`DeserializeAs`][]/[`SerializeAs`][], when the underlying type implements `Deserialize`/`Serialize`.
486///
487/// ```rust
488/// # #[cfg(feature = "alloc")] {
489/// # use serde::{Deserialize, Serialize};
490/// # use serde_with::{As, DisplayFromStr, Same};
491/// # use std::collections::BTreeMap;
492/// #
493/// # #[allow(dead_code)]
494/// #[derive(Deserialize, Serialize)]
495/// # struct S {
496/// // Serialize map, turn keys into strings but keep type of value
497/// #[serde(with = "As::<BTreeMap<DisplayFromStr, Same>>")]
498/// field: BTreeMap<u8, i32>,
499/// # }
500/// # }
501/// ```
502///
503/// [serde_as]: https://docs.rs/serde_with/3.23.0/serde_with/attr.serde_as.html
504pub struct As<T: ?Sized>(PhantomData<T>);
505
506/// Adapter to convert from `serde_as` to the serde traits.
507///
508/// This is the counter-type to [`As`][].
509/// It can be used whenever a type implementing [`DeserializeAs`]/[`SerializeAs`] is required but the normal [`Deserialize`](::serde_core::Deserialize)/[`Serialize`](::serde_core::Serialize) traits should be used.
510/// Check [`As`] for an example.
511pub struct Same;
512
513/// De/Serialize using [`Display`] and [`FromStr`] implementation
514///
515/// This allows deserializing a string as a number.
516/// It can be very useful for serialization formats like JSON, which do not support integer
517/// numbers and have to resort to strings to represent them.
518///
519/// Another use case is types with [`Display`] and [`FromStr`] implementations, but without serde
520/// support, which can be found in some crates.
521///
522/// If you control the type you want to de/serialize, you can instead use the two derive macros, [`SerializeDisplay`] and [`DeserializeFromStr`].
523/// They properly implement the traits [`Serialize`](::serde_core::Serialize) and [`Deserialize`](::serde_core::Deserialize) such that user of the type no longer have to use the `serde_as` system.
524///
525/// # Examples
526///
527/// ```rust
528/// # #[cfg(feature = "macros")] {
529/// # use serde::{Deserialize, Serialize};
530/// # use serde_json::json;
531/// # use serde_with::{serde_as, DisplayFromStr};
532/// #
533/// #[serde_as]
534/// #[derive(Deserialize, Serialize)]
535/// struct A {
536///     #[serde_as(as = "DisplayFromStr")]
537///     mime: mime::Mime,
538///     #[serde_as(as = "DisplayFromStr")]
539///     number: u32,
540/// }
541///
542/// let v: A = serde_json::from_value(json!({
543///     "mime": "text/plain",
544///     "number": "159",
545/// })).unwrap();
546/// assert_eq!(mime::TEXT_PLAIN, v.mime);
547/// assert_eq!(159, v.number);
548///
549/// let x = A {
550///     mime: mime::STAR_STAR,
551///     number: 777,
552/// };
553/// assert_eq!(json!({ "mime": "*/*", "number": "777" }), serde_json::to_value(x).unwrap());
554/// # }
555/// ```
556///
557/// [`Display`]: std::fmt::Display
558/// [`FromStr`]: std::str::FromStr
559pub struct DisplayFromStr;
560
561/// Use the first format if [`De/Serializer::is_human_readable`], otherwise use the second
562///
563/// If the second format is not specified, the normal
564/// [`Deserialize`](::serde_core::Deserialize)/[`Serialize`](::serde_core::Serialize) traits are used.
565///
566/// # Examples
567///
568/// ```rust
569/// # #[cfg(feature = "macros")] {
570/// # use serde::{Deserialize, Serialize};
571/// # use serde_json::json;
572/// # use serde_with::{serde_as, DisplayFromStr, IfIsHumanReadable, DurationMilliSeconds, DurationSeconds};
573/// use std::time::Duration;
574///
575/// #[serde_as]
576/// #[derive(Deserialize, Serialize)]
577/// struct A {
578///     #[serde_as(as = "IfIsHumanReadable<DisplayFromStr>")]
579///     number: u32,
580/// }
581/// let x = A {
582///     number: 777,
583/// };
584/// assert_eq!(json!({ "number": "777" }), serde_json::to_value(&x).unwrap());
585/// assert_eq!(vec![145, 205, 3, 9], rmp_serde::to_vec(&x).unwrap());
586///
587/// #[serde_as]
588/// #[derive(Deserialize, Serialize)]
589/// struct B {
590///     #[serde_as(as = "IfIsHumanReadable<DurationMilliSeconds, DurationSeconds>")]
591///     duration: Duration,
592/// }
593/// let x = B {
594///     duration: Duration::from_millis(1500),
595/// };
596/// assert_eq!(json!({ "duration": 1500 }), serde_json::to_value(&x).unwrap());
597/// assert_eq!(vec![145, 2], rmp_serde::to_vec(&x).unwrap());
598/// # }
599/// ```
600/// [`De/Serializer::is_human_readable`]: serde_core::Serializer::is_human_readable
601/// [`is_human_readable`]: serde_core::Serializer::is_human_readable
602pub struct IfIsHumanReadable<H, F = Same>(PhantomData<H>, PhantomData<F>);
603
604/// De/Serialize a [`Option<String>`] type while transforming the empty string to [`None`]
605///
606/// Convert an [`Option<T>`] from/to string using [`FromStr`] and [`Display`](::core::fmt::Display) implementations.
607/// An empty string is deserialized as [`None`] and a [`None`] vice versa.
608///
609/// # Examples
610///
611/// ```
612/// # #[cfg(feature = "macros")] {
613/// # use serde::{Deserialize, Serialize};
614/// # use serde_json::json;
615/// # use serde_with::{serde_as, NoneAsEmptyString};
616/// #
617/// #[serde_as]
618/// #[derive(Deserialize, Serialize)]
619/// struct A {
620///     #[serde_as(as = "NoneAsEmptyString")]
621///     tags: Option<String>,
622/// }
623///
624/// let v: A = serde_json::from_value(json!({ "tags": "" })).unwrap();
625/// assert_eq!(None, v.tags);
626///
627/// let v: A = serde_json::from_value(json!({ "tags": "Hi" })).unwrap();
628/// assert_eq!(Some("Hi".to_string()), v.tags);
629///
630/// let x = A {
631///     tags: Some("This is text".to_string()),
632/// };
633/// assert_eq!(json!({ "tags": "This is text" }), serde_json::to_value(x).unwrap());
634///
635/// let x = A {
636///     tags: None,
637/// };
638/// assert_eq!(json!({ "tags": "" }), serde_json::to_value(x).unwrap());
639/// # }
640/// ```
641///
642/// [`FromStr`]: std::str::FromStr
643pub struct NoneAsEmptyString;
644
645/// De/Serialize an [`Option<NonZero*>`] losslessly as the inner integer
646///
647/// Serde natively supports [`NonZeroU8`] and friends, but rejects `0` during deserialization.
648/// This adapter treats `0` as [`None`] and any other value as [`Some`], allowing the wire format
649/// to always be a plain integer.
650///
651/// Supported in-memory types are [`Option<NonZeroU8>`], [`Option<NonZeroU16>`], [`Option<NonZeroU32>`],
652/// [`Option<NonZeroU64>`], [`Option<NonZeroU128>`], [`Option<NonZeroUsize>`], [`Option<NonZeroI8>`],
653/// [`Option<NonZeroI16>`], [`Option<NonZeroI32>`], [`Option<NonZeroI64>`], [`Option<NonZeroI128>`],
654/// and [`Option<NonZeroIsize>`].
655///
656/// # Examples
657///
658/// ```
659/// # #[cfg(feature = "macros")] {
660/// # use core::num::NonZeroU32;
661/// # use serde::{Deserialize, Serialize};
662/// # use serde_json::json;
663/// # use serde_with::{serde_as, NoneAsZero};
664/// #
665/// #[serde_as]
666/// # #[derive(Debug, PartialEq)]
667/// #[derive(Deserialize, Serialize)]
668/// struct Data {
669///     #[serde_as(as = "NoneAsZero")]
670///     value: Option<NonZeroU32>,
671/// }
672///
673/// let data = Data { value: NonZeroU32::new(7) };
674/// assert_eq!(json!({"value": 7}), serde_json::to_value(&data).unwrap());
675/// assert_eq!(data, serde_json::from_value(json!({"value": 7})).unwrap());
676///
677/// let none = Data { value: None };
678/// assert_eq!(json!({"value": 0}), serde_json::to_value(&none).unwrap());
679/// assert_eq!(none, serde_json::from_value(json!({"value": 0})).unwrap());
680/// # }
681/// ```
682///
683/// [`NonZeroU8`]: core::num::NonZeroU8
684/// [`Option<NonZeroU8>`]: core::num::NonZeroU8
685/// [`Option<NonZeroU16>`]: core::num::NonZeroU16
686/// [`Option<NonZeroU32>`]: core::num::NonZeroU32
687/// [`Option<NonZeroU64>`]: core::num::NonZeroU64
688/// [`Option<NonZeroU128>`]: core::num::NonZeroU128
689/// [`Option<NonZeroUsize>`]: core::num::NonZeroUsize
690/// [`Option<NonZeroI8>`]: core::num::NonZeroI8
691/// [`Option<NonZeroI16>`]: core::num::NonZeroI16
692/// [`Option<NonZeroI32>`]: core::num::NonZeroI32
693/// [`Option<NonZeroI64>`]: core::num::NonZeroI64
694/// [`Option<NonZeroI128>`]: core::num::NonZeroI128
695/// [`Option<NonZeroIsize>`]: core::num::NonZeroIsize
696pub struct NoneAsZero;
697
698/// Deserialize value and return [`Default`] on error
699///
700/// The main use case is ignoring error while deserializing.
701/// Instead of erroring, it simply deserializes the [`Default`] variant of the type.
702/// It is not possible to find the error location, i.e., which field had a deserialization error, with this method.
703/// During serialization this wrapper does nothing.
704/// The serialization behavior of the underlying type is preserved.
705/// The type must implement [`Default`] for this conversion to work.
706///
707/// # Examples
708///
709/// ```
710/// # #[cfg(feature = "macros")] {
711/// # use serde::Deserialize;
712/// # use serde_with::{serde_as, DefaultOnError};
713/// #
714/// #[serde_as]
715/// #[derive(Deserialize, Debug)]
716/// struct A {
717///     #[serde_as(deserialize_as = "DefaultOnError")]
718///     value: u32,
719/// }
720///
721/// let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
722/// assert_eq!(123, a.value);
723///
724/// // null is of invalid type
725/// let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
726/// assert_eq!(0, a.value);
727///
728/// // String is of invalid type
729/// let a: A = serde_json::from_str(r#"{"value": "123"}"#).unwrap();
730/// assert_eq!(0, a.value);
731///
732/// // Map is of invalid type
733/// let a: A = dbg!(serde_json::from_str(r#"{"value": {}}"#)).unwrap();
734/// assert_eq!(0, a.value);
735///
736/// // Missing entries still cause errors
737/// assert!(serde_json::from_str::<A>(r#"{  }"#).is_err());
738/// # }
739/// ```
740///
741/// Deserializing missing values can be supported by adding the `default` field attribute:
742///
743/// ```
744/// # #[cfg(feature = "macros")] {
745/// # use serde::Deserialize;
746/// # use serde_with::{serde_as, DefaultOnError};
747/// #
748/// #[serde_as]
749/// #[derive(Deserialize)]
750/// struct B {
751///     #[serde_as(deserialize_as = "DefaultOnError")]
752///     #[serde(default)]
753///     value: u32,
754/// }
755///
756/// let b: B = serde_json::from_str(r#"{  }"#).unwrap();
757/// assert_eq!(0, b.value);
758/// # }
759/// ```
760///
761/// `DefaultOnError` can be combined with other conversion methods.
762/// In this example, we deserialize a `Vec`, each element is deserialized from a string.
763/// If the string does not parse as a number, then we get the default value of 0.
764///
765/// ```rust
766/// # #[cfg(feature = "macros")] {
767/// # use serde::{Deserialize, Serialize};
768/// # use serde_json::json;
769/// # use serde_with::{serde_as, DefaultOnError, DisplayFromStr};
770/// #
771/// #[serde_as]
772/// #[derive(Serialize, Deserialize)]
773/// struct C {
774///     #[serde_as(as = "Vec<DefaultOnError<DisplayFromStr>>")]
775///     value: Vec<u32>,
776/// }
777///
778/// let c: C = serde_json::from_value(json!({
779///     "value": ["1", "2", "a3", "", {}, "6"]
780/// })).unwrap();
781/// assert_eq!(vec![1, 2, 0, 0, 0, 6], c.value);
782/// # }
783/// ```
784#[cfg(feature = "alloc")]
785pub struct DefaultOnError<T = Same>(PhantomData<T>);
786
787/// Deserialize [`Default`] from `null` values
788///
789/// Instead of erroring on `null` values, it simply deserializes the [`Default`] variant of the type.
790/// During serialization this wrapper does nothing.
791/// The serialization behavior of the underlying type is preserved.
792/// The type must implement [`Default`] for this conversion to work.
793///
794/// # Examples
795///
796/// ```
797/// # #[cfg(feature = "macros")] {
798/// # use serde::Deserialize;
799/// # use serde_with::{serde_as, DefaultOnNull};
800/// #
801/// #[serde_as]
802/// #[derive(Deserialize, Debug)]
803/// struct A {
804///     #[serde_as(deserialize_as = "DefaultOnNull")]
805///     value: u32,
806/// }
807///
808/// let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
809/// assert_eq!(123, a.value);
810///
811/// // null values are deserialized into the default, here 0
812/// let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
813/// assert_eq!(0, a.value);
814/// # }
815/// ```
816///
817/// `DefaultOnNull` can be combined with other conversion methods.
818/// In this example, we deserialize a `Vec`, each element is deserialized from a string.
819/// If we encounter null, then we get the default value of 0.
820///
821/// ```rust
822/// # #[cfg(feature = "macros")] {
823/// # use serde::{Deserialize, Serialize};
824/// # use serde_json::json;
825/// # use serde_with::{serde_as, DefaultOnNull, DisplayFromStr};
826/// #
827/// #[serde_as]
828/// #[derive(Serialize, Deserialize)]
829/// struct C {
830///     #[serde_as(as = "Vec<DefaultOnNull<DisplayFromStr>>")]
831///     value: Vec<u32>,
832/// }
833///
834/// let c: C = serde_json::from_value(json!({
835///     "value": ["1", "2", null, null, "5"]
836/// })).unwrap();
837/// assert_eq!(vec![1, 2, 0, 0, 5], c.value);
838/// # }
839/// ```
840pub struct DefaultOnNull<T = Same>(PhantomData<T>);
841
842/// Deserialize from bytes or string
843///
844/// Any Rust [`String`] can be converted into bytes, i.e., `Vec<u8>`.
845/// Accepting both as formats while deserializing can be helpful while interacting with language
846/// which have a looser definition of string than Rust.
847///
848/// # Example
849/// ```rust
850/// # #[cfg(feature = "macros")] {
851/// # use serde::{Deserialize, Serialize};
852/// # use serde_json::json;
853/// # use serde_with::{serde_as, BytesOrString};
854/// #
855/// #[serde_as]
856/// #[derive(Deserialize, Serialize)]
857/// struct A {
858///     #[serde_as(as = "BytesOrString")]
859///     bytes_or_string: Vec<u8>,
860/// }
861///
862/// // Here we deserialize from a byte array ...
863/// let j = json!({
864///   "bytes_or_string": [
865///     0,
866///     1,
867///     2,
868///     3
869///   ]
870/// });
871///
872/// let a: A = serde_json::from_value(j.clone()).unwrap();
873/// assert_eq!(vec![0, 1, 2, 3], a.bytes_or_string);
874///
875/// // and serialization works too.
876/// assert_eq!(j, serde_json::to_value(&a).unwrap());
877///
878/// // But we also support deserializing from a String
879/// let j = json!({
880///   "bytes_or_string": "✨Works!"
881/// });
882///
883/// let a: A = serde_json::from_value(j).unwrap();
884/// assert_eq!("✨Works!".as_bytes(), &*a.bytes_or_string);
885/// # }
886/// ```
887/// [`String`]: std::string::String
888#[cfg(feature = "alloc")]
889pub struct BytesOrString;
890
891/// De/Serialize Durations as number of seconds.
892///
893/// De/serialize durations as number of seconds with sub-second precision.
894/// Sub-second precision is *only* supported for [`DurationSecondsWithFrac`], but not for [`DurationSeconds`].
895/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
896///
897/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
898/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `u64` deserialization from a `f64` will error.
899/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct duration and allows deserialization from any type.
900/// For example, deserializing `DurationSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
901/// Serialization of integers will round the duration to the nearest value.
902///
903/// This type also supports [`chrono::Duration`] with the `chrono_0_4`-[feature flag].
904/// This type also supports [`jiff::SignedDuration`][::jiff_0_2::SignedDuration] with the `jiff_0_2`-[feature flag].
905/// This type also supports [`time::Duration`][::time_0_3::Duration] with the `time_0_3`-[feature flag].
906///
907/// This table lists the available `FORMAT`s for the different duration types.
908/// The `FORMAT` specifier defaults to `u64`/`f64`.
909///
910/// | Duration Type          | Converter                 | Available `FORMAT`s      |
911/// | ---------------------- | ------------------------- | ------------------------ |
912/// | `std::time::Duration`  | `DurationSeconds`         | *`u64`*, `f64`, `String` |
913/// | `std::time::Duration`  | `DurationSecondsWithFrac` | *`f64`*, `String`        |
914/// | `chrono::Duration`     | `DurationSeconds`         | `i64`, `f64`, `String`   |
915/// | `chrono::Duration`     | `DurationSecondsWithFrac` | *`f64`*, `String`        |
916/// | `jiff::SignedDuration` | `DurationSeconds`         | `i64`, `f64`, `String`   |
917/// | `jiff::SignedDuration` | `DurationSecondsWithFrac` | *`f64`*, `String`        |
918/// | `time::Duration`       | `DurationSeconds`         | `i64`, `f64`, `String`   |
919/// | `time::Duration`       | `DurationSecondsWithFrac` | *`f64`*, `String`        |
920///
921/// # Examples
922///
923/// ```rust
924/// # #[cfg(feature = "macros")] {
925/// # use serde::{Deserialize, Serialize};
926/// # use serde_json::json;
927/// # use serde_with::{serde_as, DurationSeconds};
928/// use std::time::Duration;
929///
930/// #[serde_as]
931/// # #[derive(Debug, PartialEq)]
932/// #[derive(Deserialize, Serialize)]
933/// struct Durations {
934///     #[serde_as(as = "DurationSeconds<u64>")]
935///     d_u64: Duration,
936///     #[serde_as(as = "DurationSeconds<f64>")]
937///     d_f64: Duration,
938///     #[serde_as(as = "DurationSeconds<String>")]
939///     d_string: Duration,
940/// }
941///
942/// // Serialization
943/// // See how the values get rounded, since subsecond precision is not allowed.
944///
945/// let d = Durations {
946///     d_u64: Duration::new(12345, 0), // Create from seconds and nanoseconds
947///     d_f64: Duration::new(12345, 500_000_000),
948///     d_string: Duration::new(12345, 999_999_999),
949/// };
950/// // Observe the different data types
951/// let expected = json!({
952///     "d_u64": 12345,
953///     "d_f64": 12346.0,
954///     "d_string": "12346",
955/// });
956/// assert_eq!(expected, serde_json::to_value(d).unwrap());
957///
958/// // Deserialization works too
959/// // Subsecond precision in numbers will be rounded away
960///
961/// let json = json!({
962///     "d_u64": 12345,
963///     "d_f64": 12345.5,
964///     "d_string": "12346",
965/// });
966/// let expected = Durations {
967///     d_u64: Duration::new(12345, 0), // Create from seconds and nanoseconds
968///     d_f64: Duration::new(12346, 0),
969///     d_string: Duration::new(12346, 0),
970/// };
971/// assert_eq!(expected, serde_json::from_value(json).unwrap());
972/// # }
973/// ```
974///
975/// [`chrono::Duration`] is also supported when using the `chrono_0_4` feature.
976/// It is a signed duration, thus can be de/serialized as an `i64` instead of a `u64`.
977///
978/// ```rust
979/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
980/// # use serde::{Deserialize, Serialize};
981/// # use serde_json::json;
982/// # use serde_with::{serde_as, DurationSeconds};
983/// # use chrono_0_4::Duration;
984/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
985/// use chrono::Duration;
986/// # */
987///
988/// #[serde_as]
989/// # #[derive(Debug, PartialEq)]
990/// #[derive(Deserialize, Serialize)]
991/// struct Durations {
992///     #[serde_as(as = "DurationSeconds<i64>")]
993///     d_i64: Duration,
994///     #[serde_as(as = "DurationSeconds<f64>")]
995///     d_f64: Duration,
996///     #[serde_as(as = "DurationSeconds<String>")]
997///     d_string: Duration,
998/// }
999///
1000/// // Serialization
1001/// // See how the values get rounded, since subsecond precision is not allowed.
1002///
1003/// let d = Durations {
1004///     d_i64: Duration::seconds(-12345),
1005///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
1006///     d_string: Duration::seconds(12345) + Duration::nanoseconds(999_999_999),
1007/// };
1008/// // Observe the different data types
1009/// let expected = json!({
1010///     "d_i64": -12345,
1011///     "d_f64": -12345.0,
1012///     "d_string": "12346",
1013/// });
1014/// assert_eq!(expected, serde_json::to_value(d).unwrap());
1015///
1016/// // Deserialization works too
1017/// // Subsecond precision in numbers will be rounded away
1018///
1019/// let json = json!({
1020///     "d_i64": -12345,
1021///     "d_f64": -12345.5,
1022///     "d_string": "12346",
1023/// });
1024/// let expected = Durations {
1025///     d_i64: Duration::seconds(-12345),
1026///     d_f64: Duration::seconds(-12346),
1027///     d_string: Duration::seconds(12346),
1028/// };
1029/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1030/// # }
1031/// ```
1032///
1033/// [`chrono::Duration`]: ::chrono_0_4::Duration
1034/// [feature flag]: https://docs.rs/serde_with/3.23.0/serde_with/guide/feature_flags/index.html
1035pub struct DurationSeconds<
1036    FORMAT: formats::Format = u64,
1037    STRICTNESS: formats::Strictness = formats::Strict,
1038>(PhantomData<(FORMAT, STRICTNESS)>);
1039
1040/// De/Serialize Durations as number of seconds.
1041///
1042/// De/serialize durations as number of seconds with subsecond precision.
1043/// Subsecond precision is *only* supported for [`DurationSecondsWithFrac`], but not for [`DurationSeconds`].
1044/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
1045/// Serialization of integers will round the duration to the nearest value.
1046///
1047/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
1048/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `u64` deserialization from a `f64` will error.
1049/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct duration and allows deserialization from any type.
1050/// For example, deserializing `DurationSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
1051///
1052/// This type also supports [`chrono::Duration`] with the `chrono`-[feature flag].
1053/// This type also supports [`jiff::SignedDuration`][::jiff_0_2::SignedDuration] with the `jiff_0_2`-[feature flag].
1054/// This type also supports [`time::Duration`][::time_0_3::Duration] with the `time_0_3`-[feature flag].
1055///
1056/// This table lists the available `FORMAT`s for the different duration types.
1057/// The `FORMAT` specifier defaults to `u64`/`f64`.
1058///
1059/// | Duration Type          | Converter                 | Available `FORMAT`s      |
1060/// | ---------------------- | ------------------------- | ------------------------ |
1061/// | `std::time::Duration`  | `DurationSeconds`         | *`u64`*, `f64`, `String` |
1062/// | `std::time::Duration`  | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1063/// | `chrono::Duration`     | `DurationSeconds`         | `i64`, `f64`, `String`   |
1064/// | `chrono::Duration`     | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1065/// | `jiff::SignedDuration` | `DurationSeconds`         | `i64`, `f64`, `String`   |
1066/// | `jiff::SignedDuration` | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1067/// | `time::Duration`       | `DurationSeconds`         | `i64`, `f64`, `String`   |
1068/// | `time::Duration`       | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1069///
1070/// # Examples
1071///
1072/// ```rust
1073/// # #[cfg(feature = "macros")] {
1074/// # use serde::{Deserialize, Serialize};
1075/// # use serde_json::json;
1076/// # use serde_with::{serde_as, DurationSecondsWithFrac};
1077/// use std::time::Duration;
1078///
1079/// #[serde_as]
1080/// # #[derive(Debug, PartialEq)]
1081/// #[derive(Deserialize, Serialize)]
1082/// struct Durations {
1083///     #[serde_as(as = "DurationSecondsWithFrac<f64>")]
1084///     d_f64: Duration,
1085///     #[serde_as(as = "DurationSecondsWithFrac<String>")]
1086///     d_string: Duration,
1087/// }
1088///
1089/// // Serialization
1090/// // See how the values get rounded, since subsecond precision is not allowed.
1091///
1092/// let d = Durations {
1093///     d_f64: Duration::new(12345, 500_000_000), // Create from seconds and nanoseconds
1094///     d_string: Duration::new(12345, 999_999_000),
1095/// };
1096/// // Observe the different data types
1097/// let expected = json!({
1098///     "d_f64": 12345.5,
1099///     "d_string": "12345.999999",
1100/// });
1101/// assert_eq!(expected, serde_json::to_value(d).unwrap());
1102///
1103/// // Deserialization works too
1104/// // Subsecond precision in numbers will be rounded away
1105///
1106/// let json = json!({
1107///     "d_f64": 12345.5,
1108///     "d_string": "12345.987654",
1109/// });
1110/// let expected = Durations {
1111///     d_f64: Duration::new(12345, 500_000_000), // Create from seconds and nanoseconds
1112///     d_string: Duration::new(12345, 987_654_000),
1113/// };
1114/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1115/// # }
1116/// ```
1117///
1118/// [`chrono::Duration`] is also supported when using the `chrono_0_4` feature.
1119/// It is a signed duration, thus can be de/serialized as an `i64` instead of a `u64`.
1120///
1121/// ```rust
1122/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1123/// # use serde::{Deserialize, Serialize};
1124/// # use serde_json::json;
1125/// # use serde_with::{serde_as, DurationSecondsWithFrac};
1126/// # use chrono_0_4::Duration;
1127/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1128/// use chrono::Duration;
1129/// # */
1130///
1131/// #[serde_as]
1132/// # #[derive(Debug, PartialEq)]
1133/// #[derive(Deserialize, Serialize)]
1134/// struct Durations {
1135///     #[serde_as(as = "DurationSecondsWithFrac<f64>")]
1136///     d_f64: Duration,
1137///     #[serde_as(as = "DurationSecondsWithFrac<String>")]
1138///     d_string: Duration,
1139/// }
1140///
1141/// // Serialization
1142///
1143/// let d = Durations {
1144///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
1145///     d_string: Duration::seconds(12345) + Duration::nanoseconds(999_999_000),
1146/// };
1147/// // Observe the different data types
1148/// let expected = json!({
1149///     "d_f64": -12344.5,
1150///     "d_string": "12345.999999",
1151/// });
1152/// assert_eq!(expected, serde_json::to_value(d).unwrap());
1153///
1154/// // Deserialization works too
1155///
1156/// let json = json!({
1157///     "d_f64": -12344.5,
1158///     "d_string": "12345.987",
1159/// });
1160/// let expected = Durations {
1161///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
1162///     d_string: Duration::seconds(12345) + Duration::milliseconds(987),
1163/// };
1164/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1165/// # }
1166/// ```
1167///
1168/// [`chrono::Duration`]: ::chrono_0_4::Duration
1169/// [feature flag]: https://docs.rs/serde_with/3.23.0/serde_with/guide/feature_flags/index.html
1170pub struct DurationSecondsWithFrac<
1171    FORMAT: formats::Format = f64,
1172    STRICTNESS: formats::Strictness = formats::Strict,
1173>(PhantomData<(FORMAT, STRICTNESS)>);
1174
1175/// Equivalent to [`DurationSeconds`] with milli-seconds as base unit.
1176///
1177/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 milli-second instead of 1 second for [`DurationSeconds`].
1178pub struct DurationMilliSeconds<
1179    FORMAT: formats::Format = u64,
1180    STRICTNESS: formats::Strictness = formats::Strict,
1181>(PhantomData<(FORMAT, STRICTNESS)>);
1182
1183/// Equivalent to [`DurationSecondsWithFrac`] with milli-seconds as base unit.
1184///
1185/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 milli-second instead of 1 second for [`DurationSecondsWithFrac`].
1186pub struct DurationMilliSecondsWithFrac<
1187    FORMAT: formats::Format = f64,
1188    STRICTNESS: formats::Strictness = formats::Strict,
1189>(PhantomData<(FORMAT, STRICTNESS)>);
1190
1191/// Equivalent to [`DurationSeconds`] with micro-seconds as base unit.
1192///
1193/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 micro-second instead of 1 second for [`DurationSeconds`].
1194pub struct DurationMicroSeconds<
1195    FORMAT: formats::Format = u64,
1196    STRICTNESS: formats::Strictness = formats::Strict,
1197>(PhantomData<(FORMAT, STRICTNESS)>);
1198
1199/// Equivalent to [`DurationSecondsWithFrac`] with micro-seconds as base unit.
1200///
1201/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 micro-second instead of 1 second for [`DurationSecondsWithFrac`].
1202pub struct DurationMicroSecondsWithFrac<
1203    FORMAT: formats::Format = f64,
1204    STRICTNESS: formats::Strictness = formats::Strict,
1205>(PhantomData<(FORMAT, STRICTNESS)>);
1206
1207/// Equivalent to [`DurationSeconds`] with nano-seconds as base unit.
1208///
1209/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 nano-second instead of 1 second for [`DurationSeconds`].
1210pub struct DurationNanoSeconds<
1211    FORMAT: formats::Format = u64,
1212    STRICTNESS: formats::Strictness = formats::Strict,
1213>(PhantomData<(FORMAT, STRICTNESS)>);
1214
1215/// Equivalent to [`DurationSecondsWithFrac`] with nano-seconds as base unit.
1216///
1217/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 nano-second instead of 1 second for [`DurationSecondsWithFrac`].
1218pub struct DurationNanoSecondsWithFrac<
1219    FORMAT: formats::Format = f64,
1220    STRICTNESS: formats::Strictness = formats::Strict,
1221>(PhantomData<(FORMAT, STRICTNESS)>);
1222
1223/// De/Serialize timestamps as seconds since the UNIX epoch
1224///
1225/// De/serialize timestamps as seconds since the UNIX epoch.
1226/// Subsecond precision is *only* supported for [`TimestampSecondsWithFrac`], but not for [`TimestampSeconds`].
1227/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
1228/// Serialization of integers will round the timestamp to the nearest value.
1229///
1230/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
1231/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `i64` deserialization from a `f64` will error.
1232/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct timestamp and allows deserialization from any type.
1233/// For example, deserializing `TimestampSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
1234///
1235/// This type also supports [`chrono::DateTime`] with the `chrono_0_4`-[feature flag].
1236/// This type also supports [`jiff::Timestamp`][::jiff_0_2::Timestamp], [`jiff::Zoned`][::jiff_0_2::Zoned], and [`jiff::civil::DateTime`][::jiff_0_2::civil::DateTime] with the `jiff_0_2`-[feature flag].
1237/// This type also supports [`time::OffsetDateTime`][::time_0_3::OffsetDateTime] and [`time::PrimitiveDateTime`][::time_0_3::PrimitiveDateTime] with the `time_0_3`-[feature flag].
1238///
1239/// This table lists the available `FORMAT`s for the different timestamp types.
1240/// The `FORMAT` specifier defaults to `i64` or `f64`.
1241///
1242/// | Timestamp Type            | Converter                  | Available `FORMAT`s      |
1243/// | ------------------------- | -------------------------- | ------------------------ |
1244/// | `std::time::SystemTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1245/// | `std::time::SystemTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1246/// | `chrono::DateTime<Utc>`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1247/// | `chrono::DateTime<Utc>`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1248/// | `chrono::DateTime<Local>` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1249/// | `chrono::DateTime<Local>` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1250/// | `chrono::NaiveDateTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1251/// | `chrono::NaiveDateTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1252/// | `jiff::Timestamp`         | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1253/// | `jiff::Timestamp`         | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1254/// | `jiff::Zoned`             | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1255/// | `jiff::Zoned`             | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1256/// | `jiff::civil::DateTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1257/// | `jiff::civil::DateTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1258/// | `time::OffsetDateTime`    | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1259/// | `time::OffsetDateTime`    | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1260/// | `time::PrimitiveDateTime` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1261/// | `time::PrimitiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1262///
1263/// # Examples
1264///
1265/// ```rust
1266/// # #[cfg(feature = "macros")] {
1267/// # use serde::{Deserialize, Serialize};
1268/// # use serde_json::json;
1269/// # use serde_with::{serde_as, TimestampSeconds};
1270/// use std::time::{Duration, SystemTime};
1271///
1272/// #[serde_as]
1273/// # #[derive(Debug, PartialEq)]
1274/// #[derive(Deserialize, Serialize)]
1275/// struct Timestamps {
1276///     #[serde_as(as = "TimestampSeconds<i64>")]
1277///     st_i64: SystemTime,
1278///     #[serde_as(as = "TimestampSeconds<f64>")]
1279///     st_f64: SystemTime,
1280///     #[serde_as(as = "TimestampSeconds<String>")]
1281///     st_string: SystemTime,
1282/// }
1283///
1284/// // Serialization
1285/// // See how the values get rounded, since subsecond precision is not allowed.
1286///
1287/// let ts = Timestamps {
1288///     st_i64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 0)).unwrap(),
1289///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1290///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 999_999_999)).unwrap(),
1291/// };
1292/// // Observe the different data types
1293/// let expected = json!({
1294///     "st_i64": 12345,
1295///     "st_f64": 12346.0,
1296///     "st_string": "12346",
1297/// });
1298/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1299///
1300/// // Deserialization works too
1301/// // Subsecond precision in numbers will be rounded away
1302///
1303/// let json = json!({
1304///     "st_i64": 12345,
1305///     "st_f64": 12345.5,
1306///     "st_string": "12346",
1307/// });
1308/// let expected  = Timestamps {
1309///     st_i64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 0)).unwrap(),
1310///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12346, 0)).unwrap(),
1311///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12346, 0)).unwrap(),
1312/// };
1313/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1314/// # }
1315/// ```
1316///
1317/// [`chrono::DateTime<Utc>`] and [`chrono::DateTime<Local>`] are also supported when using the `chrono` feature.
1318/// Like [`SystemTime`], it is a signed timestamp, thus can be de/serialized as an `i64`.
1319///
1320/// ```rust
1321/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1322/// # use serde::{Deserialize, Serialize};
1323/// # use serde_json::json;
1324/// # use serde_with::{serde_as, TimestampSeconds};
1325/// # use chrono_0_4::{DateTime, Local, TimeZone, Utc};
1326/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1327/// use chrono::{DateTime, Local, TimeZone, Utc};
1328/// # */
1329///
1330/// #[serde_as]
1331/// # #[derive(Debug, PartialEq)]
1332/// #[derive(Deserialize, Serialize)]
1333/// struct Timestamps {
1334///     #[serde_as(as = "TimestampSeconds<i64>")]
1335///     dt_i64: DateTime<Utc>,
1336///     #[serde_as(as = "TimestampSeconds<f64>")]
1337///     dt_f64: DateTime<Local>,
1338///     #[serde_as(as = "TimestampSeconds<String>")]
1339///     dt_string: DateTime<Utc>,
1340/// }
1341///
1342/// // Serialization
1343/// // See how the values get rounded, since subsecond precision is not allowed.
1344///
1345/// let ts = Timestamps {
1346///     dt_i64: Utc.timestamp_opt(-12345, 0).unwrap(),
1347///     dt_f64: Local.timestamp_opt(-12345, 500_000_000).unwrap(),
1348///     dt_string: Utc.timestamp_opt(12345, 999_999_999).unwrap(),
1349/// };
1350/// // Observe the different data types
1351/// let expected = json!({
1352///     "dt_i64": -12345,
1353///     "dt_f64": -12345.0,
1354///     "dt_string": "12346",
1355/// });
1356/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1357///
1358/// // Deserialization works too
1359/// // Subsecond precision in numbers will be rounded away
1360///
1361/// let json = json!({
1362///     "dt_i64": -12345,
1363///     "dt_f64": -12345.5,
1364///     "dt_string": "12346",
1365/// });
1366/// let expected = Timestamps {
1367///     dt_i64: Utc.timestamp_opt(-12345, 0).unwrap(),
1368///     dt_f64: Local.timestamp_opt(-12346, 0).unwrap(),
1369///     dt_string: Utc.timestamp_opt(12346, 0).unwrap(),
1370/// };
1371/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1372/// # }
1373/// ```
1374///
1375/// [`SystemTime`]: std::time::SystemTime
1376/// [`chrono::DateTime<Local>`]: ::chrono_0_4::DateTime
1377/// [`chrono::DateTime<Utc>`]: ::chrono_0_4::DateTime
1378/// [feature flag]: https://docs.rs/serde_with/3.23.0/serde_with/guide/feature_flags/index.html
1379pub struct TimestampSeconds<
1380    FORMAT: formats::Format = i64,
1381    STRICTNESS: formats::Strictness = formats::Strict,
1382>(PhantomData<(FORMAT, STRICTNESS)>);
1383
1384/// De/Serialize timestamps as seconds since the UNIX epoch
1385///
1386/// De/serialize timestamps as seconds since the UNIX epoch.
1387/// Subsecond precision is *only* supported for [`TimestampSecondsWithFrac`], but not for [`TimestampSeconds`].
1388/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
1389/// Serialization of integers will round the timestamp to the nearest value.
1390///
1391/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
1392/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `i64` deserialization from a `f64` will error.
1393/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct timestamp and allows deserialization from any type.
1394/// For example, deserializing `TimestampSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
1395///
1396/// This type also supports [`chrono::DateTime`] and [`chrono::NaiveDateTime`][NaiveDateTime] with the `chrono`-[feature flag].
1397/// This type also supports [`jiff::Timestamp`][::jiff_0_2::Timestamp], [`jiff::Zoned`][::jiff_0_2::Zoned], and [`jiff::civil::DateTime`][::jiff_0_2::civil::DateTime] with the `jiff_0_2`-[feature flag].
1398/// This type also supports [`time::OffsetDateTime`][::time_0_3::OffsetDateTime] and [`time::PrimitiveDateTime`][::time_0_3::PrimitiveDateTime] with the `time_0_3`-[feature flag].
1399///
1400/// This table lists the available `FORMAT`s for the different timestamp types.
1401/// The `FORMAT` specifier defaults to `i64` or `f64`.
1402///
1403/// | Timestamp Type            | Converter                  | Available `FORMAT`s      |
1404/// | ------------------------- | -------------------------- | ------------------------ |
1405/// | `std::time::SystemTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1406/// | `std::time::SystemTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1407/// | `chrono::DateTime<Utc>`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1408/// | `chrono::DateTime<Utc>`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1409/// | `chrono::DateTime<Local>` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1410/// | `chrono::DateTime<Local>` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1411/// | `chrono::NaiveDateTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1412/// | `chrono::NaiveDateTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1413/// | `jiff::Timestamp`         | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1414/// | `jiff::Timestamp`         | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1415/// | `jiff::Zoned`             | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1416/// | `jiff::Zoned`             | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1417/// | `jiff::civil::DateTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1418/// | `jiff::civil::DateTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1419/// | `time::OffsetDateTime`    | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1420/// | `time::OffsetDateTime`    | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1421/// | `time::PrimitiveDateTime` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1422/// | `time::PrimitiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1423///
1424/// # Examples
1425///
1426/// ```rust
1427/// # #[cfg(feature = "macros")] {
1428/// # use serde::{Deserialize, Serialize};
1429/// # use serde_json::json;
1430/// # use serde_with::{serde_as, TimestampSecondsWithFrac};
1431/// use std::time::{Duration, SystemTime};
1432///
1433/// #[serde_as]
1434/// # #[derive(Debug, PartialEq)]
1435/// #[derive(Deserialize, Serialize)]
1436/// struct Timestamps {
1437///     #[serde_as(as = "TimestampSecondsWithFrac<f64>")]
1438///     st_f64: SystemTime,
1439///     #[serde_as(as = "TimestampSecondsWithFrac<String>")]
1440///     st_string: SystemTime,
1441/// }
1442///
1443/// // Serialization
1444/// // See how the values get rounded, since subsecond precision is not allowed.
1445///
1446/// let ts = Timestamps {
1447///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1448///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 999_999_000)).unwrap(),
1449/// };
1450/// // Observe the different data types
1451/// let expected = json!({
1452///     "st_f64": 12345.5,
1453///     "st_string": "12345.999999",
1454/// });
1455/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1456///
1457/// // Deserialization works too
1458/// // Subsecond precision in numbers will be rounded away
1459///
1460/// let json = json!({
1461///     "st_f64": 12345.5,
1462///     "st_string": "12345.987654",
1463/// });
1464/// let expected = Timestamps {
1465///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1466///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 987_654_000)).unwrap(),
1467/// };
1468/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1469/// # }
1470/// ```
1471///
1472/// [`chrono::DateTime<Utc>`] and [`chrono::DateTime<Local>`] are also supported when using the `chrono_0_4` feature.
1473/// Like [`SystemTime`], it is a signed timestamp, thus can be de/serialized as an `i64`.
1474///
1475/// ```rust
1476/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1477/// # use serde::{Deserialize, Serialize};
1478/// # use serde_json::json;
1479/// # use serde_with::{serde_as, TimestampSecondsWithFrac};
1480/// # use chrono_0_4::{DateTime, Local, TimeZone, Utc};
1481/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1482/// use chrono::{DateTime, Local, TimeZone, Utc};
1483/// # */
1484///
1485/// #[serde_as]
1486/// # #[derive(Debug, PartialEq)]
1487/// #[derive(Deserialize, Serialize)]
1488/// struct Timestamps {
1489///     #[serde_as(as = "TimestampSecondsWithFrac<f64>")]
1490///     dt_f64: DateTime<Utc>,
1491///     #[serde_as(as = "TimestampSecondsWithFrac<String>")]
1492///     dt_string: DateTime<Local>,
1493/// }
1494///
1495/// // Serialization
1496///
1497/// let ts = Timestamps {
1498///     dt_f64: Utc.timestamp_opt(-12345, 500_000_000).unwrap(),
1499///     dt_string: Local.timestamp_opt(12345, 999_999_000).unwrap(),
1500/// };
1501/// // Observe the different data types
1502/// let expected = json!({
1503///     "dt_f64": -12344.5,
1504///     "dt_string": "12345.999999",
1505/// });
1506/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1507///
1508/// // Deserialization works too
1509///
1510/// let json = json!({
1511///     "dt_f64": -12344.5,
1512///     "dt_string": "12345.987",
1513/// });
1514/// let expected = Timestamps {
1515///     dt_f64: Utc.timestamp_opt(-12345, 500_000_000).unwrap(),
1516///     dt_string: Local.timestamp_opt(12345, 987_000_000).unwrap(),
1517/// };
1518/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1519/// # }
1520/// ```
1521///
1522/// [`SystemTime`]: std::time::SystemTime
1523/// [`chrono::DateTime`]: ::chrono_0_4::DateTime
1524/// [`chrono::DateTime<Local>`]: ::chrono_0_4::DateTime
1525/// [`chrono::DateTime<Utc>`]: ::chrono_0_4::DateTime
1526/// [NaiveDateTime]: ::chrono_0_4::NaiveDateTime
1527/// [feature flag]: https://docs.rs/serde_with/3.23.0/serde_with/guide/feature_flags/index.html
1528pub struct TimestampSecondsWithFrac<
1529    FORMAT: formats::Format = f64,
1530    STRICTNESS: formats::Strictness = formats::Strict,
1531>(PhantomData<(FORMAT, STRICTNESS)>);
1532
1533/// Equivalent to [`TimestampSeconds`] with milli-seconds as base unit.
1534///
1535/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 milli-second instead of 1 second for [`TimestampSeconds`].
1536pub struct TimestampMilliSeconds<
1537    FORMAT: formats::Format = i64,
1538    STRICTNESS: formats::Strictness = formats::Strict,
1539>(PhantomData<(FORMAT, STRICTNESS)>);
1540
1541/// Equivalent to [`TimestampSecondsWithFrac`] with milli-seconds as base unit.
1542///
1543/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 milli-second instead of 1 second for [`TimestampSecondsWithFrac`].
1544pub struct TimestampMilliSecondsWithFrac<
1545    FORMAT: formats::Format = f64,
1546    STRICTNESS: formats::Strictness = formats::Strict,
1547>(PhantomData<(FORMAT, STRICTNESS)>);
1548
1549/// Equivalent to [`TimestampSeconds`] with micro-seconds as base unit.
1550///
1551/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 micro-second instead of 1 second for [`TimestampSeconds`].
1552pub struct TimestampMicroSeconds<
1553    FORMAT: formats::Format = i64,
1554    STRICTNESS: formats::Strictness = formats::Strict,
1555>(PhantomData<(FORMAT, STRICTNESS)>);
1556
1557/// Equivalent to [`TimestampSecondsWithFrac`] with micro-seconds as base unit.
1558///
1559/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 micro-second instead of 1 second for [`TimestampSecondsWithFrac`].
1560pub struct TimestampMicroSecondsWithFrac<
1561    FORMAT: formats::Format = f64,
1562    STRICTNESS: formats::Strictness = formats::Strict,
1563>(PhantomData<(FORMAT, STRICTNESS)>);
1564
1565/// Equivalent to [`TimestampSeconds`] with nano-seconds as base unit.
1566///
1567/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 nano-second instead of 1 second for [`TimestampSeconds`].
1568pub struct TimestampNanoSeconds<
1569    FORMAT: formats::Format = i64,
1570    STRICTNESS: formats::Strictness = formats::Strict,
1571>(PhantomData<(FORMAT, STRICTNESS)>);
1572
1573/// Equivalent to [`TimestampSecondsWithFrac`] with nano-seconds as base unit.
1574///
1575/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 nano-second instead of 1 second for [`TimestampSecondsWithFrac`].
1576pub struct TimestampNanoSecondsWithFrac<
1577    FORMAT: formats::Format = f64,
1578    STRICTNESS: formats::Strictness = formats::Strict,
1579>(PhantomData<(FORMAT, STRICTNESS)>);
1580
1581/// Optimized handling of owned and borrowed byte representations.
1582///
1583/// Serialization of byte sequences like `&[u8]` or `Vec<u8>` is quite inefficient since each value will be serialized individually.
1584/// This converter type optimizes the serialization and deserialization.
1585///
1586/// This is a port of the [`serde_bytes`] crate making it compatible with the `serde_as` annotation, which allows it to be used in more cases than provided by [`serde_bytes`].
1587///
1588/// The type provides de/serialization for these types:
1589///
1590/// * `[u8; N]`, not possible using `serde_bytes`
1591/// * `&[u8; N]`, not possible using `serde_bytes`
1592/// * `&[u8]`
1593/// * `Box<[u8; N]>`, not possible using `serde_bytes`
1594/// * `Box<[u8]>`
1595/// * `Vec<u8>`
1596/// * `Cow<'_, [u8]>`
1597/// * `Cow<'_, [u8; N]>`, not possible using `serde_bytes`
1598///
1599/// [`serde_bytes`]: https://crates.io/crates/serde_bytes
1600///
1601/// # Examples
1602///
1603/// ```
1604/// # #[cfg(feature = "macros")] {
1605/// # use serde::{Deserialize, Serialize};
1606/// # use serde_with::{serde_as, Bytes};
1607/// # use std::borrow::Cow;
1608/// #
1609/// #[serde_as]
1610/// # #[derive(Debug, PartialEq)]
1611/// #[derive(Deserialize, Serialize)]
1612/// struct Test<'a> {
1613///     #[serde_as(as = "Bytes")]
1614///     array: [u8; 15],
1615///     #[serde_as(as = "Bytes")]
1616///     boxed: Box<[u8]>,
1617///     #[serde_as(as = "Bytes")]
1618///     #[serde(borrow)]
1619///     cow: Cow<'a, [u8]>,
1620///     #[serde_as(as = "Bytes")]
1621///     #[serde(borrow)]
1622///     cow_array: Cow<'a, [u8; 15]>,
1623///     #[serde_as(as = "Bytes")]
1624///     vec: Vec<u8>,
1625/// }
1626///
1627/// let value = Test {
1628///     array: *b"0123456789ABCDE",
1629///     boxed: b"...".to_vec().into_boxed_slice(),
1630///     cow: Cow::Borrowed(b"FooBar"),
1631///     cow_array: Cow::Borrowed(&[42u8; 15]),
1632///     vec: vec![0x41, 0x61, 0x21],
1633/// };
1634/// let expected = r#"(
1635///     array: b"0123456789ABCDE",
1636///     boxed: b"...",
1637///     cow: b"FooBar",
1638///     cow_array: b"***************",
1639///     vec: b"Aa!",
1640/// )"#;
1641///
1642/// # let pretty_config = ron::ser::PrettyConfig::new().new_line("\n");
1643/// assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
1644/// assert_eq!(value, ron::from_str(expected).unwrap());
1645/// # }
1646/// ```
1647///
1648/// Fully borrowed types can also be used but you'll need a Deserializer that
1649/// supports Serde's 0-copy deserialization:
1650///
1651/// ```
1652/// # #[cfg(feature = "macros")] {
1653/// # use serde::{Deserialize, Serialize};
1654/// # use serde_with::{serde_as, Bytes};
1655/// #
1656/// #[serde_as]
1657/// # #[derive(Debug, PartialEq)]
1658/// #[derive(Deserialize, Serialize)]
1659/// struct TestBorrows<'a> {
1660///     #[serde_as(as = "Bytes")]
1661///     #[serde(borrow)]
1662///     array_buf: &'a [u8; 15],
1663///     #[serde_as(as = "Bytes")]
1664///     #[serde(borrow)]
1665///     buf: &'a [u8],
1666/// }
1667///
1668/// let value = TestBorrows {
1669///     array_buf: &[10u8; 15],
1670///     buf: &[20u8, 21u8, 22u8],
1671/// };
1672/// let expected = r#"(
1673///     array_buf: b"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1674///     buf: b"\x14\x15\x16",
1675/// )"#;
1676///
1677/// # let pretty_config = ron::ser::PrettyConfig::new().new_line("\n");
1678/// assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
1679/// // RON doesn't support borrowed deserialization of byte arrays
1680/// # }
1681/// ```
1682///
1683/// ## Alternative to [`BytesOrString`]
1684///
1685/// The [`Bytes`] can replace [`BytesOrString`].
1686/// [`Bytes`] is implemented for more types, which makes it better.
1687/// The serialization behavior of [`Bytes`] differs from [`BytesOrString`], therefore only `deserialize_as` should be used.
1688///
1689/// ```rust
1690/// # #[cfg(feature = "macros")] {
1691/// # use serde::Deserialize;
1692/// # use serde_json::json;
1693/// # use serde_with::{serde_as, Bytes};
1694/// #
1695/// #[serde_as]
1696/// # #[derive(Debug, PartialEq)]
1697/// #[derive(Deserialize, serde::Serialize)]
1698/// struct Test {
1699///     #[serde_as(deserialize_as = "Bytes")]
1700///     from_bytes: Vec<u8>,
1701///     #[serde_as(deserialize_as = "Bytes")]
1702///     from_str: Vec<u8>,
1703/// }
1704///
1705/// // Different serialized values ...
1706/// let j = json!({
1707///     "from_bytes": [70,111,111,45,66,97,114],
1708///     "from_str": "Foo-Bar",
1709/// });
1710///
1711/// // can be deserialized ...
1712/// let test = Test {
1713///     from_bytes: b"Foo-Bar".to_vec(),
1714///     from_str: b"Foo-Bar".to_vec(),
1715/// };
1716/// assert_eq!(test, serde_json::from_value(j).unwrap());
1717///
1718/// // and serialization will always be a byte sequence
1719/// # assert_eq!(json!(
1720/// {
1721///     "from_bytes": [70,111,111,45,66,97,114],
1722///     "from_str": [70,111,111,45,66,97,114],
1723/// }
1724/// # ), serde_json::to_value(&test).unwrap());
1725/// # }
1726/// ```
1727pub struct Bytes;
1728
1729/// Deserialize one or many elements
1730///
1731/// Sometimes it is desirable to have a shortcut in writing 1-element lists in a config file.
1732/// Usually, this is done by either writing a list or the list element itself.
1733/// This distinction is not semantically important on the Rust side, thus both forms should deserialize into the same `Vec`.
1734///
1735/// The `OneOrMany` adapter achieves exactly this use case.
1736/// The serialization behavior can be tweaked to either always serialize as a list using [`PreferMany`] or to serialize as the inner element if possible using [`PreferOne`].
1737/// By default, [`PreferOne`] is assumed, which can also be omitted like `OneOrMany<_>`.
1738///
1739/// [`PreferMany`]: crate::formats::PreferMany
1740/// [`PreferOne`]: crate::formats::PreferOne
1741///
1742/// # Examples
1743///
1744/// ```rust
1745/// # #[cfg(feature = "macros")] {
1746/// # use serde::Deserialize;
1747/// # use serde_json::json;
1748/// # use serde_with::{serde_as, OneOrMany};
1749/// # use serde_with::formats::{PreferOne, PreferMany};
1750/// #
1751/// #[serde_as]
1752/// # #[derive(Debug, PartialEq)]
1753/// #[derive(Deserialize, serde::Serialize)]
1754/// struct Data {
1755///     #[serde_as(as = "OneOrMany<_, PreferOne>")]
1756///     countries: Vec<String>,
1757///     #[serde_as(as = "OneOrMany<_, PreferMany>")]
1758///     cities: Vec<String>,
1759/// }
1760///
1761/// // The adapter allows deserializing a `Vec` from either
1762/// // a single element
1763/// let j = json!({
1764///     "countries": "Spain",
1765///     "cities": "Berlin",
1766/// });
1767/// assert!(serde_json::from_value::<Data>(j).is_ok());
1768///
1769/// // or from a list.
1770/// let j = json!({
1771///     "countries": ["Germany", "France"],
1772///     "cities": ["Amsterdam"],
1773/// });
1774/// assert!(serde_json::from_value::<Data>(j).is_ok());
1775///
1776/// // For serialization you can choose how a single element should be encoded.
1777/// // Either directly, with `PreferOne` (default), or as a list with `PreferMany`.
1778/// let data = Data {
1779///     countries: vec!["Spain".to_string()],
1780///     cities: vec!["Berlin".to_string()],
1781/// };
1782/// let j = json!({
1783///     "countries": "Spain",
1784///     "cities": ["Berlin"],
1785/// });
1786/// assert_eq!(serde_json::to_value(data).unwrap(), j);
1787/// # }
1788/// ```
1789pub struct OneOrMany<T: ?Sized, FORMAT: formats::Format = formats::PreferOne>(
1790    PhantomData<(FORMAT, T)>,
1791);
1792
1793/// Try multiple deserialization options until one succeeds.
1794///
1795/// This adapter allows you to specify a list of deserialization options.
1796/// They are tried in order and the first one working is applied.
1797/// Serialization always picks the first option.
1798///
1799/// `PickFirst` has one type parameter which must be instantiated with a tuple of two, three, or four elements.
1800/// For example, `PickFirst<(_, DisplayFromStr)>` on a field of type `u32` allows deserializing from a number or from a string via the `FromStr` trait.
1801/// The value will be serialized as a number, since that is what the first type `_` indicates.
1802///
1803/// # Examples
1804///
1805/// Deserialize a number from either a number or a string.
1806///
1807/// ```rust
1808/// # #[cfg(feature = "macros")] {
1809/// # use serde::{Deserialize, Serialize};
1810/// # use serde_json::json;
1811/// # use serde_with::{serde_as, DisplayFromStr, PickFirst};
1812/// #
1813/// #[serde_as]
1814/// # #[derive(Debug, PartialEq)]
1815/// #[derive(Deserialize, Serialize)]
1816/// struct Data {
1817///     #[serde_as(as = "PickFirst<(_, DisplayFromStr)>")]
1818///     as_number: u32,
1819///     #[serde_as(as = "PickFirst<(DisplayFromStr, _)>")]
1820///     as_string: u32,
1821/// }
1822/// let data = Data {
1823///     as_number: 123,
1824///     as_string: 456
1825/// };
1826///
1827/// // Both fields can be deserialized from numbers:
1828/// let j = json!({
1829///     "as_number": 123,
1830///     "as_string": 456,
1831/// });
1832/// assert_eq!(data, serde_json::from_value(j).unwrap());
1833///
1834/// // or from a string:
1835/// let j = json!({
1836///     "as_number": "123",
1837///     "as_string": "456",
1838/// });
1839/// assert_eq!(data, serde_json::from_value(j).unwrap());
1840///
1841/// // For serialization the first type in the tuple determines the behavior.
1842/// // The `as_number` field will use the normal `Serialize` behavior and produce a number,
1843/// // while `as_string` used `Display` to produce a string.
1844/// let expected = json!({
1845///     "as_number": 123,
1846///     "as_string": "456",
1847/// });
1848/// assert_eq!(expected, serde_json::to_value(&data).unwrap());
1849/// # }
1850/// ```
1851#[cfg(feature = "alloc")]
1852pub struct PickFirst<T>(PhantomData<T>);
1853
1854/// Serialize value by converting to/from a proxy type with serde support.
1855///
1856/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
1857/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
1858///
1859/// ```rust
1860/// # #[cfg(false)] {
1861/// struct S {
1862///     #[serde_as(as = "FromInto<T>")]
1863///     value: O,
1864/// }
1865/// # }
1866/// ```
1867///
1868/// For serialization `O` needs to be `O: Into<T> + Clone`.
1869/// For deserialization the opposite `T: Into<O>` is required.
1870/// The `Clone` bound is required since `serialize` operates on a reference but `Into` implementations on references are uncommon.
1871///
1872/// **Note**: [`TryFromInto`] is the more generalized version of this adapter which uses the [`TryInto`] trait instead.
1873///
1874/// # Example
1875///
1876/// ```rust
1877/// # #[cfg(feature = "macros")] {
1878/// # use serde::{Deserialize, Serialize};
1879/// # use serde_json::json;
1880/// # use serde_with::{serde_as, FromInto};
1881/// #
1882/// #[derive(Clone, Debug, PartialEq)]
1883/// struct Rgb {
1884///     red: u8,
1885///     green: u8,
1886///     blue: u8,
1887/// }
1888///
1889/// # /*
1890/// impl From<(u8, u8, u8)> for Rgb { ... }
1891/// impl From<Rgb> for (u8, u8, u8) { ... }
1892/// # */
1893/// #
1894/// # impl From<(u8, u8, u8)> for Rgb {
1895/// #     fn from(v: (u8, u8, u8)) -> Self {
1896/// #         Rgb {
1897/// #             red: v.0,
1898/// #             green: v.1,
1899/// #             blue: v.2,
1900/// #         }
1901/// #     }
1902/// # }
1903/// #
1904/// # impl From<Rgb> for (u8, u8, u8) {
1905/// #     fn from(v: Rgb) -> Self {
1906/// #         (v.red, v.green, v.blue)
1907/// #     }
1908/// # }
1909///
1910/// #[serde_as]
1911/// # #[derive(Debug, PartialEq)]
1912/// #[derive(Deserialize, Serialize)]
1913/// struct Color {
1914///     #[serde_as(as = "FromInto<(u8, u8, u8)>")]
1915///     rgb: Rgb,
1916/// }
1917/// let color = Color {
1918///     rgb: Rgb {
1919///         red: 128,
1920///         green: 64,
1921///         blue: 32,
1922///     },
1923/// };
1924///
1925/// // Define our expected JSON form
1926/// let j = json!({
1927///     "rgb": [128, 64, 32],
1928/// });
1929/// // Ensure serialization and deserialization produce the expected results
1930/// assert_eq!(j, serde_json::to_value(&color).unwrap());
1931/// assert_eq!(color, serde_json::from_value(j).unwrap());
1932/// # }
1933/// ```
1934pub struct FromInto<T>(PhantomData<T>);
1935
1936/// Serialize a reference value by converting to/from a proxy type with serde support.
1937///
1938/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
1939/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
1940///
1941/// ```rust
1942/// # #[cfg(false)] {
1943/// struct S {
1944///     #[serde_as(as = "FromIntoRef<T>")]
1945///     value: O,
1946/// }
1947/// # }
1948/// ```
1949///
1950/// For serialization `O` needs to be `for<'a> &'a O: Into<T>`.
1951/// For deserialization the opposite `T: Into<O>` is required.
1952///
1953/// **Note**: [`TryFromIntoRef`] is the more generalized version of this adapter which uses the [`TryInto`] trait instead.
1954///
1955/// # Example
1956///
1957/// ```rust
1958/// # #[cfg(feature = "macros")] {
1959/// # use serde::{Deserialize, Serialize};
1960/// # use serde_json::json;
1961/// # use serde_with::{serde_as, FromIntoRef};
1962/// #
1963/// #[derive(Debug, PartialEq)]
1964/// struct Rgb {
1965///     red: u8,
1966///     green: u8,
1967///     blue: u8,
1968/// }
1969///
1970/// # /*
1971/// impl From<(u8, u8, u8)> for Rgb { ... }
1972/// impl<'a> From<&'a Rgb> for (u8, u8, u8) { ... }
1973/// # */
1974/// #
1975/// # impl From<(u8, u8, u8)> for Rgb {
1976/// #     fn from(v: (u8, u8, u8)) -> Self {
1977/// #         Rgb {
1978/// #             red: v.0,
1979/// #             green: v.1,
1980/// #             blue: v.2,
1981/// #         }
1982/// #     }
1983/// # }
1984/// #
1985/// # impl<'a> From<&'a Rgb> for (u8, u8, u8) {
1986/// #     fn from(v: &'a Rgb) -> Self {
1987/// #         (v.red, v.green, v.blue)
1988/// #     }
1989/// # }
1990///
1991/// #[serde_as]
1992/// # #[derive(Debug, PartialEq)]
1993/// #[derive(Deserialize, Serialize)]
1994/// struct Color {
1995///     #[serde_as(as = "FromIntoRef<(u8, u8, u8)>")]
1996///     rgb: Rgb,
1997/// }
1998/// let color = Color {
1999///     rgb: Rgb {
2000///         red: 128,
2001///         green: 64,
2002///         blue: 32,
2003///     },
2004/// };
2005///
2006/// // Define our expected JSON form
2007/// let j = json!({
2008///     "rgb": [128, 64, 32],
2009/// });
2010/// // Ensure serialization and deserialization produce the expected results
2011/// assert_eq!(j, serde_json::to_value(&color).unwrap());
2012/// assert_eq!(color, serde_json::from_value(j).unwrap());
2013/// # }
2014/// ```
2015pub struct FromIntoRef<T>(PhantomData<T>);
2016
2017/// Serialize value by converting to/from a proxy type with serde support.
2018///
2019/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
2020/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
2021///
2022/// ```rust
2023/// # #[cfg(false)] {
2024/// struct S {
2025///     #[serde_as(as = "TryFromInto<T>")]
2026///     value: O,
2027/// }
2028/// # }
2029/// ```
2030///
2031/// For serialization `O` needs to be `O: TryInto<T> + Clone`.
2032/// For deserialization the opposite `T: TryInto<O>` is required.
2033/// The `Clone` bound is required since `serialize` operates on a reference but `TryInto` implementations on references are uncommon.
2034/// In both cases the `TryInto::Error` type must implement [`Display`](std::fmt::Display).
2035///
2036/// **Note**: [`FromInto`] is the more specialized version of this adapter which uses the infallible [`Into`] trait instead.
2037/// [`TryFromInto`] is strictly more general and can also be used where [`FromInto`] is applicable.
2038/// The example shows a use case, when only the deserialization behavior is fallible, but not serializing.
2039///
2040/// # Example
2041///
2042/// ```rust
2043/// # #[cfg(feature = "macros")] {
2044/// # use serde::{Deserialize, Serialize};
2045/// # use serde_json::json;
2046/// # use serde_with::{serde_as, TryFromInto};
2047/// #
2048/// #[derive(Clone, Debug, PartialEq)]
2049/// enum Boollike {
2050///     True,
2051///     False,
2052/// }
2053///
2054/// # /*
2055/// impl From<Boollike> for u8 { ... }
2056/// # */
2057/// #
2058/// impl TryFrom<u8> for Boollike {
2059///     type Error = String;
2060///     fn try_from(v: u8) -> Result<Self, Self::Error> {
2061///         match v {
2062///             0 => Ok(Boollike::False),
2063///             1 => Ok(Boollike::True),
2064///             _ => Err(format!("Boolikes can only be constructed from 0 or 1 but found {}", v))
2065///         }
2066///     }
2067/// }
2068/// #
2069/// # impl From<Boollike> for u8 {
2070/// #     fn from(v: Boollike) -> Self {
2071/// #        match v {
2072/// #            Boollike::True => 1,
2073/// #            Boollike::False => 0,
2074/// #        }
2075/// #     }
2076/// # }
2077///
2078/// #[serde_as]
2079/// # #[derive(Debug, PartialEq)]
2080/// #[derive(Deserialize, Serialize)]
2081/// struct Data {
2082///     #[serde_as(as = "TryFromInto<u8>")]
2083///     b: Boollike,
2084/// }
2085/// let data = Data {
2086///     b: Boollike::True,
2087/// };
2088///
2089/// // Define our expected JSON form
2090/// let j = json!({
2091///     "b": 1,
2092/// });
2093/// // Ensure serialization and deserialization produce the expected results
2094/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2095/// assert_eq!(data, serde_json::from_value(j).unwrap());
2096///
2097/// // Numbers besides 0 or 1 should be an error
2098/// let j = json!({
2099///     "b": 2,
2100/// });
2101/// assert_eq!("Boolikes can only be constructed from 0 or 1 but found 2", serde_json::from_value::<Data>(j).unwrap_err().to_string());
2102/// # }
2103/// ```
2104pub struct TryFromInto<T>(PhantomData<T>);
2105
2106/// Serialize a reference value by converting to/from a proxy type with serde support.
2107///
2108/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
2109/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
2110///
2111/// ```rust
2112/// # #[cfg(false)] {
2113/// struct S {
2114///     #[serde_as(as = "TryFromIntoRef<T>")]
2115///     value: O,
2116/// }
2117/// # }
2118/// ```
2119///
2120/// For serialization `O` needs to be `for<'a> &'a O: TryInto<T>`.
2121/// For deserialization the opposite `T: TryInto<O>` is required.
2122/// In both cases the `TryInto::Error` type must implement [`Display`](std::fmt::Display).
2123///
2124/// **Note**: [`FromIntoRef`] is the more specialized version of this adapter which uses the infallible [`Into`] trait instead.
2125/// [`TryFromIntoRef`] is strictly more general and can also be used where [`FromIntoRef`] is applicable.
2126/// The example shows a use case, when only the deserialization behavior is fallible, but not serializing.
2127///
2128/// # Example
2129///
2130/// ```rust
2131/// # #[cfg(feature = "macros")] {
2132/// # use serde::{Deserialize, Serialize};
2133/// # use serde_json::json;
2134/// # use serde_with::{serde_as, TryFromIntoRef};
2135/// #
2136/// #[derive(Debug, PartialEq)]
2137/// enum Boollike {
2138///     True,
2139///     False,
2140/// }
2141///
2142/// # /*
2143/// impl<'a> From<&'a Boollike> for u8 { ... }
2144/// # */
2145/// #
2146/// impl TryFrom<u8> for Boollike {
2147///     type Error = String;
2148///     fn try_from(v: u8) -> Result<Self, Self::Error> {
2149///         match v {
2150///             0 => Ok(Boollike::False),
2151///             1 => Ok(Boollike::True),
2152///             _ => Err(format!("Boolikes can only be constructed from 0 or 1 but found {}", v))
2153///         }
2154///     }
2155/// }
2156/// #
2157/// # impl<'a> From<&'a Boollike> for u8 {
2158/// #     fn from(v: &'a Boollike) -> Self {
2159/// #        match v {
2160/// #            Boollike::True => 1,
2161/// #            Boollike::False => 0,
2162/// #        }
2163/// #     }
2164/// # }
2165///
2166/// #[serde_as]
2167/// # #[derive(Debug, PartialEq)]
2168/// #[derive(Deserialize, Serialize)]
2169/// struct Data {
2170///     #[serde_as(as = "TryFromIntoRef<u8>")]
2171///     b: Boollike,
2172/// }
2173/// let data = Data {
2174///     b: Boollike::True,
2175/// };
2176///
2177/// // Define our expected JSON form
2178/// let j = json!({
2179///     "b": 1,
2180/// });
2181/// // Ensure serialization and deserialization produce the expected results
2182/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2183/// assert_eq!(data, serde_json::from_value(j).unwrap());
2184///
2185/// // Numbers besides 0 or 1 should be an error
2186/// let j = json!({
2187///     "b": 2,
2188/// });
2189/// assert_eq!("Boolikes can only be constructed from 0 or 1 but found 2", serde_json::from_value::<Data>(j).unwrap_err().to_string());
2190/// # }
2191/// ```
2192pub struct TryFromIntoRef<T>(PhantomData<T>);
2193
2194/// Borrow `Cow` data during deserialization when possible.
2195///
2196/// The types `Cow<'a, [u8]>`, `Cow<'a, [u8; N]>`, and `Cow<'a, str>` can borrow from the input data during deserialization.
2197/// serde supports this, by annotating the fields with `#[serde(borrow)]`. but does not support borrowing on nested types.
2198/// This gap is filled by this `BorrowCow` adapter.
2199///
2200/// Using this adapter with `Cow<'a, [u8]>`/`Cow<'a, [u8; N]>` will serialize the value as a sequence of `u8` values.
2201/// This *might* not allow to borrow the data during deserialization.
2202/// For a different format, which is also more efficient, use the [`Bytes`] adapter, which is also implemented for `Cow`.
2203///
2204/// When combined with the [`serde_as`] attribute, the `#[serde(borrow)]` annotation will be added automatically.
2205/// If the annotation is wrong or too broad, for example because of multiple lifetime parameters, a manual annotation is required.
2206///
2207/// # Examples
2208///
2209/// ```rust
2210/// # #[cfg(feature = "macros")] {
2211/// # use serde::{Deserialize, Serialize};
2212/// # use serde_with::{serde_as, BorrowCow};
2213/// # use std::borrow::Cow;
2214/// #
2215/// #[serde_as]
2216/// # #[derive(Debug, PartialEq)]
2217/// #[derive(Deserialize, Serialize)]
2218/// struct Data<'a, 'b, 'c> {
2219///     #[serde_as(as = "BorrowCow")]
2220///     str: Cow<'a, str>,
2221///     #[serde_as(as = "BorrowCow")]
2222///     slice: Cow<'b, [u8]>,
2223///
2224///     #[serde_as(as = "Option<[BorrowCow; 1]>")]
2225///     nested: Option<[Cow<'c, str>; 1]>,
2226/// }
2227/// let data = Data {
2228///     str: "foobar".into(),
2229///     slice: b"foobar"[..].into(),
2230///     nested: Some(["HelloWorld".into()]),
2231/// };
2232///
2233/// // Define our expected JSON form
2234/// let j = r#"{
2235///   "str": "foobar",
2236///   "slice": [
2237///     102,
2238///     111,
2239///     111,
2240///     98,
2241///     97,
2242///     114
2243///   ],
2244///   "nested": [
2245///     "HelloWorld"
2246///   ]
2247/// }"#;
2248/// // Ensure serialization and deserialization produce the expected results
2249/// assert_eq!(j, serde_json::to_string_pretty(&data).unwrap());
2250/// assert_eq!(data, serde_json::from_str(j).unwrap());
2251///
2252/// // Cow borrows from the input data
2253/// let deserialized: Data<'_, '_, '_> = serde_json::from_str(j).unwrap();
2254/// assert!(matches!(deserialized.str, Cow::Borrowed(_)));
2255/// assert!(matches!(deserialized.nested, Some([Cow::Borrowed(_)])));
2256/// // JSON does not allow borrowing bytes, so `slice` does not borrow
2257/// assert!(matches!(deserialized.slice, Cow::Owned(_)));
2258/// # }
2259/// ```
2260#[cfg(feature = "alloc")]
2261pub struct BorrowCow;
2262
2263/// A trait to inspect skipped deserialization errors
2264///
2265/// The [`VecSkipError`] and [`MapSkipError`] adapters allow to skip values which fail to deserialize.
2266/// This trait allows inspecting these errors, for example for logging purposes.
2267///
2268/// The trait has a single method [`inspect_error`][InspectError::inspect_error], which will be called for each deserialization error.
2269/// The default implementation for `()` does nothing.
2270///
2271/// See the documentation of [`VecSkipError`] and [`MapSkipError`] for usage examples.
2272#[cfg(feature = "alloc")]
2273pub trait InspectError {
2274    /// Inspect a deserialization error which was skipped.
2275    fn inspect_error(error: impl serde_core::de::Error);
2276}
2277
2278#[cfg(feature = "alloc")]
2279impl InspectError for () {
2280    fn inspect_error(_error: impl serde_core::de::Error) {}
2281}
2282
2283/// Deserialize a sequence into `Vec<T>`, skipping elements which fail to deserialize.
2284///
2285/// The serialization behavior is identical to `Vec<T>`. This is an alternative to `Vec<T>`
2286/// which is resilient against unexpected data.
2287///
2288/// You can be notified of skipped elements by providing a type that implements the [`InspectError`] trait.
2289/// The second generic argument `I` defaults to `()`, which does nothing.
2290///
2291/// # Examples
2292///
2293/// ## Basic Usage
2294///
2295/// ```rust
2296/// # #[cfg(feature = "macros")] {
2297/// # use serde::{Deserialize, Serialize};
2298/// # use serde_with::{serde_as, VecSkipError};
2299/// #
2300/// # #[derive(Debug, PartialEq)]
2301/// #[derive(Deserialize, Serialize)]
2302/// # #[non_exhaustive]
2303/// enum Color {
2304///     Red,
2305///     Green,
2306///     Blue,
2307/// }
2308/// # use Color::*;
2309/// #[serde_as]
2310/// # #[derive(Debug, PartialEq)]
2311/// #[derive(Deserialize, Serialize)]
2312/// struct Palette(#[serde_as(as = "VecSkipError<_>")] Vec<Color>);
2313///
2314/// let data = Palette(vec![Blue, Green,]);
2315/// let source_json = r#"["Blue", "Yellow", "Green"]"#;
2316/// let data_json = r#"["Blue","Green"]"#;
2317/// // Ensure serialization and deserialization produce the expected results
2318/// assert_eq!(data_json, serde_json::to_string(&data).unwrap());
2319/// assert_eq!(data, serde_json::from_str(source_json).unwrap());
2320/// # }
2321/// ```
2322///
2323/// ## Using [`InspectError`](`crate::InspectError`) to log skipped elements
2324///
2325/// ```rust
2326/// # #[cfg(all(feature = "macros", feature = "alloc"))] {
2327/// # use serde::{Serialize, Deserialize};
2328/// # use serde_with::{serde_as, InspectError, VecSkipError};
2329/// # use std::cell::RefCell;
2330///
2331/// struct ErrorInspector;
2332///
2333/// thread_local! {
2334///     static ERRORS: RefCell<Vec<String>> = RefCell::new(Vec::new());
2335/// }
2336///
2337/// impl InspectError for ErrorInspector {
2338///     fn inspect_error(error: impl serde::de::Error) {
2339///         ERRORS.with(|errors| errors.borrow_mut().push(error.to_string()));
2340///     }
2341/// }
2342///
2343/// #[serde_as]
2344/// #[derive(Debug, PartialEq, Deserialize, Serialize)]
2345/// struct S {
2346///     tag: String,
2347///     #[serde_as(as = "VecSkipError<_, ErrorInspector>")]
2348///     values: Vec<u8>,
2349/// }
2350///
2351/// let json = r#"{"tag":"type","values":[0, "str", 1, [10, 11], -2, {}, 300]}"#;
2352/// let s: S = serde_json::from_str(json).unwrap();
2353/// assert_eq!(s.values, vec![0, 1]);
2354///
2355/// let errors = ERRORS.with(|errors| errors.borrow().clone());
2356/// eprintln!("Errors: {errors:#?}");
2357/// assert_eq!(errors.len(), 5);
2358/// assert!(errors[0].contains("invalid type: string \"str\", expected u8"));
2359/// assert!(errors[1].contains("invalid type: sequence, expected u8"));
2360/// assert!(errors[2].contains("invalid value: integer `-2`, expected u8"));
2361/// assert!(errors[3].contains("invalid type: map, expected u8"));
2362/// assert!(errors[4].contains("invalid value: integer `300`, expected u8"));
2363/// # }
2364/// ```
2365#[cfg(feature = "alloc")]
2366pub struct VecSkipError<T, I = ()>(PhantomData<(T, I)>);
2367
2368/// Deserialize a map, skipping keys and values which fail to deserialize.
2369///
2370/// By default serde terminates if it fails to deserialize a key or a value when deserializing
2371/// a map. Sometimes a map has heterogeneous keys or values but we only care about some specific
2372/// types, and it is desirable to skip entries on errors.
2373///
2374/// You can be notified of skipped elements by providing a type that implements the [`InspectError`] trait.
2375/// The third generic argument `I` defaults to `()`, which does nothing.
2376///
2377/// It is especially useful in conjunction to `#[serde(flatten)]` to capture a map mixed in with
2378/// other entries which we don't want to exhaust in the type definition.
2379///
2380/// The serialization behavior is identical to the underlying map.
2381///
2382/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2383///
2384/// [`BTreeMap`]: std::collections::BTreeMap
2385/// [`HashMap`]: std::collections::HashMap
2386///
2387/// # Examples
2388///
2389/// ## Basic Usage
2390///
2391/// ```rust
2392/// # #[cfg(feature = "macros")] {
2393/// # use serde::{Deserialize, Serialize};
2394/// # use std::collections::BTreeMap;
2395/// # use serde_with::{serde_as, DisplayFromStr, MapSkipError};
2396/// #
2397/// #[serde_as]
2398/// # #[derive(Debug, PartialEq)]
2399/// #[derive(Deserialize, Serialize)]
2400/// struct VersionNames {
2401///     yanked: Vec<u16>,
2402///     #[serde_as(as = "MapSkipError<DisplayFromStr, _>")]
2403///     #[serde(flatten)]
2404///     names: BTreeMap<u16, String>,
2405/// }
2406///
2407/// let data = VersionNames {
2408///     yanked: vec![2, 5],
2409///     names: BTreeMap::from_iter([
2410///         (0u16, "v0".to_string()),
2411///         (1, "v1".to_string()),
2412///         (4, "v4".to_string())
2413///     ]),
2414/// };
2415/// let source_json = r#"{
2416///   "0": "v0",
2417///   "1": "v1",
2418///   "4": "v4",
2419///   "yanked": [2, 5],
2420///   "last_updated": 1704085200
2421/// }"#;
2422/// let data_json = r#"{"yanked":[2,5],"0":"v0","1":"v1","4":"v4"}"#;
2423/// // Ensure serialization and deserialization produce the expected results
2424/// assert_eq!(data_json, serde_json::to_string(&data).unwrap());
2425/// assert_eq!(data, serde_json::from_str(source_json).unwrap());
2426/// # }
2427/// ```
2428///
2429/// ## Using [`InspectError`](`crate::InspectError`) to log skipped elements
2430///
2431/// ```rust
2432/// # #[cfg(all(feature = "macros", feature = "alloc"))] {
2433/// # use serde::{Serialize, Deserialize};
2434/// # use serde_with::{serde_as, InspectError, MapSkipError};
2435/// # use std::collections::BTreeMap;
2436/// # use std::cell::RefCell;
2437///
2438/// struct ErrorInspector;
2439///
2440/// thread_local! {
2441///     static ERRORS: RefCell<Vec<String>> = RefCell::new(Vec::new());
2442/// }
2443///
2444/// impl InspectError for ErrorInspector {
2445///     fn inspect_error(error: impl serde::de::Error) {
2446///         ERRORS.with(|errors| errors.borrow_mut().push(error.to_string()));
2447///     }
2448/// }
2449///
2450/// #[serde_as]
2451/// #[derive(Debug, PartialEq, Deserialize, Serialize)]
2452/// struct S {
2453///     tag: String,
2454///     #[serde_as(as = "MapSkipError<_, _, ErrorInspector>")]
2455///     values: BTreeMap<String, u8>,
2456/// }
2457///
2458/// let json = r#"{"tag":"type","values":{"valid":42,"invalid": null,"another":"str","nested":[1,2,3]}}"#;
2459/// let s: S = serde_json::from_str(json).unwrap();
2460/// assert_eq!(s.values.len(), 1);
2461/// assert_eq!(s.values.get("valid"), Some(&42));
2462///
2463/// let errors = ERRORS.with(|errors| errors.borrow().clone());
2464/// assert_eq!(errors.len(), 3);
2465/// eprintln!("Errors: {errors:#?}");
2466/// assert!(errors[0].contains("invalid type: null, expected u8"));
2467/// assert!(errors[1].contains("invalid type: string \"str\", expected u8"));
2468/// assert!(errors[2].contains("invalid type: sequence, expected u8"));
2469/// # }
2470/// ```
2471#[cfg(feature = "alloc")]
2472pub struct MapSkipError<K, V, I = ()>(PhantomData<(K, V, I)>);
2473
2474/// Deserialize a boolean from a number
2475///
2476/// Deserialize a number (of `u8`) and turn it into a boolean.
2477/// The adapter supports a [`Strict`](crate::formats::Strict) and [`Flexible`](crate::formats::Flexible) format.
2478/// In `Strict` mode, the number must be `0` or `1`.
2479/// All other values produce an error.
2480/// In `Flexible` mode, the number any non-zero value is converted to `true`.
2481///
2482/// During serialization only `0` or `1` are ever emitted.
2483///
2484/// # Examples
2485///
2486/// ```rust
2487/// # #[cfg(feature = "macros")] {
2488/// # use serde::{Deserialize, Serialize};
2489/// # use serde_json::json;
2490/// # use serde_with::{serde_as, BoolFromInt};
2491/// #
2492/// #[serde_as]
2493/// # #[derive(Debug, PartialEq)]
2494/// #[derive(Deserialize, Serialize)]
2495/// struct Data(#[serde_as(as = "BoolFromInt")] bool);
2496///
2497/// let data = Data(true);
2498/// let j = json!(1);
2499/// // Ensure serialization and deserialization produce the expected results
2500/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2501/// assert_eq!(data, serde_json::from_value(j).unwrap());
2502///
2503/// // false maps to 0
2504/// let data = Data(false);
2505/// let j = json!(0);
2506/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2507/// assert_eq!(data, serde_json::from_value(j).unwrap());
2508//
2509/// #[serde_as]
2510/// # #[derive(Debug, PartialEq)]
2511/// #[derive(Deserialize, Serialize)]
2512/// struct Flexible(#[serde_as(as = "BoolFromInt<serde_with::formats::Flexible>")] bool);
2513///
2514/// // Flexible turns any non-zero number into true
2515/// let data = Flexible(true);
2516/// let j = json!(100);
2517/// assert_eq!(data, serde_json::from_value(j).unwrap());
2518/// # }
2519/// ```
2520pub struct BoolFromInt<S: formats::Strictness = formats::Strict>(PhantomData<S>);
2521
2522/// De/Serialize a delimited collection using [`Display`] and [`FromStr`] implementation
2523///
2524/// `StringWithSeparator` takes a second type, which needs to implement [`Display`]+[`FromStr`] and constitutes the inner type of the collection.
2525/// You can define an arbitrary separator, by specifying a type which implements [`Separator`].
2526/// Some common ones, like space and comma are already predefined and you can find them [here][`Separator`].
2527///
2528/// An empty string deserializes as an empty collection.
2529///
2530/// # Examples
2531///
2532/// ```
2533/// # #[cfg(feature = "macros")] {
2534/// # use serde::{Deserialize, Serialize};
2535/// #
2536/// # use serde_with::{serde_as, StringWithSeparator};
2537/// use serde_with::formats::{CommaSeparator, SpaceSeparator};
2538/// use std::collections::BTreeSet;
2539///
2540/// #[serde_as]
2541/// #[derive(Deserialize, Serialize)]
2542/// struct A {
2543///     #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
2544///     tags: Vec<String>,
2545///     #[serde_as(as = "StringWithSeparator::<CommaSeparator, String>")]
2546///     more_tags: BTreeSet<String>,
2547/// }
2548///
2549/// let v: A = serde_json::from_str(r##"{
2550///     "tags": "#hello #world",
2551///     "more_tags": "foo,bar,bar"
2552/// }"##).unwrap();
2553/// assert_eq!(vec!["#hello", "#world"], v.tags);
2554/// assert_eq!(2, v.more_tags.len());
2555///
2556/// let x = A {
2557///     tags: vec!["1".to_string(), "2".to_string(), "3".to_string()],
2558///     more_tags: BTreeSet::new(),
2559/// };
2560/// assert_eq!(
2561///     r#"{"tags":"1 2 3","more_tags":""}"#,
2562///     serde_json::to_string(&x).unwrap()
2563/// );
2564/// # }
2565/// ```
2566///
2567/// [`Display`]: core::fmt::Display
2568/// [`FromStr`]: core::str::FromStr
2569/// [`Separator`]: crate::formats::Separator
2570/// [`serde_as`]: crate::guide::serde_as
2571pub struct StringWithSeparator<Sep, T>(PhantomData<(Sep, T)>);
2572
2573/// This serializes a list of tuples into a map
2574///
2575/// Normally, you want to use a [`HashMap`] or a [`BTreeMap`] when deserializing a map.
2576/// However, sometimes this is not possible due to type constraints, e.g., if the type implements neither [`Hash`] nor [`Ord`].
2577/// Another use case is deserializing a map with duplicate keys.
2578///
2579/// # Examples
2580///
2581/// `Wrapper` does not implement [`Hash`] nor [`Ord`], thus prohibiting the use [`HashMap`] or [`BTreeMap`].
2582/// The JSON also contains a duplicate key.
2583///
2584/// [`BTreeMap`]: std::collections::BTreeMap
2585/// [`HashMap`]: std::collections::HashMap
2586/// [`Vec`]: std::vec::Vec
2587///
2588/// ```rust
2589/// # #[cfg(feature = "macros")] {
2590/// # use serde::{Deserialize, Serialize};
2591/// # use serde_with::{serde_as, Map};
2592/// #
2593/// #[serde_as]
2594/// #[derive(Debug, Deserialize, Serialize, Default)]
2595/// struct S {
2596///     #[serde_as(as = "Map<_, _>")]
2597///     s: Vec<(Wrapper<i32>, String)>,
2598/// }
2599///
2600/// #[derive(Clone, Debug, Serialize, Deserialize)]
2601/// #[serde(transparent)]
2602/// struct Wrapper<T>(T);
2603///
2604/// let data = S {
2605///     s: vec![
2606///         (Wrapper(1), "a".to_string()),
2607///         (Wrapper(2), "b".to_string()),
2608///         (Wrapper(3), "c".to_string()),
2609///         (Wrapper(2), "d".to_string()),
2610///     ],
2611/// };
2612///
2613/// let json = r#"{
2614///   "s": {
2615///     "1": "a",
2616///     "2": "b",
2617///     "3": "c",
2618///     "2": "d"
2619///   }
2620/// }"#;
2621/// assert_eq!(json, serde_json::to_string_pretty(&data).unwrap());
2622/// # }
2623/// ```
2624pub struct Map<K, V>(PhantomData<(K, V)>);
2625
2626/// De/Serialize a Map into a list of tuples
2627///
2628/// Some formats, like JSON, have limitations on the types of keys for maps.
2629/// In case of JSON, keys are restricted to strings.
2630/// Rust features more powerful keys, for example tuples, which can not be serialized to JSON.
2631///
2632/// This helper serializes the Map into a list of tuples, which do not have the same type restrictions.
2633///
2634/// # Examples
2635///
2636/// ```rust
2637/// # #[cfg(feature = "macros")] {
2638/// # use serde::{Deserialize, Serialize};
2639/// # use serde_json::json;
2640/// # use serde_with::{serde_as, Seq};
2641/// # use std::collections::BTreeMap;
2642/// #
2643/// #[serde_as]
2644/// # #[derive(Debug, PartialEq)]
2645/// #[derive(Deserialize, Serialize)]
2646/// struct A {
2647///     #[serde_as(as = "Seq<(_, _)>")]
2648///     s: BTreeMap<(String, u32), u32>,
2649/// }
2650///
2651/// // This converts the Rust type
2652/// let data = A {
2653///     s: BTreeMap::from([
2654///         (("Hello".to_string(), 123), 0),
2655///         (("World".to_string(), 456), 1),
2656///     ]),
2657/// };
2658///
2659/// // into this JSON
2660/// let value = json!({
2661///     "s": [
2662///         [["Hello", 123], 0],
2663///         [["World", 456], 1]
2664///     ]
2665/// });
2666///
2667/// assert_eq!(value, serde_json::to_value(&data).unwrap());
2668/// assert_eq!(data, serde_json::from_value(value).unwrap());
2669/// # }
2670/// ```
2671pub struct Seq<V>(PhantomData<V>);
2672
2673/// Ensure no duplicate keys exist in a map.
2674///
2675/// By default serde has a last-value-wins implementation, if duplicate keys for a map exist.
2676/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
2677/// and it can indicate an error in the serialized data.
2678///
2679/// This helper returns an error if two identical keys exist in a map.
2680///
2681/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2682///
2683/// [`BTreeMap`]: std::collections::BTreeMap
2684/// [`HashMap`]: std::collections::HashMap
2685///
2686/// # Example
2687///
2688/// ```rust
2689/// # #[cfg(feature = "macros")] {
2690/// # use serde::Deserialize;
2691/// # use std::collections::HashMap;
2692/// # use serde_with::{serde_as, MapPreventDuplicates};
2693/// #
2694/// #[serde_as]
2695/// # #[derive(Debug, Eq, PartialEq)]
2696/// #[derive(Deserialize)]
2697/// struct Doc {
2698///     #[serde_as(as = "MapPreventDuplicates<_, _>")]
2699///     map: HashMap<usize, usize>,
2700/// }
2701///
2702/// // Maps are serialized normally,
2703/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
2704/// let mut v = Doc {
2705///     map: HashMap::new(),
2706/// };
2707/// v.map.insert(1, 1);
2708/// v.map.insert(2, 2);
2709/// v.map.insert(3, 3);
2710/// assert_eq!(v, serde_json::from_str(s).unwrap());
2711///
2712/// // but create an error if duplicate keys, like the `1`, exist.
2713/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
2714/// let res: Result<Doc, _> = serde_json::from_str(s);
2715/// assert!(res.is_err());
2716/// # }
2717/// ```
2718#[cfg(feature = "alloc")]
2719pub struct MapPreventDuplicates<K, V>(PhantomData<(K, V)>);
2720
2721/// Ensure that the first key is taken, if duplicate keys exist
2722///
2723/// By default serde has a last-key-wins implementation, if duplicate keys for a map exist.
2724/// Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.
2725///
2726/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2727///
2728/// [`BTreeMap`]: std::collections::BTreeMap
2729/// [`HashMap`]: std::collections::HashMap
2730#[cfg(feature = "alloc")]
2731pub struct MapFirstKeyWins<K, V>(PhantomData<(K, V)>);
2732
2733/// Ensure no duplicate values exist in a set.
2734///
2735/// By default serde has a last-value-wins implementation, if duplicate values for a set exist.
2736/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
2737/// and it can indicate an error in the serialized data.
2738///
2739/// This helper returns an error if two identical values exist in a set.
2740///
2741/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
2742///
2743/// [`BTreeSet`]: std::collections::BTreeSet
2744/// [`HashSet`]: std::collections::HashSet
2745///
2746/// # Example
2747///
2748/// ```rust
2749/// # #[cfg(feature = "macros")] {
2750/// # use std::collections::HashSet;
2751/// # use serde::Deserialize;
2752/// # use serde_with::{serde_as, SetPreventDuplicates};
2753/// #
2754/// #[serde_as]
2755/// # #[derive(Debug, Eq, PartialEq)]
2756/// #[derive(Deserialize)]
2757/// struct Doc {
2758///     #[serde_as(as = "SetPreventDuplicates<_>")]
2759///     set: HashSet<usize>,
2760/// }
2761///
2762/// // Sets are serialized normally,
2763/// let s = r#"{"set": [1, 2, 3, 4]}"#;
2764/// let v = Doc {
2765///     set: HashSet::from_iter(vec![1, 2, 3, 4]),
2766/// };
2767/// assert_eq!(v, serde_json::from_str(s).unwrap());
2768///
2769/// // but create an error if duplicate values, like the `1`, exist.
2770/// let s = r#"{"set": [1, 2, 3, 4, 1]}"#;
2771/// let res: Result<Doc, _> = serde_json::from_str(s);
2772/// assert!(res.is_err());
2773/// # }
2774/// ```
2775#[cfg(feature = "alloc")]
2776pub struct SetPreventDuplicates<T>(PhantomData<T>);
2777
2778/// Ensure that the last value is taken, if duplicate values exist
2779///
2780/// By default serde has a first-value-wins implementation, if duplicate keys for a set exist.
2781/// Sometimes the opposite strategy is desired. This helper implements a first-value-wins strategy.
2782///
2783/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
2784///
2785/// [`BTreeSet`]: std::collections::BTreeSet
2786/// [`HashSet`]: std::collections::HashSet
2787#[cfg(feature = "alloc")]
2788pub struct SetLastValueWins<T>(PhantomData<T>);
2789
2790/// Helper for implementing [`JsonSchema`] on serializers whose output depends
2791/// on the type of the concrete field.
2792///
2793/// It is added implicitly by the [`#[serde_as]`](crate::serde_as) macro when any `schemars`
2794/// feature is enabled.
2795///
2796/// [`JsonSchema`]: ::schemars_1::JsonSchema
2797#[cfg(any(
2798    feature = "schemars_0_8",
2799    feature = "schemars_0_9",
2800    feature = "schemars_1"
2801))]
2802pub struct Schema<T: ?Sized, TA>(PhantomData<T>, PhantomData<TA>);