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