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.20.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.20.0/serde_with/struct.DisplayFromStr.html
257//! [`with_prefix!`]: https://docs.rs/serde_with/3.20.0/serde_with/macro.with_prefix.html
258//! [`with_suffix!`]: https://docs.rs/serde_with/3.20.0/serde_with/macro.with_suffix.html
259//! [feature flags]: https://docs.rs/serde_with/3.20.0/serde_with/guide/feature_flags/index.html
260//! [skip_serializing_none]: https://docs.rs/serde_with/3.20.0/serde_with/attr.skip_serializing_none.html
261//! [StringWithSeparator]: https://docs.rs/serde_with/3.20.0/serde_with/struct.StringWithSeparator.html
262//! [user guide]: https://docs.rs/serde_with/3.20.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.20.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 = "json")]
307#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
308pub mod json;
309#[cfg(feature = "alloc")]
310mod key_value_map;
311pub mod rust;
312#[cfg(feature = "schemars_0_8")]
313#[cfg_attr(docsrs, doc(cfg(feature = "schemars_0_8")))]
314pub mod schemars_0_8;
315#[cfg(feature = "schemars_0_9")]
316#[cfg_attr(docsrs, doc(cfg(feature = "schemars_0_9")))]
317pub mod schemars_0_9;
318#[cfg(feature = "schemars_1")]
319#[cfg_attr(docsrs, doc(cfg(feature = "schemars_1")))]
320pub mod schemars_1;
321pub mod ser;
322mod serde_conv;
323#[cfg(feature = "time_0_3")]
324#[cfg_attr(docsrs, doc(cfg(feature = "time_0_3")))]
325pub mod time_0_3;
326mod utils;
327#[cfg(feature = "std")]
328#[doc(hidden)]
329pub mod with_prefix;
330#[cfg(feature = "std")]
331#[doc(hidden)]
332pub mod with_suffix;
333
334// Taken from shepmaster/snafu
335// Originally licensed as MIT+Apache 2
336// https://github.com/shepmaster/snafu/blob/90991b609e8928ceebf7df1b040408539d21adda/src/lib.rs#L343-L376
337#[cfg(feature = "guide")]
338#[allow(unused_macro_rules)]
339macro_rules! generate_guide {
340    (pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
341        generate_guide!(@gen ".", pub mod $name { $($children)* } $($rest)*);
342    };
343    (@gen $prefix:expr, ) => {};
344    (@gen $prefix:expr, pub mod $name:ident; $($rest:tt)*) => {
345        generate_guide!(@gen $prefix, pub mod $name { } $($rest)*);
346    };
347    (@gen $prefix:expr, @code pub mod $name:ident; $($rest:tt)*) => {
348        #[cfg(feature = "guide")]
349        pub mod $name;
350
351        #[cfg(not(feature = "guide"))]
352        /// Not currently built; please add the `guide` feature flag.
353        pub mod $name {}
354
355        generate_guide!(@gen $prefix, $($rest)*);
356    };
357    (@gen $prefix:expr, pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
358        #[cfg(feature = "guide")]
359        #[doc = include_str!(concat!($prefix, "/", stringify!($name), ".md"))]
360        pub mod $name {
361            generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
362        }
363        #[cfg(not(feature = "guide"))]
364        /// Not currently built; please add the `guide` feature flag.
365        pub mod $name {
366            generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
367        }
368
369        generate_guide!(@gen $prefix, $($rest)*);
370    };
371}
372
373#[cfg(feature = "guide")]
374generate_guide! {
375    pub mod guide {
376        @code pub mod feature_flags;
377        pub mod serde_as;
378        pub mod serde_as_transformations;
379    }
380}
381
382pub(crate) mod prelude {
383    #![allow(unused_imports)]
384
385    pub(crate) use crate::utils::duration::{DurationSigned, Sign};
386    pub use crate::{de::*, ser::*, *};
387    #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
388    pub use alloc::sync::{Arc, Weak as ArcWeak};
389    #[cfg(feature = "alloc")]
390    pub use alloc::{
391        borrow::{Cow, ToOwned},
392        boxed::Box,
393        collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque},
394        rc::{Rc, Weak as RcWeak},
395        string::{String, ToString},
396        vec::Vec,
397    };
398    pub use core::{
399        cell::{Cell, RefCell},
400        convert::{TryFrom, TryInto},
401        fmt::{self, Display},
402        hash::{BuildHasher, Hash},
403        marker::PhantomData,
404        ops::{Bound, Range, RangeFrom, RangeInclusive, RangeTo},
405        option::Option,
406        pin::Pin,
407        result::Result,
408        str::{self, FromStr},
409        time::Duration,
410    };
411    pub use serde_core::{
412        de::{
413            Deserialize, DeserializeOwned, DeserializeSeed, Deserializer, EnumAccess,
414            Error as DeError, Expected, IgnoredAny, IntoDeserializer, MapAccess, SeqAccess,
415            Unexpected, VariantAccess, Visitor,
416        },
417        forward_to_deserialize_any,
418        ser::{
419            Error as SerError, Impossible, Serialize, SerializeMap, SerializeSeq, SerializeStruct,
420            SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant,
421            Serializer,
422        },
423    };
424    #[cfg(feature = "std")]
425    pub use std::{
426        collections::{HashMap, HashSet},
427        sync::{Mutex, RwLock},
428        time::SystemTime,
429    };
430}
431
432/// This module is not part of the public API
433///
434/// Do not rely on any exports.
435#[doc(hidden)]
436pub mod __private__ {
437    pub use crate::prelude::*;
438}
439
440#[cfg(feature = "alloc")]
441#[doc(inline)]
442pub use crate::enum_map::EnumMap;
443#[cfg(feature = "alloc")]
444#[doc(inline)]
445pub use crate::key_value_map::KeyValueMap;
446#[doc(inline)]
447pub use crate::{de::DeserializeAs, ser::SerializeAs};
448use core::marker::PhantomData;
449// Re-Export all proc_macros, as these should be seen as part of the serde_with crate
450#[cfg(feature = "macros")]
451#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
452#[doc(inline)]
453pub use serde_with_macros::*;
454
455/// Adapter to convert from `serde_as` to the serde traits.
456///
457/// The `As` type adapter allows using types which implement [`DeserializeAs`] or [`SerializeAs`] in place of serde's `with` annotation.
458/// The `with` annotation allows running custom code when de/serializing, however it is quite inflexible.
459/// The traits [`DeserializeAs`]/[`SerializeAs`] are more flexible, as they allow composition and nesting of types to create more complex de/serialization behavior.
460/// However, they are not directly compatible with serde, as they are not provided by serde.
461/// The `As` type adapter makes them compatible, by forwarding the function calls to `serialize`/`deserialize` to the corresponding functions `serialize_as` and `deserialize_as`.
462///
463/// It is not required to use this type directly.
464/// Instead, it is highly encouraged to use the [`#[serde_as]`][serde_as] attribute since it includes further usability improvements.
465/// If the use of the use of the proc-macro is not acceptable, then `As` can be used directly with serde.
466///
467/// ```rust
468/// # #[cfg(feature = "alloc")] {
469/// # use serde::{Deserialize, Serialize};
470/// # use serde_with::{As, DisplayFromStr};
471/// #
472/// # #[allow(dead_code)]
473/// #[derive(Deserialize, Serialize)]
474/// # struct S {
475/// // Serialize numbers as sequence of strings, using Display and FromStr
476/// #[serde(with = "As::<Vec<DisplayFromStr>>")]
477/// field: Vec<u8>,
478/// # }
479/// # }
480/// ```
481/// If the normal `Deserialize`/`Serialize` traits should be used, the placeholder type [`Same`] can be used.
482/// It implements [`DeserializeAs`][]/[`SerializeAs`][], when the underlying type implements `Deserialize`/`Serialize`.
483///
484/// ```rust
485/// # #[cfg(feature = "alloc")] {
486/// # use serde::{Deserialize, Serialize};
487/// # use serde_with::{As, DisplayFromStr, Same};
488/// # use std::collections::BTreeMap;
489/// #
490/// # #[allow(dead_code)]
491/// #[derive(Deserialize, Serialize)]
492/// # struct S {
493/// // Serialize map, turn keys into strings but keep type of value
494/// #[serde(with = "As::<BTreeMap<DisplayFromStr, Same>>")]
495/// field: BTreeMap<u8, i32>,
496/// # }
497/// # }
498/// ```
499///
500/// [serde_as]: https://docs.rs/serde_with/3.20.0/serde_with/attr.serde_as.html
501pub struct As<T: ?Sized>(PhantomData<T>);
502
503/// Adapter to convert from `serde_as` to the serde traits.
504///
505/// This is the counter-type to [`As`][].
506/// 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.
507/// Check [`As`] for an example.
508pub struct Same;
509
510/// De/Serialize using [`Display`] and [`FromStr`] implementation
511///
512/// This allows deserializing a string as a number.
513/// It can be very useful for serialization formats like JSON, which do not support integer
514/// numbers and have to resort to strings to represent them.
515///
516/// Another use case is types with [`Display`] and [`FromStr`] implementations, but without serde
517/// support, which can be found in some crates.
518///
519/// If you control the type you want to de/serialize, you can instead use the two derive macros, [`SerializeDisplay`] and [`DeserializeFromStr`].
520/// 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.
521///
522/// # Examples
523///
524/// ```rust
525/// # #[cfg(feature = "macros")] {
526/// # use serde::{Deserialize, Serialize};
527/// # use serde_json::json;
528/// # use serde_with::{serde_as, DisplayFromStr};
529/// #
530/// #[serde_as]
531/// #[derive(Deserialize, Serialize)]
532/// struct A {
533///     #[serde_as(as = "DisplayFromStr")]
534///     mime: mime::Mime,
535///     #[serde_as(as = "DisplayFromStr")]
536///     number: u32,
537/// }
538///
539/// let v: A = serde_json::from_value(json!({
540///     "mime": "text/plain",
541///     "number": "159",
542/// })).unwrap();
543/// assert_eq!(mime::TEXT_PLAIN, v.mime);
544/// assert_eq!(159, v.number);
545///
546/// let x = A {
547///     mime: mime::STAR_STAR,
548///     number: 777,
549/// };
550/// assert_eq!(json!({ "mime": "*/*", "number": "777" }), serde_json::to_value(x).unwrap());
551/// # }
552/// ```
553///
554/// [`Display`]: std::fmt::Display
555/// [`FromStr`]: std::str::FromStr
556pub struct DisplayFromStr;
557
558/// Use the first format if [`De/Serializer::is_human_readable`], otherwise use the second
559///
560/// If the second format is not specified, the normal
561/// [`Deserialize`](::serde_core::Deserialize)/[`Serialize`](::serde_core::Serialize) traits are used.
562///
563/// # Examples
564///
565/// ```rust
566/// # #[cfg(feature = "macros")] {
567/// # use serde::{Deserialize, Serialize};
568/// # use serde_json::json;
569/// # use serde_with::{serde_as, DisplayFromStr, IfIsHumanReadable, DurationMilliSeconds, DurationSeconds};
570/// use std::time::Duration;
571///
572/// #[serde_as]
573/// #[derive(Deserialize, Serialize)]
574/// struct A {
575///     #[serde_as(as = "IfIsHumanReadable<DisplayFromStr>")]
576///     number: u32,
577/// }
578/// let x = A {
579///     number: 777,
580/// };
581/// assert_eq!(json!({ "number": "777" }), serde_json::to_value(&x).unwrap());
582/// assert_eq!(vec![145, 205, 3, 9], rmp_serde::to_vec(&x).unwrap());
583///
584/// #[serde_as]
585/// #[derive(Deserialize, Serialize)]
586/// struct B {
587///     #[serde_as(as = "IfIsHumanReadable<DurationMilliSeconds, DurationSeconds>")]
588///     duration: Duration,
589/// }
590/// let x = B {
591///     duration: Duration::from_millis(1500),
592/// };
593/// assert_eq!(json!({ "duration": 1500 }), serde_json::to_value(&x).unwrap());
594/// assert_eq!(vec![145, 2], rmp_serde::to_vec(&x).unwrap());
595/// # }
596/// ```
597/// [`De/Serializer::is_human_readable`]: serde_core::Serializer::is_human_readable
598/// [`is_human_readable`]: serde_core::Serializer::is_human_readable
599pub struct IfIsHumanReadable<H, F = Same>(PhantomData<H>, PhantomData<F>);
600
601/// De/Serialize a [`Option<String>`] type while transforming the empty string to [`None`]
602///
603/// Convert an [`Option<T>`] from/to string using [`FromStr`] and [`Display`](::core::fmt::Display) implementations.
604/// An empty string is deserialized as [`None`] and a [`None`] vice versa.
605///
606/// # Examples
607///
608/// ```
609/// # #[cfg(feature = "macros")] {
610/// # use serde::{Deserialize, Serialize};
611/// # use serde_json::json;
612/// # use serde_with::{serde_as, NoneAsEmptyString};
613/// #
614/// #[serde_as]
615/// #[derive(Deserialize, Serialize)]
616/// struct A {
617///     #[serde_as(as = "NoneAsEmptyString")]
618///     tags: Option<String>,
619/// }
620///
621/// let v: A = serde_json::from_value(json!({ "tags": "" })).unwrap();
622/// assert_eq!(None, v.tags);
623///
624/// let v: A = serde_json::from_value(json!({ "tags": "Hi" })).unwrap();
625/// assert_eq!(Some("Hi".to_string()), v.tags);
626///
627/// let x = A {
628///     tags: Some("This is text".to_string()),
629/// };
630/// assert_eq!(json!({ "tags": "This is text" }), serde_json::to_value(x).unwrap());
631///
632/// let x = A {
633///     tags: None,
634/// };
635/// assert_eq!(json!({ "tags": "" }), serde_json::to_value(x).unwrap());
636/// # }
637/// ```
638///
639/// [`FromStr`]: std::str::FromStr
640pub struct NoneAsEmptyString;
641
642/// Deserialize value and return [`Default`] on error
643///
644/// The main use case is ignoring error while deserializing.
645/// Instead of erroring, it simply deserializes the [`Default`] variant of the type.
646/// It is not possible to find the error location, i.e., which field had a deserialization error, with this method.
647/// During serialization this wrapper does nothing.
648/// The serialization behavior of the underlying type is preserved.
649/// The type must implement [`Default`] for this conversion to work.
650///
651/// # Examples
652///
653/// ```
654/// # #[cfg(feature = "macros")] {
655/// # use serde::Deserialize;
656/// # use serde_with::{serde_as, DefaultOnError};
657/// #
658/// #[serde_as]
659/// #[derive(Deserialize, Debug)]
660/// struct A {
661///     #[serde_as(deserialize_as = "DefaultOnError")]
662///     value: u32,
663/// }
664///
665/// let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
666/// assert_eq!(123, a.value);
667///
668/// // null is of invalid type
669/// let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
670/// assert_eq!(0, a.value);
671///
672/// // String is of invalid type
673/// let a: A = serde_json::from_str(r#"{"value": "123"}"#).unwrap();
674/// assert_eq!(0, a.value);
675///
676/// // Map is of invalid type
677/// let a: A = dbg!(serde_json::from_str(r#"{"value": {}}"#)).unwrap();
678/// assert_eq!(0, a.value);
679///
680/// // Missing entries still cause errors
681/// assert!(serde_json::from_str::<A>(r#"{  }"#).is_err());
682/// # }
683/// ```
684///
685/// Deserializing missing values can be supported by adding the `default` field attribute:
686///
687/// ```
688/// # #[cfg(feature = "macros")] {
689/// # use serde::Deserialize;
690/// # use serde_with::{serde_as, DefaultOnError};
691/// #
692/// #[serde_as]
693/// #[derive(Deserialize)]
694/// struct B {
695///     #[serde_as(deserialize_as = "DefaultOnError")]
696///     #[serde(default)]
697///     value: u32,
698/// }
699///
700/// let b: B = serde_json::from_str(r#"{  }"#).unwrap();
701/// assert_eq!(0, b.value);
702/// # }
703/// ```
704///
705/// `DefaultOnError` can be combined with other conversion methods.
706/// In this example, we deserialize a `Vec`, each element is deserialized from a string.
707/// If the string does not parse as a number, then we get the default value of 0.
708///
709/// ```rust
710/// # #[cfg(feature = "macros")] {
711/// # use serde::{Deserialize, Serialize};
712/// # use serde_json::json;
713/// # use serde_with::{serde_as, DefaultOnError, DisplayFromStr};
714/// #
715/// #[serde_as]
716/// #[derive(Serialize, Deserialize)]
717/// struct C {
718///     #[serde_as(as = "Vec<DefaultOnError<DisplayFromStr>>")]
719///     value: Vec<u32>,
720/// }
721///
722/// let c: C = serde_json::from_value(json!({
723///     "value": ["1", "2", "a3", "", {}, "6"]
724/// })).unwrap();
725/// assert_eq!(vec![1, 2, 0, 0, 0, 6], c.value);
726/// # }
727/// ```
728#[cfg(feature = "alloc")]
729pub struct DefaultOnError<T = Same>(PhantomData<T>);
730
731/// Deserialize [`Default`] from `null` values
732///
733/// Instead of erroring on `null` values, it simply deserializes the [`Default`] variant of the type.
734/// During serialization this wrapper does nothing.
735/// The serialization behavior of the underlying type is preserved.
736/// The type must implement [`Default`] for this conversion to work.
737///
738/// # Examples
739///
740/// ```
741/// # #[cfg(feature = "macros")] {
742/// # use serde::Deserialize;
743/// # use serde_with::{serde_as, DefaultOnNull};
744/// #
745/// #[serde_as]
746/// #[derive(Deserialize, Debug)]
747/// struct A {
748///     #[serde_as(deserialize_as = "DefaultOnNull")]
749///     value: u32,
750/// }
751///
752/// let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
753/// assert_eq!(123, a.value);
754///
755/// // null values are deserialized into the default, here 0
756/// let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
757/// assert_eq!(0, a.value);
758/// # }
759/// ```
760///
761/// `DefaultOnNull` can be combined with other conversion methods.
762/// In this example, we deserialize a `Vec`, each element is deserialized from a string.
763/// If we encounter null, 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, DefaultOnNull, DisplayFromStr};
770/// #
771/// #[serde_as]
772/// #[derive(Serialize, Deserialize)]
773/// struct C {
774///     #[serde_as(as = "Vec<DefaultOnNull<DisplayFromStr>>")]
775///     value: Vec<u32>,
776/// }
777///
778/// let c: C = serde_json::from_value(json!({
779///     "value": ["1", "2", null, null, "5"]
780/// })).unwrap();
781/// assert_eq!(vec![1, 2, 0, 0, 5], c.value);
782/// # }
783/// ```
784pub struct DefaultOnNull<T = Same>(PhantomData<T>);
785
786/// Deserialize from bytes or string
787///
788/// Any Rust [`String`] can be converted into bytes, i.e., `Vec<u8>`.
789/// Accepting both as formats while deserializing can be helpful while interacting with language
790/// which have a looser definition of string than Rust.
791///
792/// # Example
793/// ```rust
794/// # #[cfg(feature = "macros")] {
795/// # use serde::{Deserialize, Serialize};
796/// # use serde_json::json;
797/// # use serde_with::{serde_as, BytesOrString};
798/// #
799/// #[serde_as]
800/// #[derive(Deserialize, Serialize)]
801/// struct A {
802///     #[serde_as(as = "BytesOrString")]
803///     bytes_or_string: Vec<u8>,
804/// }
805///
806/// // Here we deserialize from a byte array ...
807/// let j = json!({
808///   "bytes_or_string": [
809///     0,
810///     1,
811///     2,
812///     3
813///   ]
814/// });
815///
816/// let a: A = serde_json::from_value(j.clone()).unwrap();
817/// assert_eq!(vec![0, 1, 2, 3], a.bytes_or_string);
818///
819/// // and serialization works too.
820/// assert_eq!(j, serde_json::to_value(&a).unwrap());
821///
822/// // But we also support deserializing from a String
823/// let j = json!({
824///   "bytes_or_string": "✨Works!"
825/// });
826///
827/// let a: A = serde_json::from_value(j).unwrap();
828/// assert_eq!("✨Works!".as_bytes(), &*a.bytes_or_string);
829/// # }
830/// ```
831/// [`String`]: std::string::String
832#[cfg(feature = "alloc")]
833pub struct BytesOrString;
834
835/// De/Serialize Durations as number of seconds.
836///
837/// De/serialize durations as number of seconds with sub-second precision.
838/// Sub-second precision is *only* supported for [`DurationSecondsWithFrac`], but not for [`DurationSeconds`].
839/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
840///
841/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
842/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `u64` deserialization from a `f64` will error.
843/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct duration and allows deserialization from any type.
844/// For example, deserializing `DurationSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
845/// Serialization of integers will round the duration to the nearest value.
846///
847/// This type also supports [`chrono::Duration`] with the `chrono_0_4`-[feature flag].
848/// This type also supports [`time::Duration`][::time_0_3::Duration] with the `time_0_3`-[feature flag].
849///
850/// This table lists the available `FORMAT`s for the different duration types.
851/// The `FORMAT` specifier defaults to `u64`/`f64`.
852///
853/// | Duration Type         | Converter                 | Available `FORMAT`s      |
854/// | --------------------- | ------------------------- | ------------------------ |
855/// | `std::time::Duration` | `DurationSeconds`         | *`u64`*, `f64`, `String` |
856/// | `std::time::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String`        |
857/// | `chrono::Duration`    | `DurationSeconds`         | `i64`, `f64`, `String`   |
858/// | `chrono::Duration`    | `DurationSecondsWithFrac` | *`f64`*, `String`        |
859/// | `time::Duration`      | `DurationSeconds`         | `i64`, `f64`, `String`   |
860/// | `time::Duration`      | `DurationSecondsWithFrac` | *`f64`*, `String`        |
861///
862/// # Examples
863///
864/// ```rust
865/// # #[cfg(feature = "macros")] {
866/// # use serde::{Deserialize, Serialize};
867/// # use serde_json::json;
868/// # use serde_with::{serde_as, DurationSeconds};
869/// use std::time::Duration;
870///
871/// #[serde_as]
872/// # #[derive(Debug, PartialEq)]
873/// #[derive(Deserialize, Serialize)]
874/// struct Durations {
875///     #[serde_as(as = "DurationSeconds<u64>")]
876///     d_u64: Duration,
877///     #[serde_as(as = "DurationSeconds<f64>")]
878///     d_f64: Duration,
879///     #[serde_as(as = "DurationSeconds<String>")]
880///     d_string: Duration,
881/// }
882///
883/// // Serialization
884/// // See how the values get rounded, since subsecond precision is not allowed.
885///
886/// let d = Durations {
887///     d_u64: Duration::new(12345, 0), // Create from seconds and nanoseconds
888///     d_f64: Duration::new(12345, 500_000_000),
889///     d_string: Duration::new(12345, 999_999_999),
890/// };
891/// // Observe the different data types
892/// let expected = json!({
893///     "d_u64": 12345,
894///     "d_f64": 12346.0,
895///     "d_string": "12346",
896/// });
897/// assert_eq!(expected, serde_json::to_value(d).unwrap());
898///
899/// // Deserialization works too
900/// // Subsecond precision in numbers will be rounded away
901///
902/// let json = json!({
903///     "d_u64": 12345,
904///     "d_f64": 12345.5,
905///     "d_string": "12346",
906/// });
907/// let expected = Durations {
908///     d_u64: Duration::new(12345, 0), // Create from seconds and nanoseconds
909///     d_f64: Duration::new(12346, 0),
910///     d_string: Duration::new(12346, 0),
911/// };
912/// assert_eq!(expected, serde_json::from_value(json).unwrap());
913/// # }
914/// ```
915///
916/// [`chrono::Duration`] is also supported when using the `chrono_0_4` feature.
917/// It is a signed duration, thus can be de/serialized as an `i64` instead of a `u64`.
918///
919/// ```rust
920/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
921/// # use serde::{Deserialize, Serialize};
922/// # use serde_json::json;
923/// # use serde_with::{serde_as, DurationSeconds};
924/// # use chrono_0_4::Duration;
925/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
926/// use chrono::Duration;
927/// # */
928///
929/// #[serde_as]
930/// # #[derive(Debug, PartialEq)]
931/// #[derive(Deserialize, Serialize)]
932/// struct Durations {
933///     #[serde_as(as = "DurationSeconds<i64>")]
934///     d_i64: Duration,
935///     #[serde_as(as = "DurationSeconds<f64>")]
936///     d_f64: Duration,
937///     #[serde_as(as = "DurationSeconds<String>")]
938///     d_string: Duration,
939/// }
940///
941/// // Serialization
942/// // See how the values get rounded, since subsecond precision is not allowed.
943///
944/// let d = Durations {
945///     d_i64: Duration::seconds(-12345),
946///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
947///     d_string: Duration::seconds(12345) + Duration::nanoseconds(999_999_999),
948/// };
949/// // Observe the different data types
950/// let expected = json!({
951///     "d_i64": -12345,
952///     "d_f64": -12345.0,
953///     "d_string": "12346",
954/// });
955/// assert_eq!(expected, serde_json::to_value(d).unwrap());
956///
957/// // Deserialization works too
958/// // Subsecond precision in numbers will be rounded away
959///
960/// let json = json!({
961///     "d_i64": -12345,
962///     "d_f64": -12345.5,
963///     "d_string": "12346",
964/// });
965/// let expected = Durations {
966///     d_i64: Duration::seconds(-12345),
967///     d_f64: Duration::seconds(-12346),
968///     d_string: Duration::seconds(12346),
969/// };
970/// assert_eq!(expected, serde_json::from_value(json).unwrap());
971/// # }
972/// ```
973///
974/// [`chrono::Duration`]: ::chrono_0_4::Duration
975/// [feature flag]: https://docs.rs/serde_with/3.20.0/serde_with/guide/feature_flags/index.html
976pub struct DurationSeconds<
977    FORMAT: formats::Format = u64,
978    STRICTNESS: formats::Strictness = formats::Strict,
979>(PhantomData<(FORMAT, STRICTNESS)>);
980
981/// De/Serialize Durations as number of seconds.
982///
983/// De/serialize durations as number of seconds with subsecond precision.
984/// Subsecond precision is *only* supported for [`DurationSecondsWithFrac`], but not for [`DurationSeconds`].
985/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
986/// Serialization of integers will round the duration to the nearest value.
987///
988/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
989/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `u64` deserialization from a `f64` will error.
990/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct duration and allows deserialization from any type.
991/// For example, deserializing `DurationSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
992///
993/// This type also supports [`chrono::Duration`] with the `chrono`-[feature flag].
994/// This type also supports [`time::Duration`][::time_0_3::Duration] with the `time_0_3`-[feature flag].
995///
996/// This table lists the available `FORMAT`s for the different duration types.
997/// The `FORMAT` specifier defaults to `u64`/`f64`.
998///
999/// | Duration Type         | Converter                 | Available `FORMAT`s      |
1000/// | --------------------- | ------------------------- | ------------------------ |
1001/// | `std::time::Duration` | `DurationSeconds`         | *`u64`*, `f64`, `String` |
1002/// | `std::time::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1003/// | `chrono::Duration`    | `DurationSeconds`         | `i64`, `f64`, `String`   |
1004/// | `chrono::Duration`    | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1005/// | `time::Duration`      | `DurationSeconds`         | `i64`, `f64`, `String`   |
1006/// | `time::Duration`      | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1007///
1008/// # Examples
1009///
1010/// ```rust
1011/// # #[cfg(feature = "macros")] {
1012/// # use serde::{Deserialize, Serialize};
1013/// # use serde_json::json;
1014/// # use serde_with::{serde_as, DurationSecondsWithFrac};
1015/// use std::time::Duration;
1016///
1017/// #[serde_as]
1018/// # #[derive(Debug, PartialEq)]
1019/// #[derive(Deserialize, Serialize)]
1020/// struct Durations {
1021///     #[serde_as(as = "DurationSecondsWithFrac<f64>")]
1022///     d_f64: Duration,
1023///     #[serde_as(as = "DurationSecondsWithFrac<String>")]
1024///     d_string: Duration,
1025/// }
1026///
1027/// // Serialization
1028/// // See how the values get rounded, since subsecond precision is not allowed.
1029///
1030/// let d = Durations {
1031///     d_f64: Duration::new(12345, 500_000_000), // Create from seconds and nanoseconds
1032///     d_string: Duration::new(12345, 999_999_000),
1033/// };
1034/// // Observe the different data types
1035/// let expected = json!({
1036///     "d_f64": 12345.5,
1037///     "d_string": "12345.999999",
1038/// });
1039/// assert_eq!(expected, serde_json::to_value(d).unwrap());
1040///
1041/// // Deserialization works too
1042/// // Subsecond precision in numbers will be rounded away
1043///
1044/// let json = json!({
1045///     "d_f64": 12345.5,
1046///     "d_string": "12345.987654",
1047/// });
1048/// let expected = Durations {
1049///     d_f64: Duration::new(12345, 500_000_000), // Create from seconds and nanoseconds
1050///     d_string: Duration::new(12345, 987_654_000),
1051/// };
1052/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1053/// # }
1054/// ```
1055///
1056/// [`chrono::Duration`] is also supported when using the `chrono_0_4` feature.
1057/// It is a signed duration, thus can be de/serialized as an `i64` instead of a `u64`.
1058///
1059/// ```rust
1060/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1061/// # use serde::{Deserialize, Serialize};
1062/// # use serde_json::json;
1063/// # use serde_with::{serde_as, DurationSecondsWithFrac};
1064/// # use chrono_0_4::Duration;
1065/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1066/// use chrono::Duration;
1067/// # */
1068///
1069/// #[serde_as]
1070/// # #[derive(Debug, PartialEq)]
1071/// #[derive(Deserialize, Serialize)]
1072/// struct Durations {
1073///     #[serde_as(as = "DurationSecondsWithFrac<f64>")]
1074///     d_f64: Duration,
1075///     #[serde_as(as = "DurationSecondsWithFrac<String>")]
1076///     d_string: Duration,
1077/// }
1078///
1079/// // Serialization
1080///
1081/// let d = Durations {
1082///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
1083///     d_string: Duration::seconds(12345) + Duration::nanoseconds(999_999_000),
1084/// };
1085/// // Observe the different data types
1086/// let expected = json!({
1087///     "d_f64": -12344.5,
1088///     "d_string": "12345.999999",
1089/// });
1090/// assert_eq!(expected, serde_json::to_value(d).unwrap());
1091///
1092/// // Deserialization works too
1093///
1094/// let json = json!({
1095///     "d_f64": -12344.5,
1096///     "d_string": "12345.987",
1097/// });
1098/// let expected = Durations {
1099///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
1100///     d_string: Duration::seconds(12345) + Duration::milliseconds(987),
1101/// };
1102/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1103/// # }
1104/// ```
1105///
1106/// [`chrono::Duration`]: ::chrono_0_4::Duration
1107/// [feature flag]: https://docs.rs/serde_with/3.20.0/serde_with/guide/feature_flags/index.html
1108pub struct DurationSecondsWithFrac<
1109    FORMAT: formats::Format = f64,
1110    STRICTNESS: formats::Strictness = formats::Strict,
1111>(PhantomData<(FORMAT, STRICTNESS)>);
1112
1113/// Equivalent to [`DurationSeconds`] with milli-seconds as base unit.
1114///
1115/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 milli-second instead of 1 second for [`DurationSeconds`].
1116pub struct DurationMilliSeconds<
1117    FORMAT: formats::Format = u64,
1118    STRICTNESS: formats::Strictness = formats::Strict,
1119>(PhantomData<(FORMAT, STRICTNESS)>);
1120
1121/// Equivalent to [`DurationSecondsWithFrac`] with milli-seconds as base unit.
1122///
1123/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 milli-second instead of 1 second for [`DurationSecondsWithFrac`].
1124pub struct DurationMilliSecondsWithFrac<
1125    FORMAT: formats::Format = f64,
1126    STRICTNESS: formats::Strictness = formats::Strict,
1127>(PhantomData<(FORMAT, STRICTNESS)>);
1128
1129/// Equivalent to [`DurationSeconds`] with micro-seconds as base unit.
1130///
1131/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 micro-second instead of 1 second for [`DurationSeconds`].
1132pub struct DurationMicroSeconds<
1133    FORMAT: formats::Format = u64,
1134    STRICTNESS: formats::Strictness = formats::Strict,
1135>(PhantomData<(FORMAT, STRICTNESS)>);
1136
1137/// Equivalent to [`DurationSecondsWithFrac`] with micro-seconds as base unit.
1138///
1139/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 micro-second instead of 1 second for [`DurationSecondsWithFrac`].
1140pub struct DurationMicroSecondsWithFrac<
1141    FORMAT: formats::Format = f64,
1142    STRICTNESS: formats::Strictness = formats::Strict,
1143>(PhantomData<(FORMAT, STRICTNESS)>);
1144
1145/// Equivalent to [`DurationSeconds`] with nano-seconds as base unit.
1146///
1147/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 nano-second instead of 1 second for [`DurationSeconds`].
1148pub struct DurationNanoSeconds<
1149    FORMAT: formats::Format = u64,
1150    STRICTNESS: formats::Strictness = formats::Strict,
1151>(PhantomData<(FORMAT, STRICTNESS)>);
1152
1153/// Equivalent to [`DurationSecondsWithFrac`] with nano-seconds as base unit.
1154///
1155/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 nano-second instead of 1 second for [`DurationSecondsWithFrac`].
1156pub struct DurationNanoSecondsWithFrac<
1157    FORMAT: formats::Format = f64,
1158    STRICTNESS: formats::Strictness = formats::Strict,
1159>(PhantomData<(FORMAT, STRICTNESS)>);
1160
1161/// De/Serialize timestamps as seconds since the UNIX epoch
1162///
1163/// De/serialize timestamps as seconds since the UNIX epoch.
1164/// Subsecond precision is *only* supported for [`TimestampSecondsWithFrac`], but not for [`TimestampSeconds`].
1165/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
1166/// Serialization of integers will round the timestamp to the nearest value.
1167///
1168/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
1169/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `i64` deserialization from a `f64` will error.
1170/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct timestamp and allows deserialization from any type.
1171/// For example, deserializing `TimestampSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
1172///
1173/// This type also supports [`chrono::DateTime`] with the `chrono_0_4`-[feature flag].
1174/// This type also supports [`time::OffsetDateTime`][::time_0_3::OffsetDateTime] and [`time::PrimitiveDateTime`][::time_0_3::PrimitiveDateTime] with the `time_0_3`-[feature flag].
1175///
1176/// This table lists the available `FORMAT`s for the different timestamp types.
1177/// The `FORMAT` specifier defaults to `i64` or `f64`.
1178///
1179/// | Timestamp Type            | Converter                  | Available `FORMAT`s      |
1180/// | ------------------------- | -------------------------- | ------------------------ |
1181/// | `std::time::SystemTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1182/// | `std::time::SystemTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1183/// | `chrono::DateTime<Utc>`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1184/// | `chrono::DateTime<Utc>`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1185/// | `chrono::DateTime<Local>` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1186/// | `chrono::DateTime<Local>` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1187/// | `chrono::NaiveDateTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1188/// | `chrono::NaiveDateTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1189/// | `time::OffsetDateTime`    | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1190/// | `time::OffsetDateTime`    | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1191/// | `time::PrimitiveDateTime` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1192/// | `time::PrimitiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1193///
1194/// # Examples
1195///
1196/// ```rust
1197/// # #[cfg(feature = "macros")] {
1198/// # use serde::{Deserialize, Serialize};
1199/// # use serde_json::json;
1200/// # use serde_with::{serde_as, TimestampSeconds};
1201/// use std::time::{Duration, SystemTime};
1202///
1203/// #[serde_as]
1204/// # #[derive(Debug, PartialEq)]
1205/// #[derive(Deserialize, Serialize)]
1206/// struct Timestamps {
1207///     #[serde_as(as = "TimestampSeconds<i64>")]
1208///     st_i64: SystemTime,
1209///     #[serde_as(as = "TimestampSeconds<f64>")]
1210///     st_f64: SystemTime,
1211///     #[serde_as(as = "TimestampSeconds<String>")]
1212///     st_string: SystemTime,
1213/// }
1214///
1215/// // Serialization
1216/// // See how the values get rounded, since subsecond precision is not allowed.
1217///
1218/// let ts = Timestamps {
1219///     st_i64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 0)).unwrap(),
1220///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1221///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 999_999_999)).unwrap(),
1222/// };
1223/// // Observe the different data types
1224/// let expected = json!({
1225///     "st_i64": 12345,
1226///     "st_f64": 12346.0,
1227///     "st_string": "12346",
1228/// });
1229/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1230///
1231/// // Deserialization works too
1232/// // Subsecond precision in numbers will be rounded away
1233///
1234/// let json = json!({
1235///     "st_i64": 12345,
1236///     "st_f64": 12345.5,
1237///     "st_string": "12346",
1238/// });
1239/// let expected  = Timestamps {
1240///     st_i64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 0)).unwrap(),
1241///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12346, 0)).unwrap(),
1242///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12346, 0)).unwrap(),
1243/// };
1244/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1245/// # }
1246/// ```
1247///
1248/// [`chrono::DateTime<Utc>`] and [`chrono::DateTime<Local>`] are also supported when using the `chrono` feature.
1249/// Like [`SystemTime`], it is a signed timestamp, thus can be de/serialized as an `i64`.
1250///
1251/// ```rust
1252/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1253/// # use serde::{Deserialize, Serialize};
1254/// # use serde_json::json;
1255/// # use serde_with::{serde_as, TimestampSeconds};
1256/// # use chrono_0_4::{DateTime, Local, TimeZone, Utc};
1257/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1258/// use chrono::{DateTime, Local, TimeZone, Utc};
1259/// # */
1260///
1261/// #[serde_as]
1262/// # #[derive(Debug, PartialEq)]
1263/// #[derive(Deserialize, Serialize)]
1264/// struct Timestamps {
1265///     #[serde_as(as = "TimestampSeconds<i64>")]
1266///     dt_i64: DateTime<Utc>,
1267///     #[serde_as(as = "TimestampSeconds<f64>")]
1268///     dt_f64: DateTime<Local>,
1269///     #[serde_as(as = "TimestampSeconds<String>")]
1270///     dt_string: DateTime<Utc>,
1271/// }
1272///
1273/// // Serialization
1274/// // See how the values get rounded, since subsecond precision is not allowed.
1275///
1276/// let ts = Timestamps {
1277///     dt_i64: Utc.timestamp_opt(-12345, 0).unwrap(),
1278///     dt_f64: Local.timestamp_opt(-12345, 500_000_000).unwrap(),
1279///     dt_string: Utc.timestamp_opt(12345, 999_999_999).unwrap(),
1280/// };
1281/// // Observe the different data types
1282/// let expected = json!({
1283///     "dt_i64": -12345,
1284///     "dt_f64": -12345.0,
1285///     "dt_string": "12346",
1286/// });
1287/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1288///
1289/// // Deserialization works too
1290/// // Subsecond precision in numbers will be rounded away
1291///
1292/// let json = json!({
1293///     "dt_i64": -12345,
1294///     "dt_f64": -12345.5,
1295///     "dt_string": "12346",
1296/// });
1297/// let expected = Timestamps {
1298///     dt_i64: Utc.timestamp_opt(-12345, 0).unwrap(),
1299///     dt_f64: Local.timestamp_opt(-12346, 0).unwrap(),
1300///     dt_string: Utc.timestamp_opt(12346, 0).unwrap(),
1301/// };
1302/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1303/// # }
1304/// ```
1305///
1306/// [`SystemTime`]: std::time::SystemTime
1307/// [`chrono::DateTime<Local>`]: ::chrono_0_4::DateTime
1308/// [`chrono::DateTime<Utc>`]: ::chrono_0_4::DateTime
1309/// [feature flag]: https://docs.rs/serde_with/3.20.0/serde_with/guide/feature_flags/index.html
1310pub struct TimestampSeconds<
1311    FORMAT: formats::Format = i64,
1312    STRICTNESS: formats::Strictness = formats::Strict,
1313>(PhantomData<(FORMAT, STRICTNESS)>);
1314
1315/// De/Serialize timestamps as seconds since the UNIX epoch
1316///
1317/// De/serialize timestamps as seconds since the UNIX epoch.
1318/// Subsecond precision is *only* supported for [`TimestampSecondsWithFrac`], but not for [`TimestampSeconds`].
1319/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
1320/// Serialization of integers will round the timestamp to the nearest value.
1321///
1322/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
1323/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `i64` deserialization from a `f64` will error.
1324/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct timestamp and allows deserialization from any type.
1325/// For example, deserializing `TimestampSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
1326///
1327/// This type also supports [`chrono::DateTime`] and [`chrono::NaiveDateTime`][NaiveDateTime] with the `chrono`-[feature flag].
1328/// This type also supports [`time::OffsetDateTime`][::time_0_3::OffsetDateTime] and [`time::PrimitiveDateTime`][::time_0_3::PrimitiveDateTime] with the `time_0_3`-[feature flag].
1329///
1330/// This table lists the available `FORMAT`s for the different timestamp types.
1331/// The `FORMAT` specifier defaults to `i64` or `f64`.
1332///
1333/// | Timestamp Type            | Converter                  | Available `FORMAT`s      |
1334/// | ------------------------- | -------------------------- | ------------------------ |
1335/// | `std::time::SystemTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1336/// | `std::time::SystemTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1337/// | `chrono::DateTime<Utc>`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1338/// | `chrono::DateTime<Utc>`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1339/// | `chrono::DateTime<Local>` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1340/// | `chrono::DateTime<Local>` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1341/// | `chrono::NaiveDateTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1342/// | `chrono::NaiveDateTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1343/// | `time::OffsetDateTime`    | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1344/// | `time::OffsetDateTime`    | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1345/// | `time::PrimitiveDateTime` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1346/// | `time::PrimitiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1347///
1348/// # Examples
1349///
1350/// ```rust
1351/// # #[cfg(feature = "macros")] {
1352/// # use serde::{Deserialize, Serialize};
1353/// # use serde_json::json;
1354/// # use serde_with::{serde_as, TimestampSecondsWithFrac};
1355/// use std::time::{Duration, SystemTime};
1356///
1357/// #[serde_as]
1358/// # #[derive(Debug, PartialEq)]
1359/// #[derive(Deserialize, Serialize)]
1360/// struct Timestamps {
1361///     #[serde_as(as = "TimestampSecondsWithFrac<f64>")]
1362///     st_f64: SystemTime,
1363///     #[serde_as(as = "TimestampSecondsWithFrac<String>")]
1364///     st_string: SystemTime,
1365/// }
1366///
1367/// // Serialization
1368/// // See how the values get rounded, since subsecond precision is not allowed.
1369///
1370/// let ts = Timestamps {
1371///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1372///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 999_999_000)).unwrap(),
1373/// };
1374/// // Observe the different data types
1375/// let expected = json!({
1376///     "st_f64": 12345.5,
1377///     "st_string": "12345.999999",
1378/// });
1379/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1380///
1381/// // Deserialization works too
1382/// // Subsecond precision in numbers will be rounded away
1383///
1384/// let json = json!({
1385///     "st_f64": 12345.5,
1386///     "st_string": "12345.987654",
1387/// });
1388/// let expected = Timestamps {
1389///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1390///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 987_654_000)).unwrap(),
1391/// };
1392/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1393/// # }
1394/// ```
1395///
1396/// [`chrono::DateTime<Utc>`] and [`chrono::DateTime<Local>`] are also supported when using the `chrono_0_4` feature.
1397/// Like [`SystemTime`], it is a signed timestamp, thus can be de/serialized as an `i64`.
1398///
1399/// ```rust
1400/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1401/// # use serde::{Deserialize, Serialize};
1402/// # use serde_json::json;
1403/// # use serde_with::{serde_as, TimestampSecondsWithFrac};
1404/// # use chrono_0_4::{DateTime, Local, TimeZone, Utc};
1405/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1406/// use chrono::{DateTime, Local, TimeZone, Utc};
1407/// # */
1408///
1409/// #[serde_as]
1410/// # #[derive(Debug, PartialEq)]
1411/// #[derive(Deserialize, Serialize)]
1412/// struct Timestamps {
1413///     #[serde_as(as = "TimestampSecondsWithFrac<f64>")]
1414///     dt_f64: DateTime<Utc>,
1415///     #[serde_as(as = "TimestampSecondsWithFrac<String>")]
1416///     dt_string: DateTime<Local>,
1417/// }
1418///
1419/// // Serialization
1420///
1421/// let ts = Timestamps {
1422///     dt_f64: Utc.timestamp_opt(-12345, 500_000_000).unwrap(),
1423///     dt_string: Local.timestamp_opt(12345, 999_999_000).unwrap(),
1424/// };
1425/// // Observe the different data types
1426/// let expected = json!({
1427///     "dt_f64": -12344.5,
1428///     "dt_string": "12345.999999",
1429/// });
1430/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1431///
1432/// // Deserialization works too
1433///
1434/// let json = json!({
1435///     "dt_f64": -12344.5,
1436///     "dt_string": "12345.987",
1437/// });
1438/// let expected = Timestamps {
1439///     dt_f64: Utc.timestamp_opt(-12345, 500_000_000).unwrap(),
1440///     dt_string: Local.timestamp_opt(12345, 987_000_000).unwrap(),
1441/// };
1442/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1443/// # }
1444/// ```
1445///
1446/// [`SystemTime`]: std::time::SystemTime
1447/// [`chrono::DateTime`]: ::chrono_0_4::DateTime
1448/// [`chrono::DateTime<Local>`]: ::chrono_0_4::DateTime
1449/// [`chrono::DateTime<Utc>`]: ::chrono_0_4::DateTime
1450/// [NaiveDateTime]: ::chrono_0_4::NaiveDateTime
1451/// [feature flag]: https://docs.rs/serde_with/3.20.0/serde_with/guide/feature_flags/index.html
1452pub struct TimestampSecondsWithFrac<
1453    FORMAT: formats::Format = f64,
1454    STRICTNESS: formats::Strictness = formats::Strict,
1455>(PhantomData<(FORMAT, STRICTNESS)>);
1456
1457/// Equivalent to [`TimestampSeconds`] with milli-seconds as base unit.
1458///
1459/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 milli-second instead of 1 second for [`TimestampSeconds`].
1460pub struct TimestampMilliSeconds<
1461    FORMAT: formats::Format = i64,
1462    STRICTNESS: formats::Strictness = formats::Strict,
1463>(PhantomData<(FORMAT, STRICTNESS)>);
1464
1465/// Equivalent to [`TimestampSecondsWithFrac`] with milli-seconds as base unit.
1466///
1467/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 milli-second instead of 1 second for [`TimestampSecondsWithFrac`].
1468pub struct TimestampMilliSecondsWithFrac<
1469    FORMAT: formats::Format = f64,
1470    STRICTNESS: formats::Strictness = formats::Strict,
1471>(PhantomData<(FORMAT, STRICTNESS)>);
1472
1473/// Equivalent to [`TimestampSeconds`] with micro-seconds as base unit.
1474///
1475/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 micro-second instead of 1 second for [`TimestampSeconds`].
1476pub struct TimestampMicroSeconds<
1477    FORMAT: formats::Format = i64,
1478    STRICTNESS: formats::Strictness = formats::Strict,
1479>(PhantomData<(FORMAT, STRICTNESS)>);
1480
1481/// Equivalent to [`TimestampSecondsWithFrac`] with micro-seconds as base unit.
1482///
1483/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 micro-second instead of 1 second for [`TimestampSecondsWithFrac`].
1484pub struct TimestampMicroSecondsWithFrac<
1485    FORMAT: formats::Format = f64,
1486    STRICTNESS: formats::Strictness = formats::Strict,
1487>(PhantomData<(FORMAT, STRICTNESS)>);
1488
1489/// Equivalent to [`TimestampSeconds`] with nano-seconds as base unit.
1490///
1491/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 nano-second instead of 1 second for [`TimestampSeconds`].
1492pub struct TimestampNanoSeconds<
1493    FORMAT: formats::Format = i64,
1494    STRICTNESS: formats::Strictness = formats::Strict,
1495>(PhantomData<(FORMAT, STRICTNESS)>);
1496
1497/// Equivalent to [`TimestampSecondsWithFrac`] with nano-seconds as base unit.
1498///
1499/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 nano-second instead of 1 second for [`TimestampSecondsWithFrac`].
1500pub struct TimestampNanoSecondsWithFrac<
1501    FORMAT: formats::Format = f64,
1502    STRICTNESS: formats::Strictness = formats::Strict,
1503>(PhantomData<(FORMAT, STRICTNESS)>);
1504
1505/// Optimized handling of owned and borrowed byte representations.
1506///
1507/// Serialization of byte sequences like `&[u8]` or `Vec<u8>` is quite inefficient since each value will be serialized individually.
1508/// This converter type optimizes the serialization and deserialization.
1509///
1510/// 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`].
1511///
1512/// The type provides de/serialization for these types:
1513///
1514/// * `[u8; N]`, not possible using `serde_bytes`
1515/// * `&[u8; N]`, not possible using `serde_bytes`
1516/// * `&[u8]`
1517/// * `Box<[u8; N]>`, not possible using `serde_bytes`
1518/// * `Box<[u8]>`
1519/// * `Vec<u8>`
1520/// * `Cow<'_, [u8]>`
1521/// * `Cow<'_, [u8; N]>`, not possible using `serde_bytes`
1522///
1523/// [`serde_bytes`]: https://crates.io/crates/serde_bytes
1524///
1525/// # Examples
1526///
1527/// ```
1528/// # #[cfg(feature = "macros")] {
1529/// # use serde::{Deserialize, Serialize};
1530/// # use serde_with::{serde_as, Bytes};
1531/// # use std::borrow::Cow;
1532/// #
1533/// #[serde_as]
1534/// # #[derive(Debug, PartialEq)]
1535/// #[derive(Deserialize, Serialize)]
1536/// struct Test<'a> {
1537///     #[serde_as(as = "Bytes")]
1538///     array: [u8; 15],
1539///     #[serde_as(as = "Bytes")]
1540///     boxed: Box<[u8]>,
1541///     #[serde_as(as = "Bytes")]
1542///     #[serde(borrow)]
1543///     cow: Cow<'a, [u8]>,
1544///     #[serde_as(as = "Bytes")]
1545///     #[serde(borrow)]
1546///     cow_array: Cow<'a, [u8; 15]>,
1547///     #[serde_as(as = "Bytes")]
1548///     vec: Vec<u8>,
1549/// }
1550///
1551/// let value = Test {
1552///     array: *b"0123456789ABCDE",
1553///     boxed: b"...".to_vec().into_boxed_slice(),
1554///     cow: Cow::Borrowed(b"FooBar"),
1555///     cow_array: Cow::Borrowed(&[42u8; 15]),
1556///     vec: vec![0x41, 0x61, 0x21],
1557/// };
1558/// let expected = r#"(
1559///     array: b"0123456789ABCDE",
1560///     boxed: b"...",
1561///     cow: b"FooBar",
1562///     cow_array: b"***************",
1563///     vec: b"Aa!",
1564/// )"#;
1565///
1566/// # let pretty_config = ron::ser::PrettyConfig::new().new_line("\n");
1567/// assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
1568/// assert_eq!(value, ron::from_str(expected).unwrap());
1569/// # }
1570/// ```
1571///
1572/// Fully borrowed types can also be used but you'll need a Deserializer that
1573/// supports Serde's 0-copy deserialization:
1574///
1575/// ```
1576/// # #[cfg(feature = "macros")] {
1577/// # use serde::{Deserialize, Serialize};
1578/// # use serde_with::{serde_as, Bytes};
1579/// #
1580/// #[serde_as]
1581/// # #[derive(Debug, PartialEq)]
1582/// #[derive(Deserialize, Serialize)]
1583/// struct TestBorrows<'a> {
1584///     #[serde_as(as = "Bytes")]
1585///     #[serde(borrow)]
1586///     array_buf: &'a [u8; 15],
1587///     #[serde_as(as = "Bytes")]
1588///     #[serde(borrow)]
1589///     buf: &'a [u8],
1590/// }
1591///
1592/// let value = TestBorrows {
1593///     array_buf: &[10u8; 15],
1594///     buf: &[20u8, 21u8, 22u8],
1595/// };
1596/// let expected = r#"(
1597///     array_buf: b"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1598///     buf: b"\x14\x15\x16",
1599/// )"#;
1600///
1601/// # let pretty_config = ron::ser::PrettyConfig::new().new_line("\n");
1602/// assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
1603/// // RON doesn't support borrowed deserialization of byte arrays
1604/// # }
1605/// ```
1606///
1607/// ## Alternative to [`BytesOrString`]
1608///
1609/// The [`Bytes`] can replace [`BytesOrString`].
1610/// [`Bytes`] is implemented for more types, which makes it better.
1611/// The serialization behavior of [`Bytes`] differs from [`BytesOrString`], therefore only `deserialize_as` should be used.
1612///
1613/// ```rust
1614/// # #[cfg(feature = "macros")] {
1615/// # use serde::Deserialize;
1616/// # use serde_json::json;
1617/// # use serde_with::{serde_as, Bytes};
1618/// #
1619/// #[serde_as]
1620/// # #[derive(Debug, PartialEq)]
1621/// #[derive(Deserialize, serde::Serialize)]
1622/// struct Test {
1623///     #[serde_as(deserialize_as = "Bytes")]
1624///     from_bytes: Vec<u8>,
1625///     #[serde_as(deserialize_as = "Bytes")]
1626///     from_str: Vec<u8>,
1627/// }
1628///
1629/// // Different serialized values ...
1630/// let j = json!({
1631///     "from_bytes": [70,111,111,45,66,97,114],
1632///     "from_str": "Foo-Bar",
1633/// });
1634///
1635/// // can be deserialized ...
1636/// let test = Test {
1637///     from_bytes: b"Foo-Bar".to_vec(),
1638///     from_str: b"Foo-Bar".to_vec(),
1639/// };
1640/// assert_eq!(test, serde_json::from_value(j).unwrap());
1641///
1642/// // and serialization will always be a byte sequence
1643/// # assert_eq!(json!(
1644/// {
1645///     "from_bytes": [70,111,111,45,66,97,114],
1646///     "from_str": [70,111,111,45,66,97,114],
1647/// }
1648/// # ), serde_json::to_value(&test).unwrap());
1649/// # }
1650/// ```
1651pub struct Bytes;
1652
1653/// Deserialize one or many elements
1654///
1655/// Sometimes it is desirable to have a shortcut in writing 1-element lists in a config file.
1656/// Usually, this is done by either writing a list or the list element itself.
1657/// This distinction is not semantically important on the Rust side, thus both forms should deserialize into the same `Vec`.
1658///
1659/// The `OneOrMany` adapter achieves exactly this use case.
1660/// 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`].
1661/// By default, [`PreferOne`] is assumed, which can also be omitted like `OneOrMany<_>`.
1662///
1663/// [`PreferMany`]: crate::formats::PreferMany
1664/// [`PreferOne`]: crate::formats::PreferOne
1665///
1666/// # Examples
1667///
1668/// ```rust
1669/// # #[cfg(feature = "macros")] {
1670/// # use serde::Deserialize;
1671/// # use serde_json::json;
1672/// # use serde_with::{serde_as, OneOrMany};
1673/// # use serde_with::formats::{PreferOne, PreferMany};
1674/// #
1675/// #[serde_as]
1676/// # #[derive(Debug, PartialEq)]
1677/// #[derive(Deserialize, serde::Serialize)]
1678/// struct Data {
1679///     #[serde_as(as = "OneOrMany<_, PreferOne>")]
1680///     countries: Vec<String>,
1681///     #[serde_as(as = "OneOrMany<_, PreferMany>")]
1682///     cities: Vec<String>,
1683/// }
1684///
1685/// // The adapter allows deserializing a `Vec` from either
1686/// // a single element
1687/// let j = json!({
1688///     "countries": "Spain",
1689///     "cities": "Berlin",
1690/// });
1691/// assert!(serde_json::from_value::<Data>(j).is_ok());
1692///
1693/// // or from a list.
1694/// let j = json!({
1695///     "countries": ["Germany", "France"],
1696///     "cities": ["Amsterdam"],
1697/// });
1698/// assert!(serde_json::from_value::<Data>(j).is_ok());
1699///
1700/// // For serialization you can choose how a single element should be encoded.
1701/// // Either directly, with `PreferOne` (default), or as a list with `PreferMany`.
1702/// let data = Data {
1703///     countries: vec!["Spain".to_string()],
1704///     cities: vec!["Berlin".to_string()],
1705/// };
1706/// let j = json!({
1707///     "countries": "Spain",
1708///     "cities": ["Berlin"],
1709/// });
1710/// assert_eq!(serde_json::to_value(data).unwrap(), j);
1711/// # }
1712/// ```
1713pub struct OneOrMany<T: ?Sized, FORMAT: formats::Format = formats::PreferOne>(
1714    PhantomData<(FORMAT, T)>,
1715);
1716
1717/// Try multiple deserialization options until one succeeds.
1718///
1719/// This adapter allows you to specify a list of deserialization options.
1720/// They are tried in order and the first one working is applied.
1721/// Serialization always picks the first option.
1722///
1723/// `PickFirst` has one type parameter which must be instantiated with a tuple of two, three, or four elements.
1724/// For example, `PickFirst<(_, DisplayFromStr)>` on a field of type `u32` allows deserializing from a number or from a string via the `FromStr` trait.
1725/// The value will be serialized as a number, since that is what the first type `_` indicates.
1726///
1727/// # Examples
1728///
1729/// Deserialize a number from either a number or a string.
1730///
1731/// ```rust
1732/// # #[cfg(feature = "macros")] {
1733/// # use serde::{Deserialize, Serialize};
1734/// # use serde_json::json;
1735/// # use serde_with::{serde_as, DisplayFromStr, PickFirst};
1736/// #
1737/// #[serde_as]
1738/// # #[derive(Debug, PartialEq)]
1739/// #[derive(Deserialize, Serialize)]
1740/// struct Data {
1741///     #[serde_as(as = "PickFirst<(_, DisplayFromStr)>")]
1742///     as_number: u32,
1743///     #[serde_as(as = "PickFirst<(DisplayFromStr, _)>")]
1744///     as_string: u32,
1745/// }
1746/// let data = Data {
1747///     as_number: 123,
1748///     as_string: 456
1749/// };
1750///
1751/// // Both fields can be deserialized from numbers:
1752/// let j = json!({
1753///     "as_number": 123,
1754///     "as_string": 456,
1755/// });
1756/// assert_eq!(data, serde_json::from_value(j).unwrap());
1757///
1758/// // or from a string:
1759/// let j = json!({
1760///     "as_number": "123",
1761///     "as_string": "456",
1762/// });
1763/// assert_eq!(data, serde_json::from_value(j).unwrap());
1764///
1765/// // For serialization the first type in the tuple determines the behavior.
1766/// // The `as_number` field will use the normal `Serialize` behavior and produce a number,
1767/// // while `as_string` used `Display` to produce a string.
1768/// let expected = json!({
1769///     "as_number": 123,
1770///     "as_string": "456",
1771/// });
1772/// assert_eq!(expected, serde_json::to_value(&data).unwrap());
1773/// # }
1774/// ```
1775#[cfg(feature = "alloc")]
1776pub struct PickFirst<T>(PhantomData<T>);
1777
1778/// Serialize value by converting to/from a proxy type with serde support.
1779///
1780/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
1781/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
1782///
1783/// ```rust
1784/// # #[cfg(any())] {
1785/// struct S {
1786///     #[serde_as(as = "FromInto<T>")]
1787///     value: O,
1788/// }
1789/// # }
1790/// ```
1791///
1792/// For serialization `O` needs to be `O: Into<T> + Clone`.
1793/// For deserialization the opposite `T: Into<O>` is required.
1794/// The `Clone` bound is required since `serialize` operates on a reference but `Into` implementations on references are uncommon.
1795///
1796/// **Note**: [`TryFromInto`] is the more generalized version of this adapter which uses the [`TryInto`] trait instead.
1797///
1798/// # Example
1799///
1800/// ```rust
1801/// # #[cfg(feature = "macros")] {
1802/// # use serde::{Deserialize, Serialize};
1803/// # use serde_json::json;
1804/// # use serde_with::{serde_as, FromInto};
1805/// #
1806/// #[derive(Clone, Debug, PartialEq)]
1807/// struct Rgb {
1808///     red: u8,
1809///     green: u8,
1810///     blue: u8,
1811/// }
1812///
1813/// # /*
1814/// impl From<(u8, u8, u8)> for Rgb { ... }
1815/// impl From<Rgb> for (u8, u8, u8) { ... }
1816/// # */
1817/// #
1818/// # impl From<(u8, u8, u8)> for Rgb {
1819/// #     fn from(v: (u8, u8, u8)) -> Self {
1820/// #         Rgb {
1821/// #             red: v.0,
1822/// #             green: v.1,
1823/// #             blue: v.2,
1824/// #         }
1825/// #     }
1826/// # }
1827/// #
1828/// # impl From<Rgb> for (u8, u8, u8) {
1829/// #     fn from(v: Rgb) -> Self {
1830/// #         (v.red, v.green, v.blue)
1831/// #     }
1832/// # }
1833///
1834/// #[serde_as]
1835/// # #[derive(Debug, PartialEq)]
1836/// #[derive(Deserialize, Serialize)]
1837/// struct Color {
1838///     #[serde_as(as = "FromInto<(u8, u8, u8)>")]
1839///     rgb: Rgb,
1840/// }
1841/// let color = Color {
1842///     rgb: Rgb {
1843///         red: 128,
1844///         green: 64,
1845///         blue: 32,
1846///     },
1847/// };
1848///
1849/// // Define our expected JSON form
1850/// let j = json!({
1851///     "rgb": [128, 64, 32],
1852/// });
1853/// // Ensure serialization and deserialization produce the expected results
1854/// assert_eq!(j, serde_json::to_value(&color).unwrap());
1855/// assert_eq!(color, serde_json::from_value(j).unwrap());
1856/// # }
1857/// ```
1858pub struct FromInto<T>(PhantomData<T>);
1859
1860/// Serialize a reference value by converting to/from a proxy type with serde support.
1861///
1862/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
1863/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
1864///
1865/// ```rust
1866/// # #[cfg(any())] {
1867/// struct S {
1868///     #[serde_as(as = "FromIntoRef<T>")]
1869///     value: O,
1870/// }
1871/// # }
1872/// ```
1873///
1874/// For serialization `O` needs to be `for<'a> &'a O: Into<T>`.
1875/// For deserialization the opposite `T: Into<O>` is required.
1876///
1877/// **Note**: [`TryFromIntoRef`] is the more generalized version of this adapter which uses the [`TryInto`] trait instead.
1878///
1879/// # Example
1880///
1881/// ```rust
1882/// # #[cfg(feature = "macros")] {
1883/// # use serde::{Deserialize, Serialize};
1884/// # use serde_json::json;
1885/// # use serde_with::{serde_as, FromIntoRef};
1886/// #
1887/// #[derive(Debug, PartialEq)]
1888/// struct Rgb {
1889///     red: u8,
1890///     green: u8,
1891///     blue: u8,
1892/// }
1893///
1894/// # /*
1895/// impl From<(u8, u8, u8)> for Rgb { ... }
1896/// impl<'a> From<&'a Rgb> for (u8, u8, u8) { ... }
1897/// # */
1898/// #
1899/// # impl From<(u8, u8, u8)> for Rgb {
1900/// #     fn from(v: (u8, u8, u8)) -> Self {
1901/// #         Rgb {
1902/// #             red: v.0,
1903/// #             green: v.1,
1904/// #             blue: v.2,
1905/// #         }
1906/// #     }
1907/// # }
1908/// #
1909/// # impl<'a> From<&'a Rgb> for (u8, u8, u8) {
1910/// #     fn from(v: &'a Rgb) -> Self {
1911/// #         (v.red, v.green, v.blue)
1912/// #     }
1913/// # }
1914///
1915/// #[serde_as]
1916/// # #[derive(Debug, PartialEq)]
1917/// #[derive(Deserialize, Serialize)]
1918/// struct Color {
1919///     #[serde_as(as = "FromIntoRef<(u8, u8, u8)>")]
1920///     rgb: Rgb,
1921/// }
1922/// let color = Color {
1923///     rgb: Rgb {
1924///         red: 128,
1925///         green: 64,
1926///         blue: 32,
1927///     },
1928/// };
1929///
1930/// // Define our expected JSON form
1931/// let j = json!({
1932///     "rgb": [128, 64, 32],
1933/// });
1934/// // Ensure serialization and deserialization produce the expected results
1935/// assert_eq!(j, serde_json::to_value(&color).unwrap());
1936/// assert_eq!(color, serde_json::from_value(j).unwrap());
1937/// # }
1938/// ```
1939pub struct FromIntoRef<T>(PhantomData<T>);
1940
1941/// Serialize value by converting to/from a proxy type with serde support.
1942///
1943/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
1944/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
1945///
1946/// ```rust
1947/// # #[cfg(any())] {
1948/// struct S {
1949///     #[serde_as(as = "TryFromInto<T>")]
1950///     value: O,
1951/// }
1952/// # }
1953/// ```
1954///
1955/// For serialization `O` needs to be `O: TryInto<T> + Clone`.
1956/// For deserialization the opposite `T: TryInto<O>` is required.
1957/// The `Clone` bound is required since `serialize` operates on a reference but `TryInto` implementations on references are uncommon.
1958/// In both cases the `TryInto::Error` type must implement [`Display`](std::fmt::Display).
1959///
1960/// **Note**: [`FromInto`] is the more specialized version of this adapter which uses the infallible [`Into`] trait instead.
1961/// [`TryFromInto`] is strictly more general and can also be used where [`FromInto`] is applicable.
1962/// The example shows a use case, when only the deserialization behavior is fallible, but not serializing.
1963///
1964/// # Example
1965///
1966/// ```rust
1967/// # #[cfg(feature = "macros")] {
1968/// # use serde::{Deserialize, Serialize};
1969/// # use serde_json::json;
1970/// # use serde_with::{serde_as, TryFromInto};
1971/// #
1972/// #[derive(Clone, Debug, PartialEq)]
1973/// enum Boollike {
1974///     True,
1975///     False,
1976/// }
1977///
1978/// # /*
1979/// impl From<Boollike> for u8 { ... }
1980/// # */
1981/// #
1982/// impl TryFrom<u8> for Boollike {
1983///     type Error = String;
1984///     fn try_from(v: u8) -> Result<Self, Self::Error> {
1985///         match v {
1986///             0 => Ok(Boollike::False),
1987///             1 => Ok(Boollike::True),
1988///             _ => Err(format!("Boolikes can only be constructed from 0 or 1 but found {}", v))
1989///         }
1990///     }
1991/// }
1992/// #
1993/// # impl From<Boollike> for u8 {
1994/// #     fn from(v: Boollike) -> Self {
1995/// #        match v {
1996/// #            Boollike::True => 1,
1997/// #            Boollike::False => 0,
1998/// #        }
1999/// #     }
2000/// # }
2001///
2002/// #[serde_as]
2003/// # #[derive(Debug, PartialEq)]
2004/// #[derive(Deserialize, Serialize)]
2005/// struct Data {
2006///     #[serde_as(as = "TryFromInto<u8>")]
2007///     b: Boollike,
2008/// }
2009/// let data = Data {
2010///     b: Boollike::True,
2011/// };
2012///
2013/// // Define our expected JSON form
2014/// let j = json!({
2015///     "b": 1,
2016/// });
2017/// // Ensure serialization and deserialization produce the expected results
2018/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2019/// assert_eq!(data, serde_json::from_value(j).unwrap());
2020///
2021/// // Numbers besides 0 or 1 should be an error
2022/// let j = json!({
2023///     "b": 2,
2024/// });
2025/// assert_eq!("Boolikes can only be constructed from 0 or 1 but found 2", serde_json::from_value::<Data>(j).unwrap_err().to_string());
2026/// # }
2027/// ```
2028pub struct TryFromInto<T>(PhantomData<T>);
2029
2030/// Serialize a reference value by converting to/from a proxy type with serde support.
2031///
2032/// This adapter serializes a type `O` by converting it into a second type `T` and serializing `T`.
2033/// Deserializing works analogue, by deserializing a `T` and then converting into `O`.
2034///
2035/// ```rust
2036/// # #[cfg(any())] {
2037/// struct S {
2038///     #[serde_as(as = "TryFromIntoRef<T>")]
2039///     value: O,
2040/// }
2041/// # }
2042/// ```
2043///
2044/// For serialization `O` needs to be `for<'a> &'a O: TryInto<T>`.
2045/// For deserialization the opposite `T: TryInto<O>` is required.
2046/// In both cases the `TryInto::Error` type must implement [`Display`](std::fmt::Display).
2047///
2048/// **Note**: [`FromIntoRef`] is the more specialized version of this adapter which uses the infallible [`Into`] trait instead.
2049/// [`TryFromIntoRef`] is strictly more general and can also be used where [`FromIntoRef`] is applicable.
2050/// The example shows a use case, when only the deserialization behavior is fallible, but not serializing.
2051///
2052/// # Example
2053///
2054/// ```rust
2055/// # #[cfg(feature = "macros")] {
2056/// # use serde::{Deserialize, Serialize};
2057/// # use serde_json::json;
2058/// # use serde_with::{serde_as, TryFromIntoRef};
2059/// #
2060/// #[derive(Debug, PartialEq)]
2061/// enum Boollike {
2062///     True,
2063///     False,
2064/// }
2065///
2066/// # /*
2067/// impl<'a> From<&'a Boollike> for u8 { ... }
2068/// # */
2069/// #
2070/// impl TryFrom<u8> for Boollike {
2071///     type Error = String;
2072///     fn try_from(v: u8) -> Result<Self, Self::Error> {
2073///         match v {
2074///             0 => Ok(Boollike::False),
2075///             1 => Ok(Boollike::True),
2076///             _ => Err(format!("Boolikes can only be constructed from 0 or 1 but found {}", v))
2077///         }
2078///     }
2079/// }
2080/// #
2081/// # impl<'a> From<&'a Boollike> for u8 {
2082/// #     fn from(v: &'a Boollike) -> Self {
2083/// #        match v {
2084/// #            Boollike::True => 1,
2085/// #            Boollike::False => 0,
2086/// #        }
2087/// #     }
2088/// # }
2089///
2090/// #[serde_as]
2091/// # #[derive(Debug, PartialEq)]
2092/// #[derive(Deserialize, Serialize)]
2093/// struct Data {
2094///     #[serde_as(as = "TryFromIntoRef<u8>")]
2095///     b: Boollike,
2096/// }
2097/// let data = Data {
2098///     b: Boollike::True,
2099/// };
2100///
2101/// // Define our expected JSON form
2102/// let j = json!({
2103///     "b": 1,
2104/// });
2105/// // Ensure serialization and deserialization produce the expected results
2106/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2107/// assert_eq!(data, serde_json::from_value(j).unwrap());
2108///
2109/// // Numbers besides 0 or 1 should be an error
2110/// let j = json!({
2111///     "b": 2,
2112/// });
2113/// assert_eq!("Boolikes can only be constructed from 0 or 1 but found 2", serde_json::from_value::<Data>(j).unwrap_err().to_string());
2114/// # }
2115/// ```
2116pub struct TryFromIntoRef<T>(PhantomData<T>);
2117
2118/// Borrow `Cow` data during deserialization when possible.
2119///
2120/// The types `Cow<'a, [u8]>`, `Cow<'a, [u8; N]>`, and `Cow<'a, str>` can borrow from the input data during deserialization.
2121/// serde supports this, by annotating the fields with `#[serde(borrow)]`. but does not support borrowing on nested types.
2122/// This gap is filled by this `BorrowCow` adapter.
2123///
2124/// Using this adapter with `Cow<'a, [u8]>`/`Cow<'a, [u8; N]>` will serialize the value as a sequence of `u8` values.
2125/// This *might* not allow to borrow the data during deserialization.
2126/// For a different format, which is also more efficient, use the [`Bytes`] adapter, which is also implemented for `Cow`.
2127///
2128/// When combined with the [`serde_as`] attribute, the `#[serde(borrow)]` annotation will be added automatically.
2129/// If the annotation is wrong or too broad, for example because of multiple lifetime parameters, a manual annotation is required.
2130///
2131/// # Examples
2132///
2133/// ```rust
2134/// # #[cfg(feature = "macros")] {
2135/// # use serde::{Deserialize, Serialize};
2136/// # use serde_with::{serde_as, BorrowCow};
2137/// # use std::borrow::Cow;
2138/// #
2139/// #[serde_as]
2140/// # #[derive(Debug, PartialEq)]
2141/// #[derive(Deserialize, Serialize)]
2142/// struct Data<'a, 'b, 'c> {
2143///     #[serde_as(as = "BorrowCow")]
2144///     str: Cow<'a, str>,
2145///     #[serde_as(as = "BorrowCow")]
2146///     slice: Cow<'b, [u8]>,
2147///
2148///     #[serde_as(as = "Option<[BorrowCow; 1]>")]
2149///     nested: Option<[Cow<'c, str>; 1]>,
2150/// }
2151/// let data = Data {
2152///     str: "foobar".into(),
2153///     slice: b"foobar"[..].into(),
2154///     nested: Some(["HelloWorld".into()]),
2155/// };
2156///
2157/// // Define our expected JSON form
2158/// let j = r#"{
2159///   "str": "foobar",
2160///   "slice": [
2161///     102,
2162///     111,
2163///     111,
2164///     98,
2165///     97,
2166///     114
2167///   ],
2168///   "nested": [
2169///     "HelloWorld"
2170///   ]
2171/// }"#;
2172/// // Ensure serialization and deserialization produce the expected results
2173/// assert_eq!(j, serde_json::to_string_pretty(&data).unwrap());
2174/// assert_eq!(data, serde_json::from_str(j).unwrap());
2175///
2176/// // Cow borrows from the input data
2177/// let deserialized: Data<'_, '_, '_> = serde_json::from_str(j).unwrap();
2178/// assert!(matches!(deserialized.str, Cow::Borrowed(_)));
2179/// assert!(matches!(deserialized.nested, Some([Cow::Borrowed(_)])));
2180/// // JSON does not allow borrowing bytes, so `slice` does not borrow
2181/// assert!(matches!(deserialized.slice, Cow::Owned(_)));
2182/// # }
2183/// ```
2184#[cfg(feature = "alloc")]
2185pub struct BorrowCow;
2186
2187/// A trait to inspect skipped deserialization errors
2188///
2189/// The [`VecSkipError`] and [`MapSkipError`] adapters allow to skip values which fail to deserialize.
2190/// This trait allows inspecting these errors, for example for logging purposes.
2191///
2192/// The trait has a single method [`inspect_error`][InspectError::inspect_error], which will be called for each deserialization error.
2193/// The default implementation for `()` does nothing.
2194///
2195/// See the documentation of [`VecSkipError`] and [`MapSkipError`] for usage examples.
2196#[cfg(feature = "alloc")]
2197pub trait InspectError {
2198    /// Inspect a deserialization error which was skipped.
2199    fn inspect_error(error: impl serde_core::de::Error);
2200}
2201
2202#[cfg(feature = "alloc")]
2203impl InspectError for () {
2204    fn inspect_error(_error: impl serde_core::de::Error) {}
2205}
2206
2207/// Deserialize a sequence into `Vec<T>`, skipping elements which fail to deserialize.
2208///
2209/// The serialization behavior is identical to `Vec<T>`. This is an alternative to `Vec<T>`
2210/// which is resilient against unexpected data.
2211///
2212/// You can be notified of skipped elements by providing a type that implements the [`InspectError`] trait.
2213/// The second generic argument `I` defaults to `()`, which does nothing.
2214///
2215/// # Examples
2216///
2217/// ## Basic Usage
2218///
2219/// ```rust
2220/// # #[cfg(feature = "macros")] {
2221/// # use serde::{Deserialize, Serialize};
2222/// # use serde_with::{serde_as, VecSkipError};
2223/// #
2224/// # #[derive(Debug, PartialEq)]
2225/// #[derive(Deserialize, Serialize)]
2226/// # #[non_exhaustive]
2227/// enum Color {
2228///     Red,
2229///     Green,
2230///     Blue,
2231/// }
2232/// # use Color::*;
2233/// #[serde_as]
2234/// # #[derive(Debug, PartialEq)]
2235/// #[derive(Deserialize, Serialize)]
2236/// struct Palette(#[serde_as(as = "VecSkipError<_>")] Vec<Color>);
2237///
2238/// let data = Palette(vec![Blue, Green,]);
2239/// let source_json = r#"["Blue", "Yellow", "Green"]"#;
2240/// let data_json = r#"["Blue","Green"]"#;
2241/// // Ensure serialization and deserialization produce the expected results
2242/// assert_eq!(data_json, serde_json::to_string(&data).unwrap());
2243/// assert_eq!(data, serde_json::from_str(source_json).unwrap());
2244/// # }
2245/// ```
2246///
2247/// ## Using [`InspectError`](`crate::InspectError`) to log skipped elements
2248///
2249/// ```rust
2250/// # #[cfg(all(feature = "macros", feature = "alloc"))] {
2251/// # use serde::{Serialize, Deserialize};
2252/// # use serde_with::{serde_as, InspectError, VecSkipError};
2253/// # use std::cell::RefCell;
2254///
2255/// struct ErrorInspector;
2256///
2257/// thread_local! {
2258///     static ERRORS: RefCell<Vec<String>> = RefCell::new(Vec::new());
2259/// }
2260///
2261/// impl InspectError for ErrorInspector {
2262///     fn inspect_error(error: impl serde::de::Error) {
2263///         ERRORS.with(|errors| errors.borrow_mut().push(error.to_string()));
2264///     }
2265/// }
2266///
2267/// #[serde_as]
2268/// #[derive(Debug, PartialEq, Deserialize, Serialize)]
2269/// struct S {
2270///     tag: String,
2271///     #[serde_as(as = "VecSkipError<_, ErrorInspector>")]
2272///     values: Vec<u8>,
2273/// }
2274///
2275/// let json = r#"{"tag":"type","values":[0, "str", 1, [10, 11], -2, {}, 300]}"#;
2276/// let s: S = serde_json::from_str(json).unwrap();
2277/// assert_eq!(s.values, vec![0, 1]);
2278///
2279/// let errors = ERRORS.with(|errors| errors.borrow().clone());
2280/// eprintln!("Errors: {errors:#?}");
2281/// assert_eq!(errors.len(), 5);
2282/// assert!(errors[0].contains("invalid type: string \"str\", expected u8"));
2283/// assert!(errors[1].contains("invalid type: sequence, expected u8"));
2284/// assert!(errors[2].contains("invalid value: integer `-2`, expected u8"));
2285/// assert!(errors[3].contains("invalid type: map, expected u8"));
2286/// assert!(errors[4].contains("invalid value: integer `300`, expected u8"));
2287/// # }
2288/// ```
2289#[cfg(feature = "alloc")]
2290pub struct VecSkipError<T, I = ()>(PhantomData<(T, I)>);
2291
2292/// Deserialize a map, skipping keys and values which fail to deserialize.
2293///
2294/// By default serde terminates if it fails to deserialize a key or a value when deserializing
2295/// a map. Sometimes a map has heterogeneous keys or values but we only care about some specific
2296/// types, and it is desirable to skip entries on errors.
2297///
2298/// You can be notified of skipped elements by providing a type that implements the [`InspectError`] trait.
2299/// The third generic argument `I` defaults to `()`, which does nothing.
2300///
2301/// It is especially useful in conjunction to `#[serde(flatten)]` to capture a map mixed in with
2302/// other entries which we don't want to exhaust in the type definition.
2303///
2304/// The serialization behavior is identical to the underlying map.
2305///
2306/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2307///
2308/// [`BTreeMap`]: std::collections::BTreeMap
2309/// [`HashMap`]: std::collections::HashMap
2310///
2311/// # Examples
2312///
2313/// ## Basic Usage
2314///
2315/// ```rust
2316/// # #[cfg(feature = "macros")] {
2317/// # use serde::{Deserialize, Serialize};
2318/// # use std::collections::BTreeMap;
2319/// # use serde_with::{serde_as, DisplayFromStr, MapSkipError};
2320/// #
2321/// #[serde_as]
2322/// # #[derive(Debug, PartialEq)]
2323/// #[derive(Deserialize, Serialize)]
2324/// struct VersionNames {
2325///     yanked: Vec<u16>,
2326///     #[serde_as(as = "MapSkipError<DisplayFromStr, _>")]
2327///     #[serde(flatten)]
2328///     names: BTreeMap<u16, String>,
2329/// }
2330///
2331/// let data = VersionNames {
2332///     yanked: vec![2, 5],
2333///     names: BTreeMap::from_iter([
2334///         (0u16, "v0".to_string()),
2335///         (1, "v1".to_string()),
2336///         (4, "v4".to_string())
2337///     ]),
2338/// };
2339/// let source_json = r#"{
2340///   "0": "v0",
2341///   "1": "v1",
2342///   "4": "v4",
2343///   "yanked": [2, 5],
2344///   "last_updated": 1704085200
2345/// }"#;
2346/// let data_json = r#"{"yanked":[2,5],"0":"v0","1":"v1","4":"v4"}"#;
2347/// // Ensure serialization and deserialization produce the expected results
2348/// assert_eq!(data_json, serde_json::to_string(&data).unwrap());
2349/// assert_eq!(data, serde_json::from_str(source_json).unwrap());
2350/// # }
2351/// ```
2352///
2353/// ## Using [`InspectError`](`crate::InspectError`) to log skipped elements
2354///
2355/// ```rust
2356/// # #[cfg(all(feature = "macros", feature = "alloc"))] {
2357/// # use serde::{Serialize, Deserialize};
2358/// # use serde_with::{serde_as, InspectError, MapSkipError};
2359/// # use std::collections::BTreeMap;
2360/// # use std::cell::RefCell;
2361///
2362/// struct ErrorInspector;
2363///
2364/// thread_local! {
2365///     static ERRORS: RefCell<Vec<String>> = RefCell::new(Vec::new());
2366/// }
2367///
2368/// impl InspectError for ErrorInspector {
2369///     fn inspect_error(error: impl serde::de::Error) {
2370///         ERRORS.with(|errors| errors.borrow_mut().push(error.to_string()));
2371///     }
2372/// }
2373///
2374/// #[serde_as]
2375/// #[derive(Debug, PartialEq, Deserialize, Serialize)]
2376/// struct S {
2377///     tag: String,
2378///     #[serde_as(as = "MapSkipError<_, _, ErrorInspector>")]
2379///     values: BTreeMap<String, u8>,
2380/// }
2381///
2382/// let json = r#"{"tag":"type","values":{"valid":42,"invalid": null,"another":"str","nested":[1,2,3]}}"#;
2383/// let s: S = serde_json::from_str(json).unwrap();
2384/// assert_eq!(s.values.len(), 1);
2385/// assert_eq!(s.values.get("valid"), Some(&42));
2386///
2387/// let errors = ERRORS.with(|errors| errors.borrow().clone());
2388/// assert_eq!(errors.len(), 3);
2389/// eprintln!("Errors: {errors:#?}");
2390/// assert!(errors[0].contains("invalid type: null, expected u8"));
2391/// assert!(errors[1].contains("invalid type: string \"str\", expected u8"));
2392/// assert!(errors[2].contains("invalid type: sequence, expected u8"));
2393/// # }
2394/// ```
2395#[cfg(feature = "alloc")]
2396pub struct MapSkipError<K, V, I = ()>(PhantomData<(K, V, I)>);
2397
2398/// Deserialize a boolean from a number
2399///
2400/// Deserialize a number (of `u8`) and turn it into a boolean.
2401/// The adapter supports a [`Strict`](crate::formats::Strict) and [`Flexible`](crate::formats::Flexible) format.
2402/// In `Strict` mode, the number must be `0` or `1`.
2403/// All other values produce an error.
2404/// In `Flexible` mode, the number any non-zero value is converted to `true`.
2405///
2406/// During serialization only `0` or `1` are ever emitted.
2407///
2408/// # Examples
2409///
2410/// ```rust
2411/// # #[cfg(feature = "macros")] {
2412/// # use serde::{Deserialize, Serialize};
2413/// # use serde_json::json;
2414/// # use serde_with::{serde_as, BoolFromInt};
2415/// #
2416/// #[serde_as]
2417/// # #[derive(Debug, PartialEq)]
2418/// #[derive(Deserialize, Serialize)]
2419/// struct Data(#[serde_as(as = "BoolFromInt")] bool);
2420///
2421/// let data = Data(true);
2422/// let j = json!(1);
2423/// // Ensure serialization and deserialization produce the expected results
2424/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2425/// assert_eq!(data, serde_json::from_value(j).unwrap());
2426///
2427/// // false maps to 0
2428/// let data = Data(false);
2429/// let j = json!(0);
2430/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2431/// assert_eq!(data, serde_json::from_value(j).unwrap());
2432//
2433/// #[serde_as]
2434/// # #[derive(Debug, PartialEq)]
2435/// #[derive(Deserialize, Serialize)]
2436/// struct Flexible(#[serde_as(as = "BoolFromInt<serde_with::formats::Flexible>")] bool);
2437///
2438/// // Flexible turns any non-zero number into true
2439/// let data = Flexible(true);
2440/// let j = json!(100);
2441/// assert_eq!(data, serde_json::from_value(j).unwrap());
2442/// # }
2443/// ```
2444pub struct BoolFromInt<S: formats::Strictness = formats::Strict>(PhantomData<S>);
2445
2446/// De/Serialize a delimited collection using [`Display`] and [`FromStr`] implementation
2447///
2448/// `StringWithSeparator` takes a second type, which needs to implement [`Display`]+[`FromStr`] and constitutes the inner type of the collection.
2449/// You can define an arbitrary separator, by specifying a type which implements [`Separator`].
2450/// Some common ones, like space and comma are already predefined and you can find them [here][`Separator`].
2451///
2452/// An empty string deserializes as an empty collection.
2453///
2454/// # Examples
2455///
2456/// ```
2457/// # #[cfg(feature = "macros")] {
2458/// # use serde::{Deserialize, Serialize};
2459/// #
2460/// # use serde_with::{serde_as, StringWithSeparator};
2461/// use serde_with::formats::{CommaSeparator, SpaceSeparator};
2462/// use std::collections::BTreeSet;
2463///
2464/// #[serde_as]
2465/// #[derive(Deserialize, Serialize)]
2466/// struct A {
2467///     #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
2468///     tags: Vec<String>,
2469///     #[serde_as(as = "StringWithSeparator::<CommaSeparator, String>")]
2470///     more_tags: BTreeSet<String>,
2471/// }
2472///
2473/// let v: A = serde_json::from_str(r##"{
2474///     "tags": "#hello #world",
2475///     "more_tags": "foo,bar,bar"
2476/// }"##).unwrap();
2477/// assert_eq!(vec!["#hello", "#world"], v.tags);
2478/// assert_eq!(2, v.more_tags.len());
2479///
2480/// let x = A {
2481///     tags: vec!["1".to_string(), "2".to_string(), "3".to_string()],
2482///     more_tags: BTreeSet::new(),
2483/// };
2484/// assert_eq!(
2485///     r#"{"tags":"1 2 3","more_tags":""}"#,
2486///     serde_json::to_string(&x).unwrap()
2487/// );
2488/// # }
2489/// ```
2490///
2491/// [`Display`]: core::fmt::Display
2492/// [`FromStr`]: core::str::FromStr
2493/// [`Separator`]: crate::formats::Separator
2494/// [`serde_as`]: crate::guide::serde_as
2495pub struct StringWithSeparator<Sep, T>(PhantomData<(Sep, T)>);
2496
2497/// This serializes a list of tuples into a map
2498///
2499/// Normally, you want to use a [`HashMap`] or a [`BTreeMap`] when deserializing a map.
2500/// However, sometimes this is not possible due to type constraints, e.g., if the type implements neither [`Hash`] nor [`Ord`].
2501/// Another use case is deserializing a map with duplicate keys.
2502///
2503/// # Examples
2504///
2505/// `Wrapper` does not implement [`Hash`] nor [`Ord`], thus prohibiting the use [`HashMap`] or [`BTreeMap`].
2506/// The JSON also contains a duplicate key.
2507///
2508/// [`BTreeMap`]: std::collections::BTreeMap
2509/// [`HashMap`]: std::collections::HashMap
2510/// [`Vec`]: std::vec::Vec
2511///
2512/// ```rust
2513/// # #[cfg(feature = "macros")] {
2514/// # use serde::{Deserialize, Serialize};
2515/// # use serde_with::{serde_as, Map};
2516/// #
2517/// #[serde_as]
2518/// #[derive(Debug, Deserialize, Serialize, Default)]
2519/// struct S {
2520///     #[serde_as(as = "Map<_, _>")]
2521///     s: Vec<(Wrapper<i32>, String)>,
2522/// }
2523///
2524/// #[derive(Clone, Debug, Serialize, Deserialize)]
2525/// #[serde(transparent)]
2526/// struct Wrapper<T>(T);
2527///
2528/// let data = S {
2529///     s: vec![
2530///         (Wrapper(1), "a".to_string()),
2531///         (Wrapper(2), "b".to_string()),
2532///         (Wrapper(3), "c".to_string()),
2533///         (Wrapper(2), "d".to_string()),
2534///     ],
2535/// };
2536///
2537/// let json = r#"{
2538///   "s": {
2539///     "1": "a",
2540///     "2": "b",
2541///     "3": "c",
2542///     "2": "d"
2543///   }
2544/// }"#;
2545/// assert_eq!(json, serde_json::to_string_pretty(&data).unwrap());
2546/// # }
2547/// ```
2548pub struct Map<K, V>(PhantomData<(K, V)>);
2549
2550/// De/Serialize a Map into a list of tuples
2551///
2552/// Some formats, like JSON, have limitations on the types of keys for maps.
2553/// In case of JSON, keys are restricted to strings.
2554/// Rust features more powerful keys, for example tuples, which can not be serialized to JSON.
2555///
2556/// This helper serializes the Map into a list of tuples, which do not have the same type restrictions.
2557///
2558/// # Examples
2559///
2560/// ```rust
2561/// # #[cfg(feature = "macros")] {
2562/// # use serde::{Deserialize, Serialize};
2563/// # use serde_json::json;
2564/// # use serde_with::{serde_as, Seq};
2565/// # use std::collections::BTreeMap;
2566/// #
2567/// #[serde_as]
2568/// # #[derive(Debug, PartialEq)]
2569/// #[derive(Deserialize, Serialize)]
2570/// struct A {
2571///     #[serde_as(as = "Seq<(_, _)>")]
2572///     s: BTreeMap<(String, u32), u32>,
2573/// }
2574///
2575/// // This converts the Rust type
2576/// let data = A {
2577///     s: BTreeMap::from([
2578///         (("Hello".to_string(), 123), 0),
2579///         (("World".to_string(), 456), 1),
2580///     ]),
2581/// };
2582///
2583/// // into this JSON
2584/// let value = json!({
2585///     "s": [
2586///         [["Hello", 123], 0],
2587///         [["World", 456], 1]
2588///     ]
2589/// });
2590///
2591/// assert_eq!(value, serde_json::to_value(&data).unwrap());
2592/// assert_eq!(data, serde_json::from_value(value).unwrap());
2593/// # }
2594/// ```
2595pub struct Seq<V>(PhantomData<V>);
2596
2597/// Ensure no duplicate keys exist in a map.
2598///
2599/// By default serde has a last-value-wins implementation, if duplicate keys for a map exist.
2600/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
2601/// and it can indicate an error in the serialized data.
2602///
2603/// This helper returns an error if two identical keys exist in a map.
2604///
2605/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2606///
2607/// [`BTreeMap`]: std::collections::BTreeMap
2608/// [`HashMap`]: std::collections::HashMap
2609///
2610/// # Example
2611///
2612/// ```rust
2613/// # #[cfg(feature = "macros")] {
2614/// # use serde::Deserialize;
2615/// # use std::collections::HashMap;
2616/// # use serde_with::{serde_as, MapPreventDuplicates};
2617/// #
2618/// #[serde_as]
2619/// # #[derive(Debug, Eq, PartialEq)]
2620/// #[derive(Deserialize)]
2621/// struct Doc {
2622///     #[serde_as(as = "MapPreventDuplicates<_, _>")]
2623///     map: HashMap<usize, usize>,
2624/// }
2625///
2626/// // Maps are serialized normally,
2627/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
2628/// let mut v = Doc {
2629///     map: HashMap::new(),
2630/// };
2631/// v.map.insert(1, 1);
2632/// v.map.insert(2, 2);
2633/// v.map.insert(3, 3);
2634/// assert_eq!(v, serde_json::from_str(s).unwrap());
2635///
2636/// // but create an error if duplicate keys, like the `1`, exist.
2637/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
2638/// let res: Result<Doc, _> = serde_json::from_str(s);
2639/// assert!(res.is_err());
2640/// # }
2641/// ```
2642#[cfg(feature = "alloc")]
2643pub struct MapPreventDuplicates<K, V>(PhantomData<(K, V)>);
2644
2645/// Ensure that the first key is taken, if duplicate keys exist
2646///
2647/// By default serde has a last-key-wins implementation, if duplicate keys for a map exist.
2648/// Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.
2649///
2650/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2651///
2652/// [`BTreeMap`]: std::collections::BTreeMap
2653/// [`HashMap`]: std::collections::HashMap
2654#[cfg(feature = "alloc")]
2655pub struct MapFirstKeyWins<K, V>(PhantomData<(K, V)>);
2656
2657/// Ensure no duplicate values exist in a set.
2658///
2659/// By default serde has a last-value-wins implementation, if duplicate values for a set exist.
2660/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
2661/// and it can indicate an error in the serialized data.
2662///
2663/// This helper returns an error if two identical values exist in a set.
2664///
2665/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
2666///
2667/// [`BTreeSet`]: std::collections::BTreeSet
2668/// [`HashSet`]: std::collections::HashSet
2669///
2670/// # Example
2671///
2672/// ```rust
2673/// # #[cfg(feature = "macros")] {
2674/// # use std::collections::HashSet;
2675/// # use serde::Deserialize;
2676/// # use serde_with::{serde_as, SetPreventDuplicates};
2677/// #
2678/// #[serde_as]
2679/// # #[derive(Debug, Eq, PartialEq)]
2680/// #[derive(Deserialize)]
2681/// struct Doc {
2682///     #[serde_as(as = "SetPreventDuplicates<_>")]
2683///     set: HashSet<usize>,
2684/// }
2685///
2686/// // Sets are serialized normally,
2687/// let s = r#"{"set": [1, 2, 3, 4]}"#;
2688/// let v = Doc {
2689///     set: HashSet::from_iter(vec![1, 2, 3, 4]),
2690/// };
2691/// assert_eq!(v, serde_json::from_str(s).unwrap());
2692///
2693/// // but create an error if duplicate values, like the `1`, exist.
2694/// let s = r#"{"set": [1, 2, 3, 4, 1]}"#;
2695/// let res: Result<Doc, _> = serde_json::from_str(s);
2696/// assert!(res.is_err());
2697/// # }
2698/// ```
2699#[cfg(feature = "alloc")]
2700pub struct SetPreventDuplicates<T>(PhantomData<T>);
2701
2702/// Ensure that the last value is taken, if duplicate values exist
2703///
2704/// By default serde has a first-value-wins implementation, if duplicate keys for a set exist.
2705/// Sometimes the opposite strategy is desired. This helper implements a first-value-wins strategy.
2706///
2707/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
2708///
2709/// [`BTreeSet`]: std::collections::BTreeSet
2710/// [`HashSet`]: std::collections::HashSet
2711#[cfg(feature = "alloc")]
2712pub struct SetLastValueWins<T>(PhantomData<T>);
2713
2714/// Helper for implementing [`JsonSchema`] on serializers whose output depends
2715/// on the type of the concrete field.
2716///
2717/// It is added implicitly by the [`#[serde_as]`](crate::serde_as) macro when any `schemars`
2718/// feature is enabled.
2719///
2720/// [`JsonSchema`]: ::schemars_1::JsonSchema
2721#[cfg(any(
2722    feature = "schemars_0_8",
2723    feature = "schemars_0_9",
2724    feature = "schemars_1"
2725))]
2726pub struct Schema<T: ?Sized, TA>(PhantomData<T>, PhantomData<TA>);