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.13.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//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/py7ida)
33//!
34//! ---
35//!
36//! 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.
37//! Some common use cases are:
38//!
39//! * De/Serializing a type using the `Display` and `FromStr` traits, e.g., for `u8`, `url::Url`, or `mime::Mime`.
40//!   Check [`DisplayFromStr`] for details.
41//! * Support for arrays larger than 32 elements or using const generics.
42//!   With `serde_as` large arrays are supported, even if they are nested in other types.
43//!   `[bool; 64]`, `Option<[u8; M]>`, and `Box<[[u8; 64]; N]>` are all supported, as [this examples shows](#large-and-const-generic-arrays).
44//! * Skip serializing all empty `Option` types with [`#[skip_serializing_none]`][skip_serializing_none].
45//! * 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!`][].
46//! * Deserialize a comma separated list like `#hash,#tags,#are,#great` into a `Vec<String>`.
47//!   Check the documentation for [`serde_with::StringWithSeparator::<CommaSeparator, T>`][StringWithSeparator].
48//!
49//! ## Getting Help
50//!
51//! **Check out the [user guide][user guide] to find out more tips and tricks about this crate.**
52//!
53//! 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/).
54//! For bugs, please open a [new issue](https://github.com/jonasbb/serde_with/issues/new) on GitHub.
55//!
56//! # Use `serde_with` in your Project
57//!
58//! ```bash
59//! # Add the current version to your Cargo.toml
60//! cargo add serde_with
61//! ```
62//!
63//! The crate contains different features for integration with other common crates.
64//! Check the [feature flags][] section for information about all available features.
65//!
66//! # Examples
67//!
68//! Annotate your struct or enum to enable the custom de/serializer.
69//! The `#[serde_as]` attribute must be placed *before* the `#[derive]`.
70//!
71//! The `as` is analogous to the `with` attribute of serde.
72//! You mirror the type structure of the field you want to de/serialize.
73//! You can specify converters for the inner types of a field, e.g., `Vec<DisplayFromStr>`.
74//! The default de/serialization behavior can be restored by using `_` as a placeholder, e.g., `BTreeMap<_, DisplayFromStr>`.
75//!
76//! ## `DisplayFromStr`
77//!
78//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/py7ida)
79//! ```rust
80//! # #[cfg(all(feature = "macros", feature = "json"))] {
81//! # use serde::{Deserialize, Serialize};
82//! # use serde_with::{serde_as, DisplayFromStr};
83//! #[serde_as]
84//! # #[derive(Debug, Eq, PartialEq)]
85//! #[derive(Deserialize, Serialize)]
86//! struct Foo {
87//!     // Serialize with Display, deserialize with FromStr
88//!     #[serde_as(as = "DisplayFromStr")]
89//!     bar: u8,
90//! }
91//!
92//! // This will serialize
93//! # let foo =
94//! Foo {bar: 12}
95//! # ;
96//!
97//! // into this JSON
98//! # let json = r#"
99//! {"bar": "12"}
100//! # "#;
101//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
102//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
103//! # }
104//! ```
105//!
106//! ## Large and const-generic arrays
107//!
108//! serde does not support arrays with more than 32 elements or using const-generics.
109//! The `serde_as` attribute allows circumventing this restriction, even for nested types and nested arrays.
110//!
111//! On top of it, `[u8; N]` (aka, bytes) can use the specialized `"Bytes"` for efficiency much like the `serde_bytes` crate.
112//!
113//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/um0xyi)
114//! ```rust
115//! # #[cfg(all(feature = "macros", feature = "json"))] {
116//! # use serde::{Deserialize, Serialize};
117//! # use serde_with::{serde_as, Bytes};
118//! #[serde_as]
119//! # #[derive(Debug, Eq, PartialEq)]
120//! #[derive(Deserialize, Serialize)]
121//! struct Arrays<const N: usize, const M: usize> {
122//!     #[serde_as(as = "[_; N]")]
123//!     constgeneric: [bool; N],
124//!
125//!     #[serde_as(as = "Box<[[_; 64]; N]>")]
126//!     nested: Box<[[u8; 64]; N]>,
127//!
128//!     #[serde_as(as = "Option<[_; M]>")]
129//!     optional: Option<[u8; M]>,
130//!
131//!     #[serde_as(as = "Bytes")]
132//!     bytes: [u8; M],
133//! }
134//!
135//! // This allows us to serialize a struct like this
136//! let arrays: Arrays<100, 128> = Arrays {
137//!     constgeneric: [true; 100],
138//!     nested: Box::new([[111; 64]; 100]),
139//!     optional: Some([222; 128]),
140//!     bytes: [0x42; 128],
141//! };
142//! assert!(serde_json::to_string(&arrays).is_ok());
143//! # }
144//! ```
145//!
146//! ## `skip_serializing_none`
147//!
148//! This situation often occurs with JSON, but other formats also support optional fields.
149//! If many fields are optional, putting the annotations on the structs can become tedious.
150//! The `#[skip_serializing_none]` attribute must be placed *before* the `#[derive]`.
151//!
152//! [![Rustexplorer](https://img.shields.io/badge/Try%20on-rustexplorer-lightgrey?logo=rust&logoColor=orange)](https://www.rustexplorer.com/b/xr1tm0)
153//! ```rust
154//! # #[cfg(all(feature = "macros", feature = "json"))] {
155//! # use serde::{Deserialize, Serialize};
156//! # use serde_with::skip_serializing_none;
157//! #[skip_serializing_none]
158//! # #[derive(Debug, Eq, PartialEq)]
159//! #[derive(Deserialize, Serialize)]
160//! struct Foo {
161//!     a: Option<usize>,
162//!     b: Option<usize>,
163//!     c: Option<usize>,
164//!     d: Option<usize>,
165//!     e: Option<usize>,
166//!     f: Option<usize>,
167//!     g: Option<usize>,
168//! }
169//!
170//! // This will serialize
171//! # let foo =
172//! Foo {a: None, b: None, c: None, d: Some(4), e: None, f: None, g: Some(7)}
173//! # ;
174//!
175//! // into this JSON
176//! # let json = r#"
177//! {"d": 4, "g": 7}
178//! # "#;
179//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
180//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
181//! # }
182//! ```
183//!
184//! ## Advanced `serde_as` usage
185//!
186//! This example is mainly supposed to highlight the flexibility of the `serde_as` annotation compared to [serde's `with` annotation][with-annotation].
187//! More details about `serde_as` can be found in the [user guide].
188//!
189//! ```rust
190//! # #[cfg(all(feature = "macros", feature = "hex"))]
191//! # use {
192//! #     serde::{Deserialize, Serialize},
193//! #     serde_with::{serde_as, DisplayFromStr, DurationSeconds, hex::Hex, Map},
194//! # };
195//! # #[cfg(all(feature = "macros", feature = "hex"))]
196//! use std::time::Duration;
197//!
198//! # #[cfg(all(feature = "macros", feature = "hex"))]
199//! #[serde_as]
200//! # #[derive(Debug, Eq, PartialEq)]
201//! #[derive(Deserialize, Serialize)]
202//! enum Foo {
203//!     Durations(
204//!         // Serialize them into a list of number as seconds
205//!         #[serde_as(as = "Vec<DurationSeconds>")]
206//!         Vec<Duration>,
207//!     ),
208//!     Bytes {
209//!         // We can treat a Vec like a map with duplicates.
210//!         // JSON only allows string keys, so convert i32 to strings
211//!         // The bytes will be hex encoded
212//!         #[serde_as(as = "Map<DisplayFromStr, Hex>")]
213//!         bytes: Vec<(i32, Vec<u8>)>,
214//!     }
215//! }
216//!
217//! # #[cfg(all(feature = "macros", feature = "json", feature = "hex"))] {
218//! // This will serialize
219//! # let foo =
220//! Foo::Durations(
221//!     vec![Duration::new(5, 0), Duration::new(3600, 0), Duration::new(0, 0)]
222//! )
223//! # ;
224//! // into this JSON
225//! # let json = r#"
226//! {
227//!     "Durations": [5, 3600, 0]
228//! }
229//! # "#;
230//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
231//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
232//!
233//! // and serializes
234//! # let foo =
235//! Foo::Bytes {
236//!     bytes: vec![
237//!         (1, vec![0, 1, 2]),
238//!         (-100, vec![100, 200, 255]),
239//!         (1, vec![0, 111, 222]),
240//!     ],
241//! }
242//! # ;
243//! // into this JSON
244//! # let json = r#"
245//! {
246//!     "Bytes": {
247//!         "bytes": {
248//!             "1": "000102",
249//!             "-100": "64c8ff",
250//!             "1": "006fde"
251//!         }
252//!     }
253//! }
254//! # "#;
255//! # assert_eq!(json.replace(" ", "").replace("\n", ""), serde_json::to_string(&foo).unwrap());
256//! # assert_eq!(foo, serde_json::from_str(json).unwrap());
257//! # }
258//! ```
259//!
260//! [`DisplayFromStr`]: https://docs.rs/serde_with/3.13.0/serde_with/struct.DisplayFromStr.html
261//! [`with_prefix!`]: https://docs.rs/serde_with/3.13.0/serde_with/macro.with_prefix.html
262//! [`with_suffix!`]: https://docs.rs/serde_with/3.13.0/serde_with/macro.with_suffix.html
263//! [feature flags]: https://docs.rs/serde_with/3.13.0/serde_with/guide/feature_flags/index.html
264//! [skip_serializing_none]: https://docs.rs/serde_with/3.13.0/serde_with/attr.skip_serializing_none.html
265//! [StringWithSeparator]: https://docs.rs/serde_with/3.13.0/serde_with/struct.StringWithSeparator.html
266//! [user guide]: https://docs.rs/serde_with/3.13.0/serde_with/guide/index.html
267//! [with-annotation]: https://serde.rs/field-attrs.html#with
268//! [as-annotation]: https://docs.rs/serde_with/3.13.0/serde_with/guide/serde_as/index.html
269
270#[cfg(feature = "alloc")]
271extern crate alloc;
272#[doc(hidden)]
273pub extern crate core;
274#[doc(hidden)]
275pub extern crate serde;
276#[doc(hidden)]
277pub extern crate serde_derive;
278#[cfg(feature = "std")]
279extern crate std;
280
281#[cfg(feature = "base64")]
282#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
283pub mod base64;
284#[cfg(feature = "chrono_0_4")]
285#[cfg_attr(docsrs, doc(cfg(feature = "chrono_0_4")))]
286pub mod chrono_0_4;
287/// Legacy export of the [`chrono_0_4`] module.
288#[cfg(feature = "chrono")]
289#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
290pub mod chrono {
291    pub use crate::chrono_0_4::*;
292    pub use chrono_0_4::*;
293}
294#[cfg(feature = "alloc")]
295mod content;
296pub mod de;
297#[cfg(feature = "alloc")]
298mod duplicate_key_impls;
299#[cfg(feature = "alloc")]
300mod enum_map;
301#[cfg(feature = "std")]
302mod flatten_maybe;
303pub mod formats;
304#[cfg(feature = "hex")]
305#[cfg_attr(docsrs, doc(cfg(feature = "hex")))]
306pub mod hex;
307#[cfg(feature = "json")]
308#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
309pub mod json;
310#[cfg(feature = "alloc")]
311mod key_value_map;
312pub mod rust;
313#[cfg(feature = "schemars_0_8")]
314#[cfg_attr(docsrs, doc(cfg(feature = "schemars_0_8")))]
315pub mod schemars_0_8;
316#[cfg(feature = "schemars_0_9")]
317#[cfg_attr(docsrs, doc(cfg(feature = "schemars_0_9")))]
318pub mod schemars_0_9;
319pub mod ser;
320mod serde_conv;
321#[cfg(feature = "time_0_3")]
322#[cfg_attr(docsrs, doc(cfg(feature = "time_0_3")))]
323pub mod time_0_3;
324mod utils;
325#[cfg(feature = "std")]
326#[doc(hidden)]
327pub mod with_prefix;
328#[cfg(feature = "std")]
329#[doc(hidden)]
330pub mod with_suffix;
331
332// Taken from shepmaster/snafu
333// Originally licensed as MIT+Apache 2
334// https://github.com/shepmaster/snafu/blob/90991b609e8928ceebf7df1b040408539d21adda/src/lib.rs#L343-L376
335#[cfg(feature = "guide")]
336#[allow(unused_macro_rules)]
337macro_rules! generate_guide {
338    (pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
339        generate_guide!(@gen ".", pub mod $name { $($children)* } $($rest)*);
340    };
341    (@gen $prefix:expr, ) => {};
342    (@gen $prefix:expr, pub mod $name:ident; $($rest:tt)*) => {
343        generate_guide!(@gen $prefix, pub mod $name { } $($rest)*);
344    };
345    (@gen $prefix:expr, @code pub mod $name:ident; $($rest:tt)*) => {
346        #[cfg(feature = "guide")]
347        pub mod $name;
348
349        #[cfg(not(feature = "guide"))]
350        /// Not currently built; please add the `guide` feature flag.
351        pub mod $name {}
352
353        generate_guide!(@gen $prefix, $($rest)*);
354    };
355    (@gen $prefix:expr, pub mod $name:ident { $($children:tt)* } $($rest:tt)*) => {
356        #[cfg(feature = "guide")]
357        #[doc = include_str!(concat!($prefix, "/", stringify!($name), ".md"))]
358        pub mod $name {
359            generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
360        }
361        #[cfg(not(feature = "guide"))]
362        /// Not currently built; please add the `guide` feature flag.
363        pub mod $name {
364            generate_guide!(@gen concat!($prefix, "/", stringify!($name)), $($children)*);
365        }
366
367        generate_guide!(@gen $prefix, $($rest)*);
368    };
369}
370
371#[cfg(feature = "guide")]
372generate_guide! {
373    pub mod guide {
374        @code pub mod feature_flags;
375        pub mod serde_as;
376        pub mod serde_as_transformations;
377    }
378}
379
380pub(crate) mod prelude {
381    #![allow(unused_imports)]
382
383    pub(crate) use crate::utils::duration::{DurationSigned, Sign};
384    pub use crate::{de::*, ser::*, *};
385    #[cfg(all(feature = "alloc", target_has_atomic = "ptr"))]
386    pub use alloc::sync::{Arc, Weak as ArcWeak};
387    #[cfg(feature = "alloc")]
388    pub use alloc::{
389        borrow::{Cow, ToOwned},
390        boxed::Box,
391        collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque},
392        rc::{Rc, Weak as RcWeak},
393        string::{String, ToString},
394        vec::Vec,
395    };
396    pub use core::{
397        cell::{Cell, RefCell},
398        convert::{TryFrom, TryInto},
399        fmt::{self, Display},
400        hash::{BuildHasher, Hash},
401        marker::PhantomData,
402        ops::Bound,
403        option::Option,
404        pin::Pin,
405        result::Result,
406        str::FromStr,
407        time::Duration,
408    };
409    pub use serde::{
410        de::{
411            Deserialize, DeserializeOwned, DeserializeSeed, Deserializer, EnumAccess,
412            Error as DeError, Expected, IgnoredAny, IntoDeserializer, MapAccess, SeqAccess,
413            Unexpected, VariantAccess, Visitor,
414        },
415        forward_to_deserialize_any,
416        ser::{
417            Error as SerError, Impossible, Serialize, SerializeMap, SerializeSeq, SerializeStruct,
418            SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant,
419            Serializer,
420        },
421    };
422    #[cfg(feature = "std")]
423    pub use std::{
424        collections::{HashMap, HashSet},
425        sync::{Mutex, RwLock},
426        time::SystemTime,
427    };
428}
429
430/// This module is not part of the public API
431///
432/// Do not rely on any exports.
433#[doc(hidden)]
434pub mod __private__ {
435    pub use crate::prelude::*;
436}
437
438#[cfg(feature = "alloc")]
439#[doc(inline)]
440pub use crate::enum_map::EnumMap;
441#[cfg(feature = "alloc")]
442#[doc(inline)]
443pub use crate::key_value_map::KeyValueMap;
444#[doc(inline)]
445pub use crate::{de::DeserializeAs, ser::SerializeAs};
446use core::marker::PhantomData;
447// Re-Export all proc_macros, as these should be seen as part of the serde_with crate
448#[cfg(feature = "macros")]
449#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
450#[doc(inline)]
451pub use serde_with_macros::*;
452
453/// Adapter to convert from `serde_as` to the serde traits.
454///
455/// The `As` type adapter allows using types which implement [`DeserializeAs`] or [`SerializeAs`] in place of serde's `with` annotation.
456/// The `with` annotation allows running custom code when de/serializing, however it is quite inflexible.
457/// The traits [`DeserializeAs`]/[`SerializeAs`] are more flexible, as they allow composition and nesting of types to create more complex de/serialization behavior.
458/// However, they are not directly compatible with serde, as they are not provided by serde.
459/// The `As` type adapter makes them compatible, by forwarding the function calls to `serialize`/`deserialize` to the corresponding functions `serialize_as` and `deserialize_as`.
460///
461/// It is not required to use this type directly.
462/// Instead, it is highly encouraged to use the [`#[serde_as]`][serde_as] attribute since it includes further usability improvements.
463/// If the use of the use of the proc-macro is not acceptable, then `As` can be used directly with serde.
464///
465/// ```rust
466/// # #[cfg(feature = "alloc")] {
467/// # use serde::{Deserialize, Serialize};
468/// # use serde_with::{As, DisplayFromStr};
469/// #
470/// # #[allow(dead_code)]
471/// #[derive(Deserialize, Serialize)]
472/// # struct S {
473/// // Serialize numbers as sequence of strings, using Display and FromStr
474/// #[serde(with = "As::<Vec<DisplayFromStr>>")]
475/// field: Vec<u8>,
476/// # }
477/// # }
478/// ```
479/// If the normal `Deserialize`/`Serialize` traits should be used, the placeholder type [`Same`] can be used.
480/// It implements [`DeserializeAs`][]/[`SerializeAs`][], when the underlying type implements `Deserialize`/`Serialize`.
481///
482/// ```rust
483/// # #[cfg(feature = "alloc")] {
484/// # use serde::{Deserialize, Serialize};
485/// # use serde_with::{As, DisplayFromStr, Same};
486/// # use std::collections::BTreeMap;
487/// #
488/// # #[allow(dead_code)]
489/// #[derive(Deserialize, Serialize)]
490/// # struct S {
491/// // Serialize map, turn keys into strings but keep type of value
492/// #[serde(with = "As::<BTreeMap<DisplayFromStr, Same>>")]
493/// field: BTreeMap<u8, i32>,
494/// # }
495/// # }
496/// ```
497///
498/// [serde_as]: https://docs.rs/serde_with/3.13.0/serde_with/attr.serde_as.html
499pub struct As<T: ?Sized>(PhantomData<T>);
500
501/// Adapter to convert from `serde_as` to the serde traits.
502///
503/// This is the counter-type to [`As`][].
504/// It can be used whenever a type implementing [`DeserializeAs`]/[`SerializeAs`] is required but the normal [`Deserialize`](::serde::Deserialize)/[`Serialize`](::serde::Serialize) traits should be used.
505/// Check [`As`] for an example.
506pub struct Same;
507
508/// De/Serialize using [`Display`] and [`FromStr`] implementation
509///
510/// This allows deserializing a string as a number.
511/// It can be very useful for serialization formats like JSON, which do not support integer
512/// numbers and have to resort to strings to represent them.
513///
514/// Another use case is types with [`Display`] and [`FromStr`] implementations, but without serde
515/// support, which can be found in some crates.
516///
517/// If you control the type you want to de/serialize, you can instead use the two derive macros, [`SerializeDisplay`] and [`DeserializeFromStr`].
518/// They properly implement the traits [`serde::Serialize`] and [`serde::Deserialize`] such that user of the type no longer have to use the `serde_as` system.
519///
520/// # Examples
521///
522/// ```rust
523/// # #[cfg(feature = "macros")] {
524/// # use serde::{Deserialize, Serialize};
525/// # use serde_json::json;
526/// # use serde_with::{serde_as, DisplayFromStr};
527/// #
528/// #[serde_as]
529/// #[derive(Deserialize, Serialize)]
530/// struct A {
531///     #[serde_as(as = "DisplayFromStr")]
532///     mime: mime::Mime,
533///     #[serde_as(as = "DisplayFromStr")]
534///     number: u32,
535/// }
536///
537/// let v: A = serde_json::from_value(json!({
538///     "mime": "text/plain",
539///     "number": "159",
540/// })).unwrap();
541/// assert_eq!(mime::TEXT_PLAIN, v.mime);
542/// assert_eq!(159, v.number);
543///
544/// let x = A {
545///     mime: mime::STAR_STAR,
546///     number: 777,
547/// };
548/// assert_eq!(json!({ "mime": "*/*", "number": "777" }), serde_json::to_value(x).unwrap());
549/// # }
550/// ```
551///
552/// [`Display`]: std::fmt::Display
553/// [`FromStr`]: std::str::FromStr
554pub struct DisplayFromStr;
555
556/// Use the first format if [`De/Serializer::is_human_readable`], otherwise use the second
557///
558/// If the second format is not specified, the normal
559/// [`Deserialize`](::serde::Deserialize)/[`Serialize`](::serde::Serialize) traits are used.
560///
561/// # Examples
562///
563/// ```rust
564/// # #[cfg(feature = "macros")] {
565/// # use serde::{Deserialize, Serialize};
566/// # use serde_json::json;
567/// # use serde_with::{serde_as, DisplayFromStr, IfIsHumanReadable, DurationMilliSeconds, DurationSeconds};
568/// use std::time::Duration;
569///
570/// #[serde_as]
571/// #[derive(Deserialize, Serialize)]
572/// struct A {
573///     #[serde_as(as = "IfIsHumanReadable<DisplayFromStr>")]
574///     number: u32,
575/// }
576/// let x = A {
577///     number: 777,
578/// };
579/// assert_eq!(json!({ "number": "777" }), serde_json::to_value(&x).unwrap());
580/// assert_eq!(vec![145, 205, 3, 9], rmp_serde::to_vec(&x).unwrap());
581///
582/// #[serde_as]
583/// #[derive(Deserialize, Serialize)]
584/// struct B {
585///     #[serde_as(as = "IfIsHumanReadable<DurationMilliSeconds, DurationSeconds>")]
586///     duration: Duration,
587/// }
588/// let x = B {
589///     duration: Duration::from_millis(1500),
590/// };
591/// assert_eq!(json!({ "duration": 1500 }), serde_json::to_value(&x).unwrap());
592/// assert_eq!(vec![145, 2], rmp_serde::to_vec(&x).unwrap());
593/// # }
594/// ```
595/// [`De/Serializer::is_human_readable`]: serde::Serializer::is_human_readable
596/// [`is_human_readable`]: serde::Serializer::is_human_readable
597pub struct IfIsHumanReadable<H, F = Same>(PhantomData<H>, PhantomData<F>);
598
599/// De/Serialize a [`Option<String>`] type while transforming the empty string to [`None`]
600///
601/// Convert an [`Option<T>`] from/to string using [`FromStr`] and [`Display`](::core::fmt::Display) implementations.
602/// An empty string is deserialized as [`None`] and a [`None`] vice versa.
603///
604/// # Examples
605///
606/// ```
607/// # #[cfg(feature = "macros")] {
608/// # use serde::{Deserialize, Serialize};
609/// # use serde_json::json;
610/// # use serde_with::{serde_as, NoneAsEmptyString};
611/// #
612/// #[serde_as]
613/// #[derive(Deserialize, Serialize)]
614/// struct A {
615///     #[serde_as(as = "NoneAsEmptyString")]
616///     tags: Option<String>,
617/// }
618///
619/// let v: A = serde_json::from_value(json!({ "tags": "" })).unwrap();
620/// assert_eq!(None, v.tags);
621///
622/// let v: A = serde_json::from_value(json!({ "tags": "Hi" })).unwrap();
623/// assert_eq!(Some("Hi".to_string()), v.tags);
624///
625/// let x = A {
626///     tags: Some("This is text".to_string()),
627/// };
628/// assert_eq!(json!({ "tags": "This is text" }), serde_json::to_value(x).unwrap());
629///
630/// let x = A {
631///     tags: None,
632/// };
633/// assert_eq!(json!({ "tags": "" }), serde_json::to_value(x).unwrap());
634/// # }
635/// ```
636///
637/// [`FromStr`]: std::str::FromStr
638pub struct NoneAsEmptyString;
639
640/// Deserialize value and return [`Default`] on error
641///
642/// The main use case is ignoring error while deserializing.
643/// Instead of erroring, it simply deserializes the [`Default`] variant of the type.
644/// It is not possible to find the error location, i.e., which field had a deserialization error, with this method.
645/// During serialization this wrapper does nothing.
646/// The serialization behavior of the underlying type is preserved.
647/// The type must implement [`Default`] for this conversion to work.
648///
649/// # Examples
650///
651/// ```
652/// # #[cfg(feature = "macros")] {
653/// # use serde::Deserialize;
654/// # use serde_with::{serde_as, DefaultOnError};
655/// #
656/// #[serde_as]
657/// #[derive(Deserialize, Debug)]
658/// struct A {
659///     #[serde_as(deserialize_as = "DefaultOnError")]
660///     value: u32,
661/// }
662///
663/// let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
664/// assert_eq!(123, a.value);
665///
666/// // null is of invalid type
667/// let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
668/// assert_eq!(0, a.value);
669///
670/// // String is of invalid type
671/// let a: A = serde_json::from_str(r#"{"value": "123"}"#).unwrap();
672/// assert_eq!(0, a.value);
673///
674/// // Map is of invalid type
675/// let a: A = dbg!(serde_json::from_str(r#"{"value": {}}"#)).unwrap();
676/// assert_eq!(0, a.value);
677///
678/// // Missing entries still cause errors
679/// assert!(serde_json::from_str::<A>(r#"{  }"#).is_err());
680/// # }
681/// ```
682///
683/// Deserializing missing values can be supported by adding the `default` field attribute:
684///
685/// ```
686/// # #[cfg(feature = "macros")] {
687/// # use serde::Deserialize;
688/// # use serde_with::{serde_as, DefaultOnError};
689/// #
690/// #[serde_as]
691/// #[derive(Deserialize)]
692/// struct B {
693///     #[serde_as(deserialize_as = "DefaultOnError")]
694///     #[serde(default)]
695///     value: u32,
696/// }
697///
698/// let b: B = serde_json::from_str(r#"{  }"#).unwrap();
699/// assert_eq!(0, b.value);
700/// # }
701/// ```
702///
703/// `DefaultOnError` can be combined with other conversion methods.
704/// In this example, we deserialize a `Vec`, each element is deserialized from a string.
705/// If the string does not parse as a number, then we get the default value of 0.
706///
707/// ```rust
708/// # #[cfg(feature = "macros")] {
709/// # use serde::{Deserialize, Serialize};
710/// # use serde_json::json;
711/// # use serde_with::{serde_as, DefaultOnError, DisplayFromStr};
712/// #
713/// #[serde_as]
714/// #[derive(Serialize, Deserialize)]
715/// struct C {
716///     #[serde_as(as = "Vec<DefaultOnError<DisplayFromStr>>")]
717///     value: Vec<u32>,
718/// }
719///
720/// let c: C = serde_json::from_value(json!({
721///     "value": ["1", "2", "a3", "", {}, "6"]
722/// })).unwrap();
723/// assert_eq!(vec![1, 2, 0, 0, 0, 6], c.value);
724/// # }
725/// ```
726#[cfg(feature = "alloc")]
727pub struct DefaultOnError<T = Same>(PhantomData<T>);
728
729/// Deserialize [`Default`] from `null` values
730///
731/// Instead of erroring on `null` values, it simply deserializes the [`Default`] variant of the type.
732/// During serialization this wrapper does nothing.
733/// The serialization behavior of the underlying type is preserved.
734/// The type must implement [`Default`] for this conversion to work.
735///
736/// # Examples
737///
738/// ```
739/// # #[cfg(feature = "macros")] {
740/// # use serde::Deserialize;
741/// # use serde_with::{serde_as, DefaultOnNull};
742/// #
743/// #[serde_as]
744/// #[derive(Deserialize, Debug)]
745/// struct A {
746///     #[serde_as(deserialize_as = "DefaultOnNull")]
747///     value: u32,
748/// }
749///
750/// let a: A = serde_json::from_str(r#"{"value": 123}"#).unwrap();
751/// assert_eq!(123, a.value);
752///
753/// // null values are deserialized into the default, here 0
754/// let a: A = serde_json::from_str(r#"{"value": null}"#).unwrap();
755/// assert_eq!(0, a.value);
756/// # }
757/// ```
758///
759/// `DefaultOnNull` can be combined with other conversion methods.
760/// In this example, we deserialize a `Vec`, each element is deserialized from a string.
761/// If we encounter null, then we get the default value of 0.
762///
763/// ```rust
764/// # #[cfg(feature = "macros")] {
765/// # use serde::{Deserialize, Serialize};
766/// # use serde_json::json;
767/// # use serde_with::{serde_as, DefaultOnNull, DisplayFromStr};
768/// #
769/// #[serde_as]
770/// #[derive(Serialize, Deserialize)]
771/// struct C {
772///     #[serde_as(as = "Vec<DefaultOnNull<DisplayFromStr>>")]
773///     value: Vec<u32>,
774/// }
775///
776/// let c: C = serde_json::from_value(json!({
777///     "value": ["1", "2", null, null, "5"]
778/// })).unwrap();
779/// assert_eq!(vec![1, 2, 0, 0, 5], c.value);
780/// # }
781/// ```
782pub struct DefaultOnNull<T = Same>(PhantomData<T>);
783
784/// Deserialize from bytes or string
785///
786/// Any Rust [`String`] can be converted into bytes, i.e., `Vec<u8>`.
787/// Accepting both as formats while deserializing can be helpful while interacting with language
788/// which have a looser definition of string than Rust.
789///
790/// # Example
791/// ```rust
792/// # #[cfg(feature = "macros")] {
793/// # use serde::{Deserialize, Serialize};
794/// # use serde_json::json;
795/// # use serde_with::{serde_as, BytesOrString};
796/// #
797/// #[serde_as]
798/// #[derive(Deserialize, Serialize)]
799/// struct A {
800///     #[serde_as(as = "BytesOrString")]
801///     bytes_or_string: Vec<u8>,
802/// }
803///
804/// // Here we deserialize from a byte array ...
805/// let j = json!({
806///   "bytes_or_string": [
807///     0,
808///     1,
809///     2,
810///     3
811///   ]
812/// });
813///
814/// let a: A = serde_json::from_value(j.clone()).unwrap();
815/// assert_eq!(vec![0, 1, 2, 3], a.bytes_or_string);
816///
817/// // and serialization works too.
818/// assert_eq!(j, serde_json::to_value(&a).unwrap());
819///
820/// // But we also support deserializing from a String
821/// let j = json!({
822///   "bytes_or_string": "✨Works!"
823/// });
824///
825/// let a: A = serde_json::from_value(j).unwrap();
826/// assert_eq!("✨Works!".as_bytes(), &*a.bytes_or_string);
827/// # }
828/// ```
829/// [`String`]: std::string::String
830#[cfg(feature = "alloc")]
831pub struct BytesOrString;
832
833/// De/Serialize Durations as number of seconds.
834///
835/// De/serialize durations as number of seconds with sub-second precision.
836/// Sub-second precision is *only* supported for [`DurationSecondsWithFrac`], but not for [`DurationSeconds`].
837/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
838///
839/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
840/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `u64` deserialization from a `f64` will error.
841/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct duration and allows deserialization from any type.
842/// For example, deserializing `DurationSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
843/// Serialization of integers will round the duration to the nearest value.
844///
845/// This type also supports [`chrono::Duration`] with the `chrono_0_4`-[feature flag].
846/// This type also supports [`time::Duration`][::time_0_3::Duration] with the `time_0_3`-[feature flag].
847///
848/// This table lists the available `FORMAT`s for the different duration types.
849/// The `FORMAT` specifier defaults to `u64`/`f64`.
850///
851/// | Duration Type         | Converter                 | Available `FORMAT`s      |
852/// | --------------------- | ------------------------- | ------------------------ |
853/// | `std::time::Duration` | `DurationSeconds`         | *`u64`*, `f64`, `String` |
854/// | `std::time::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String`        |
855/// | `chrono::Duration`    | `DurationSeconds`         | `i64`, `f64`, `String`   |
856/// | `chrono::Duration`    | `DurationSecondsWithFrac` | *`f64`*, `String`        |
857/// | `time::Duration`      | `DurationSeconds`         | `i64`, `f64`, `String`   |
858/// | `time::Duration`      | `DurationSecondsWithFrac` | *`f64`*, `String`        |
859///
860/// # Examples
861///
862/// ```rust
863/// # #[cfg(feature = "macros")] {
864/// # use serde::{Deserialize, Serialize};
865/// # use serde_json::json;
866/// # use serde_with::{serde_as, DurationSeconds};
867/// use std::time::Duration;
868///
869/// #[serde_as]
870/// # #[derive(Debug, PartialEq)]
871/// #[derive(Deserialize, Serialize)]
872/// struct Durations {
873///     #[serde_as(as = "DurationSeconds<u64>")]
874///     d_u64: Duration,
875///     #[serde_as(as = "DurationSeconds<f64>")]
876///     d_f64: Duration,
877///     #[serde_as(as = "DurationSeconds<String>")]
878///     d_string: Duration,
879/// }
880///
881/// // Serialization
882/// // See how the values get rounded, since subsecond precision is not allowed.
883///
884/// let d = Durations {
885///     d_u64: Duration::new(12345, 0), // Create from seconds and nanoseconds
886///     d_f64: Duration::new(12345, 500_000_000),
887///     d_string: Duration::new(12345, 999_999_999),
888/// };
889/// // Observe the different data types
890/// let expected = json!({
891///     "d_u64": 12345,
892///     "d_f64": 12346.0,
893///     "d_string": "12346",
894/// });
895/// assert_eq!(expected, serde_json::to_value(d).unwrap());
896///
897/// // Deserialization works too
898/// // Subsecond precision in numbers will be rounded away
899///
900/// let json = json!({
901///     "d_u64": 12345,
902///     "d_f64": 12345.5,
903///     "d_string": "12346",
904/// });
905/// let expected = Durations {
906///     d_u64: Duration::new(12345, 0), // Create from seconds and nanoseconds
907///     d_f64: Duration::new(12346, 0),
908///     d_string: Duration::new(12346, 0),
909/// };
910/// assert_eq!(expected, serde_json::from_value(json).unwrap());
911/// # }
912/// ```
913///
914/// [`chrono::Duration`] is also supported when using the `chrono_0_4` feature.
915/// It is a signed duration, thus can be de/serialized as an `i64` instead of a `u64`.
916///
917/// ```rust
918/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
919/// # use serde::{Deserialize, Serialize};
920/// # use serde_json::json;
921/// # use serde_with::{serde_as, DurationSeconds};
922/// # use chrono_0_4::Duration;
923/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
924/// use chrono::Duration;
925/// # */
926///
927/// #[serde_as]
928/// # #[derive(Debug, PartialEq)]
929/// #[derive(Deserialize, Serialize)]
930/// struct Durations {
931///     #[serde_as(as = "DurationSeconds<i64>")]
932///     d_i64: Duration,
933///     #[serde_as(as = "DurationSeconds<f64>")]
934///     d_f64: Duration,
935///     #[serde_as(as = "DurationSeconds<String>")]
936///     d_string: Duration,
937/// }
938///
939/// // Serialization
940/// // See how the values get rounded, since subsecond precision is not allowed.
941///
942/// let d = Durations {
943///     d_i64: Duration::seconds(-12345),
944///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
945///     d_string: Duration::seconds(12345) + Duration::nanoseconds(999_999_999),
946/// };
947/// // Observe the different data types
948/// let expected = json!({
949///     "d_i64": -12345,
950///     "d_f64": -12345.0,
951///     "d_string": "12346",
952/// });
953/// assert_eq!(expected, serde_json::to_value(d).unwrap());
954///
955/// // Deserialization works too
956/// // Subsecond precision in numbers will be rounded away
957///
958/// let json = json!({
959///     "d_i64": -12345,
960///     "d_f64": -12345.5,
961///     "d_string": "12346",
962/// });
963/// let expected = Durations {
964///     d_i64: Duration::seconds(-12345),
965///     d_f64: Duration::seconds(-12346),
966///     d_string: Duration::seconds(12346),
967/// };
968/// assert_eq!(expected, serde_json::from_value(json).unwrap());
969/// # }
970/// ```
971///
972/// [`chrono::Duration`]: ::chrono_0_4::Duration
973/// [feature flag]: https://docs.rs/serde_with/3.13.0/serde_with/guide/feature_flags/index.html
974pub struct DurationSeconds<
975    FORMAT: formats::Format = u64,
976    STRICTNESS: formats::Strictness = formats::Strict,
977>(PhantomData<(FORMAT, STRICTNESS)>);
978
979/// De/Serialize Durations as number of seconds.
980///
981/// De/serialize durations as number of seconds with subsecond precision.
982/// Subsecond precision is *only* supported for [`DurationSecondsWithFrac`], but not for [`DurationSeconds`].
983/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
984/// Serialization of integers will round the duration to the nearest value.
985///
986/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
987/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `u64` deserialization from a `f64` will error.
988/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct duration and allows deserialization from any type.
989/// For example, deserializing `DurationSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
990///
991/// This type also supports [`chrono::Duration`] with the `chrono`-[feature flag].
992/// This type also supports [`time::Duration`][::time_0_3::Duration] with the `time_0_3`-[feature flag].
993///
994/// This table lists the available `FORMAT`s for the different duration types.
995/// The `FORMAT` specifier defaults to `u64`/`f64`.
996///
997/// | Duration Type         | Converter                 | Available `FORMAT`s      |
998/// | --------------------- | ------------------------- | ------------------------ |
999/// | `std::time::Duration` | `DurationSeconds`         | *`u64`*, `f64`, `String` |
1000/// | `std::time::Duration` | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1001/// | `chrono::Duration`    | `DurationSeconds`         | `i64`, `f64`, `String`   |
1002/// | `chrono::Duration`    | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1003/// | `time::Duration`      | `DurationSeconds`         | `i64`, `f64`, `String`   |
1004/// | `time::Duration`      | `DurationSecondsWithFrac` | *`f64`*, `String`        |
1005///
1006/// # Examples
1007///
1008/// ```rust
1009/// # #[cfg(feature = "macros")] {
1010/// # use serde::{Deserialize, Serialize};
1011/// # use serde_json::json;
1012/// # use serde_with::{serde_as, DurationSecondsWithFrac};
1013/// use std::time::Duration;
1014///
1015/// #[serde_as]
1016/// # #[derive(Debug, PartialEq)]
1017/// #[derive(Deserialize, Serialize)]
1018/// struct Durations {
1019///     #[serde_as(as = "DurationSecondsWithFrac<f64>")]
1020///     d_f64: Duration,
1021///     #[serde_as(as = "DurationSecondsWithFrac<String>")]
1022///     d_string: Duration,
1023/// }
1024///
1025/// // Serialization
1026/// // See how the values get rounded, since subsecond precision is not allowed.
1027///
1028/// let d = Durations {
1029///     d_f64: Duration::new(12345, 500_000_000), // Create from seconds and nanoseconds
1030///     d_string: Duration::new(12345, 999_999_000),
1031/// };
1032/// // Observe the different data types
1033/// let expected = json!({
1034///     "d_f64": 12345.5,
1035///     "d_string": "12345.999999",
1036/// });
1037/// assert_eq!(expected, serde_json::to_value(d).unwrap());
1038///
1039/// // Deserialization works too
1040/// // Subsecond precision in numbers will be rounded away
1041///
1042/// let json = json!({
1043///     "d_f64": 12345.5,
1044///     "d_string": "12345.987654",
1045/// });
1046/// let expected = Durations {
1047///     d_f64: Duration::new(12345, 500_000_000), // Create from seconds and nanoseconds
1048///     d_string: Duration::new(12345, 987_654_000),
1049/// };
1050/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1051/// # }
1052/// ```
1053///
1054/// [`chrono::Duration`] is also supported when using the `chrono_0_4` feature.
1055/// It is a signed duration, thus can be de/serialized as an `i64` instead of a `u64`.
1056///
1057/// ```rust
1058/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1059/// # use serde::{Deserialize, Serialize};
1060/// # use serde_json::json;
1061/// # use serde_with::{serde_as, DurationSecondsWithFrac};
1062/// # use chrono_0_4::Duration;
1063/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1064/// use chrono::Duration;
1065/// # */
1066///
1067/// #[serde_as]
1068/// # #[derive(Debug, PartialEq)]
1069/// #[derive(Deserialize, Serialize)]
1070/// struct Durations {
1071///     #[serde_as(as = "DurationSecondsWithFrac<f64>")]
1072///     d_f64: Duration,
1073///     #[serde_as(as = "DurationSecondsWithFrac<String>")]
1074///     d_string: Duration,
1075/// }
1076///
1077/// // Serialization
1078///
1079/// let d = Durations {
1080///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
1081///     d_string: Duration::seconds(12345) + Duration::nanoseconds(999_999_000),
1082/// };
1083/// // Observe the different data types
1084/// let expected = json!({
1085///     "d_f64": -12344.5,
1086///     "d_string": "12345.999999",
1087/// });
1088/// assert_eq!(expected, serde_json::to_value(d).unwrap());
1089///
1090/// // Deserialization works too
1091///
1092/// let json = json!({
1093///     "d_f64": -12344.5,
1094///     "d_string": "12345.987",
1095/// });
1096/// let expected = Durations {
1097///     d_f64: Duration::seconds(-12345) + Duration::milliseconds(500),
1098///     d_string: Duration::seconds(12345) + Duration::milliseconds(987),
1099/// };
1100/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1101/// # }
1102/// ```
1103///
1104/// [`chrono::Duration`]: ::chrono_0_4::Duration
1105/// [feature flag]: https://docs.rs/serde_with/3.13.0/serde_with/guide/feature_flags/index.html
1106pub struct DurationSecondsWithFrac<
1107    FORMAT: formats::Format = f64,
1108    STRICTNESS: formats::Strictness = formats::Strict,
1109>(PhantomData<(FORMAT, STRICTNESS)>);
1110
1111/// Equivalent to [`DurationSeconds`] with milli-seconds as base unit.
1112///
1113/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 milli-second instead of 1 second for [`DurationSeconds`].
1114pub struct DurationMilliSeconds<
1115    FORMAT: formats::Format = u64,
1116    STRICTNESS: formats::Strictness = formats::Strict,
1117>(PhantomData<(FORMAT, STRICTNESS)>);
1118
1119/// Equivalent to [`DurationSecondsWithFrac`] with milli-seconds as base unit.
1120///
1121/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 milli-second instead of 1 second for [`DurationSecondsWithFrac`].
1122pub struct DurationMilliSecondsWithFrac<
1123    FORMAT: formats::Format = f64,
1124    STRICTNESS: formats::Strictness = formats::Strict,
1125>(PhantomData<(FORMAT, STRICTNESS)>);
1126
1127/// Equivalent to [`DurationSeconds`] with micro-seconds as base unit.
1128///
1129/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 micro-second instead of 1 second for [`DurationSeconds`].
1130pub struct DurationMicroSeconds<
1131    FORMAT: formats::Format = u64,
1132    STRICTNESS: formats::Strictness = formats::Strict,
1133>(PhantomData<(FORMAT, STRICTNESS)>);
1134
1135/// Equivalent to [`DurationSecondsWithFrac`] with micro-seconds as base unit.
1136///
1137/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 micro-second instead of 1 second for [`DurationSecondsWithFrac`].
1138pub struct DurationMicroSecondsWithFrac<
1139    FORMAT: formats::Format = f64,
1140    STRICTNESS: formats::Strictness = formats::Strict,
1141>(PhantomData<(FORMAT, STRICTNESS)>);
1142
1143/// Equivalent to [`DurationSeconds`] with nano-seconds as base unit.
1144///
1145/// This type is equivalent to [`DurationSeconds`] except that each unit represents 1 nano-second instead of 1 second for [`DurationSeconds`].
1146pub struct DurationNanoSeconds<
1147    FORMAT: formats::Format = u64,
1148    STRICTNESS: formats::Strictness = formats::Strict,
1149>(PhantomData<(FORMAT, STRICTNESS)>);
1150
1151/// Equivalent to [`DurationSecondsWithFrac`] with nano-seconds as base unit.
1152///
1153/// This type is equivalent to [`DurationSecondsWithFrac`] except that each unit represents 1 nano-second instead of 1 second for [`DurationSecondsWithFrac`].
1154pub struct DurationNanoSecondsWithFrac<
1155    FORMAT: formats::Format = f64,
1156    STRICTNESS: formats::Strictness = formats::Strict,
1157>(PhantomData<(FORMAT, STRICTNESS)>);
1158
1159/// De/Serialize timestamps as seconds since the UNIX epoch
1160///
1161/// De/serialize timestamps as seconds since the UNIX epoch.
1162/// Subsecond precision is *only* supported for [`TimestampSecondsWithFrac`], but not for [`TimestampSeconds`].
1163/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
1164/// Serialization of integers will round the timestamp to the nearest value.
1165///
1166/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
1167/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `i64` deserialization from a `f64` will error.
1168/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct timestamp and allows deserialization from any type.
1169/// For example, deserializing `TimestampSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
1170///
1171/// This type also supports [`chrono::DateTime`] with the `chrono_0_4`-[feature flag].
1172/// This type also supports [`time::OffsetDateTime`][::time_0_3::OffsetDateTime] and [`time::PrimitiveDateTime`][::time_0_3::PrimitiveDateTime] with the `time_0_3`-[feature flag].
1173///
1174/// This table lists the available `FORMAT`s for the different timestamp types.
1175/// The `FORMAT` specifier defaults to `i64` or `f64`.
1176///
1177/// | Timestamp Type            | Converter                  | Available `FORMAT`s      |
1178/// | ------------------------- | -------------------------- | ------------------------ |
1179/// | `std::time::SystemTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1180/// | `std::time::SystemTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1181/// | `chrono::DateTime<Utc>`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1182/// | `chrono::DateTime<Utc>`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1183/// | `chrono::DateTime<Local>` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1184/// | `chrono::DateTime<Local>` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1185/// | `chrono::NaiveDateTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1186/// | `chrono::NaiveDateTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1187/// | `time::OffsetDateTime`    | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1188/// | `time::OffsetDateTime`    | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1189/// | `time::PrimitiveDateTime` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1190/// | `time::PrimitiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1191///
1192/// # Examples
1193///
1194/// ```rust
1195/// # #[cfg(feature = "macros")] {
1196/// # use serde::{Deserialize, Serialize};
1197/// # use serde_json::json;
1198/// # use serde_with::{serde_as, TimestampSeconds};
1199/// use std::time::{Duration, SystemTime};
1200///
1201/// #[serde_as]
1202/// # #[derive(Debug, PartialEq)]
1203/// #[derive(Deserialize, Serialize)]
1204/// struct Timestamps {
1205///     #[serde_as(as = "TimestampSeconds<i64>")]
1206///     st_i64: SystemTime,
1207///     #[serde_as(as = "TimestampSeconds<f64>")]
1208///     st_f64: SystemTime,
1209///     #[serde_as(as = "TimestampSeconds<String>")]
1210///     st_string: SystemTime,
1211/// }
1212///
1213/// // Serialization
1214/// // See how the values get rounded, since subsecond precision is not allowed.
1215///
1216/// let ts = Timestamps {
1217///     st_i64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 0)).unwrap(),
1218///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1219///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 999_999_999)).unwrap(),
1220/// };
1221/// // Observe the different data types
1222/// let expected = json!({
1223///     "st_i64": 12345,
1224///     "st_f64": 12346.0,
1225///     "st_string": "12346",
1226/// });
1227/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1228///
1229/// // Deserialization works too
1230/// // Subsecond precision in numbers will be rounded away
1231///
1232/// let json = json!({
1233///     "st_i64": 12345,
1234///     "st_f64": 12345.5,
1235///     "st_string": "12346",
1236/// });
1237/// let expected  = Timestamps {
1238///     st_i64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 0)).unwrap(),
1239///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12346, 0)).unwrap(),
1240///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12346, 0)).unwrap(),
1241/// };
1242/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1243/// # }
1244/// ```
1245///
1246/// [`chrono::DateTime<Utc>`] and [`chrono::DateTime<Local>`] are also supported when using the `chrono` feature.
1247/// Like [`SystemTime`], it is a signed timestamp, thus can be de/serialized as an `i64`.
1248///
1249/// ```rust
1250/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1251/// # use serde::{Deserialize, Serialize};
1252/// # use serde_json::json;
1253/// # use serde_with::{serde_as, TimestampSeconds};
1254/// # use chrono_0_4::{DateTime, Local, TimeZone, Utc};
1255/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1256/// use chrono::{DateTime, Local, TimeZone, Utc};
1257/// # */
1258///
1259/// #[serde_as]
1260/// # #[derive(Debug, PartialEq)]
1261/// #[derive(Deserialize, Serialize)]
1262/// struct Timestamps {
1263///     #[serde_as(as = "TimestampSeconds<i64>")]
1264///     dt_i64: DateTime<Utc>,
1265///     #[serde_as(as = "TimestampSeconds<f64>")]
1266///     dt_f64: DateTime<Local>,
1267///     #[serde_as(as = "TimestampSeconds<String>")]
1268///     dt_string: DateTime<Utc>,
1269/// }
1270///
1271/// // Serialization
1272/// // See how the values get rounded, since subsecond precision is not allowed.
1273///
1274/// let ts = Timestamps {
1275///     dt_i64: Utc.timestamp_opt(-12345, 0).unwrap(),
1276///     dt_f64: Local.timestamp_opt(-12345, 500_000_000).unwrap(),
1277///     dt_string: Utc.timestamp_opt(12345, 999_999_999).unwrap(),
1278/// };
1279/// // Observe the different data types
1280/// let expected = json!({
1281///     "dt_i64": -12345,
1282///     "dt_f64": -12345.0,
1283///     "dt_string": "12346",
1284/// });
1285/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1286///
1287/// // Deserialization works too
1288/// // Subsecond precision in numbers will be rounded away
1289///
1290/// let json = json!({
1291///     "dt_i64": -12345,
1292///     "dt_f64": -12345.5,
1293///     "dt_string": "12346",
1294/// });
1295/// let expected = Timestamps {
1296///     dt_i64: Utc.timestamp_opt(-12345, 0).unwrap(),
1297///     dt_f64: Local.timestamp_opt(-12346, 0).unwrap(),
1298///     dt_string: Utc.timestamp_opt(12346, 0).unwrap(),
1299/// };
1300/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1301/// # }
1302/// ```
1303///
1304/// [`SystemTime`]: std::time::SystemTime
1305/// [`chrono::DateTime<Local>`]: ::chrono_0_4::DateTime
1306/// [`chrono::DateTime<Utc>`]: ::chrono_0_4::DateTime
1307/// [feature flag]: https://docs.rs/serde_with/3.13.0/serde_with/guide/feature_flags/index.html
1308pub struct TimestampSeconds<
1309    FORMAT: formats::Format = i64,
1310    STRICTNESS: formats::Strictness = formats::Strict,
1311>(PhantomData<(FORMAT, STRICTNESS)>);
1312
1313/// De/Serialize timestamps as seconds since the UNIX epoch
1314///
1315/// De/serialize timestamps as seconds since the UNIX epoch.
1316/// Subsecond precision is *only* supported for [`TimestampSecondsWithFrac`], but not for [`TimestampSeconds`].
1317/// You can configure the serialization format between integers, floats, and stringified numbers with the `FORMAT` specifier and configure the deserialization with the `STRICTNESS` specifier.
1318/// Serialization of integers will round the timestamp to the nearest value.
1319///
1320/// The `STRICTNESS` specifier can either be [`formats::Strict`] or [`formats::Flexible`] and defaults to [`formats::Strict`].
1321/// [`formats::Strict`] means that deserialization only supports the type given in `FORMAT`, e.g., if `FORMAT` is `i64` deserialization from a `f64` will error.
1322/// [`formats::Flexible`] means that deserialization will perform a best effort to extract the correct timestamp and allows deserialization from any type.
1323/// For example, deserializing `TimestampSeconds<f64, Flexible>` will discard any subsecond precision during deserialization from `f64` and will parse a `String` as an integer number.
1324///
1325/// This type also supports [`chrono::DateTime`] and [`chrono::NaiveDateTime`][NaiveDateTime] with the `chrono`-[feature flag].
1326/// This type also supports [`time::OffsetDateTime`][::time_0_3::OffsetDateTime] and [`time::PrimitiveDateTime`][::time_0_3::PrimitiveDateTime] with the `time_0_3`-[feature flag].
1327///
1328/// This table lists the available `FORMAT`s for the different timestamp types.
1329/// The `FORMAT` specifier defaults to `i64` or `f64`.
1330///
1331/// | Timestamp Type            | Converter                  | Available `FORMAT`s      |
1332/// | ------------------------- | -------------------------- | ------------------------ |
1333/// | `std::time::SystemTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1334/// | `std::time::SystemTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1335/// | `chrono::DateTime<Utc>`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1336/// | `chrono::DateTime<Utc>`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1337/// | `chrono::DateTime<Local>` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1338/// | `chrono::DateTime<Local>` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1339/// | `chrono::NaiveDateTime`   | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1340/// | `chrono::NaiveDateTime`   | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1341/// | `time::OffsetDateTime`    | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1342/// | `time::OffsetDateTime`    | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1343/// | `time::PrimitiveDateTime` | `TimestampSeconds`         | *`i64`*, `f64`, `String` |
1344/// | `time::PrimitiveDateTime` | `TimestampSecondsWithFrac` | *`f64`*, `String`        |
1345///
1346/// # Examples
1347///
1348/// ```rust
1349/// # #[cfg(feature = "macros")] {
1350/// # use serde::{Deserialize, Serialize};
1351/// # use serde_json::json;
1352/// # use serde_with::{serde_as, TimestampSecondsWithFrac};
1353/// use std::time::{Duration, SystemTime};
1354///
1355/// #[serde_as]
1356/// # #[derive(Debug, PartialEq)]
1357/// #[derive(Deserialize, Serialize)]
1358/// struct Timestamps {
1359///     #[serde_as(as = "TimestampSecondsWithFrac<f64>")]
1360///     st_f64: SystemTime,
1361///     #[serde_as(as = "TimestampSecondsWithFrac<String>")]
1362///     st_string: SystemTime,
1363/// }
1364///
1365/// // Serialization
1366/// // See how the values get rounded, since subsecond precision is not allowed.
1367///
1368/// let ts = Timestamps {
1369///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1370///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 999_999_000)).unwrap(),
1371/// };
1372/// // Observe the different data types
1373/// let expected = json!({
1374///     "st_f64": 12345.5,
1375///     "st_string": "12345.999999",
1376/// });
1377/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1378///
1379/// // Deserialization works too
1380/// // Subsecond precision in numbers will be rounded away
1381///
1382/// let json = json!({
1383///     "st_f64": 12345.5,
1384///     "st_string": "12345.987654",
1385/// });
1386/// let expected = Timestamps {
1387///     st_f64: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 500_000_000)).unwrap(),
1388///     st_string: SystemTime::UNIX_EPOCH.checked_add(Duration::new(12345, 987_654_000)).unwrap(),
1389/// };
1390/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1391/// # }
1392/// ```
1393///
1394/// [`chrono::DateTime<Utc>`] and [`chrono::DateTime<Local>`] are also supported when using the `chrono_0_4` feature.
1395/// Like [`SystemTime`], it is a signed timestamp, thus can be de/serialized as an `i64`.
1396///
1397/// ```rust
1398/// # #[cfg(all(feature = "macros", feature = "chrono_0_4"))] {
1399/// # use serde::{Deserialize, Serialize};
1400/// # use serde_json::json;
1401/// # use serde_with::{serde_as, TimestampSecondsWithFrac};
1402/// # use chrono_0_4::{DateTime, Local, TimeZone, Utc};
1403/// # /* Ugliness to make the docs look nicer since I want to hide the rename of the chrono crate
1404/// use chrono::{DateTime, Local, TimeZone, Utc};
1405/// # */
1406///
1407/// #[serde_as]
1408/// # #[derive(Debug, PartialEq)]
1409/// #[derive(Deserialize, Serialize)]
1410/// struct Timestamps {
1411///     #[serde_as(as = "TimestampSecondsWithFrac<f64>")]
1412///     dt_f64: DateTime<Utc>,
1413///     #[serde_as(as = "TimestampSecondsWithFrac<String>")]
1414///     dt_string: DateTime<Local>,
1415/// }
1416///
1417/// // Serialization
1418///
1419/// let ts = Timestamps {
1420///     dt_f64: Utc.timestamp_opt(-12345, 500_000_000).unwrap(),
1421///     dt_string: Local.timestamp_opt(12345, 999_999_000).unwrap(),
1422/// };
1423/// // Observe the different data types
1424/// let expected = json!({
1425///     "dt_f64": -12344.5,
1426///     "dt_string": "12345.999999",
1427/// });
1428/// assert_eq!(expected, serde_json::to_value(ts).unwrap());
1429///
1430/// // Deserialization works too
1431///
1432/// let json = json!({
1433///     "dt_f64": -12344.5,
1434///     "dt_string": "12345.987",
1435/// });
1436/// let expected = Timestamps {
1437///     dt_f64: Utc.timestamp_opt(-12345, 500_000_000).unwrap(),
1438///     dt_string: Local.timestamp_opt(12345, 987_000_000).unwrap(),
1439/// };
1440/// assert_eq!(expected, serde_json::from_value(json).unwrap());
1441/// # }
1442/// ```
1443///
1444/// [`SystemTime`]: std::time::SystemTime
1445/// [`chrono::DateTime`]: ::chrono_0_4::DateTime
1446/// [`chrono::DateTime<Local>`]: ::chrono_0_4::DateTime
1447/// [`chrono::DateTime<Utc>`]: ::chrono_0_4::DateTime
1448/// [NaiveDateTime]: ::chrono_0_4::NaiveDateTime
1449/// [feature flag]: https://docs.rs/serde_with/3.13.0/serde_with/guide/feature_flags/index.html
1450pub struct TimestampSecondsWithFrac<
1451    FORMAT: formats::Format = f64,
1452    STRICTNESS: formats::Strictness = formats::Strict,
1453>(PhantomData<(FORMAT, STRICTNESS)>);
1454
1455/// Equivalent to [`TimestampSeconds`] with milli-seconds as base unit.
1456///
1457/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 milli-second instead of 1 second for [`TimestampSeconds`].
1458pub struct TimestampMilliSeconds<
1459    FORMAT: formats::Format = i64,
1460    STRICTNESS: formats::Strictness = formats::Strict,
1461>(PhantomData<(FORMAT, STRICTNESS)>);
1462
1463/// Equivalent to [`TimestampSecondsWithFrac`] with milli-seconds as base unit.
1464///
1465/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 milli-second instead of 1 second for [`TimestampSecondsWithFrac`].
1466pub struct TimestampMilliSecondsWithFrac<
1467    FORMAT: formats::Format = f64,
1468    STRICTNESS: formats::Strictness = formats::Strict,
1469>(PhantomData<(FORMAT, STRICTNESS)>);
1470
1471/// Equivalent to [`TimestampSeconds`] with micro-seconds as base unit.
1472///
1473/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 micro-second instead of 1 second for [`TimestampSeconds`].
1474pub struct TimestampMicroSeconds<
1475    FORMAT: formats::Format = i64,
1476    STRICTNESS: formats::Strictness = formats::Strict,
1477>(PhantomData<(FORMAT, STRICTNESS)>);
1478
1479/// Equivalent to [`TimestampSecondsWithFrac`] with micro-seconds as base unit.
1480///
1481/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 micro-second instead of 1 second for [`TimestampSecondsWithFrac`].
1482pub struct TimestampMicroSecondsWithFrac<
1483    FORMAT: formats::Format = f64,
1484    STRICTNESS: formats::Strictness = formats::Strict,
1485>(PhantomData<(FORMAT, STRICTNESS)>);
1486
1487/// Equivalent to [`TimestampSeconds`] with nano-seconds as base unit.
1488///
1489/// This type is equivalent to [`TimestampSeconds`] except that each unit represents 1 nano-second instead of 1 second for [`TimestampSeconds`].
1490pub struct TimestampNanoSeconds<
1491    FORMAT: formats::Format = i64,
1492    STRICTNESS: formats::Strictness = formats::Strict,
1493>(PhantomData<(FORMAT, STRICTNESS)>);
1494
1495/// Equivalent to [`TimestampSecondsWithFrac`] with nano-seconds as base unit.
1496///
1497/// This type is equivalent to [`TimestampSecondsWithFrac`] except that each unit represents 1 nano-second instead of 1 second for [`TimestampSecondsWithFrac`].
1498pub struct TimestampNanoSecondsWithFrac<
1499    FORMAT: formats::Format = f64,
1500    STRICTNESS: formats::Strictness = formats::Strict,
1501>(PhantomData<(FORMAT, STRICTNESS)>);
1502
1503/// Optimized handling of owned and borrowed byte representations.
1504///
1505/// Serialization of byte sequences like `&[u8]` or `Vec<u8>` is quite inefficient since each value will be serialized individually.
1506/// This converter type optimizes the serialization and deserialization.
1507///
1508/// 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`].
1509///
1510/// The type provides de/serialization for these types:
1511///
1512/// * `[u8; N]`, not possible using `serde_bytes`
1513/// * `&[u8; N]`, not possible using `serde_bytes`
1514/// * `&[u8]`
1515/// * `Box<[u8; N]>`, not possible using `serde_bytes`
1516/// * `Box<[u8]>`
1517/// * `Vec<u8>`
1518/// * `Cow<'_, [u8]>`
1519/// * `Cow<'_, [u8; N]>`, not possible using `serde_bytes`
1520///
1521/// [`serde_bytes`]: https://crates.io/crates/serde_bytes
1522///
1523/// # Examples
1524///
1525/// ```
1526/// # #[cfg(feature = "macros")] {
1527/// # use serde::{Deserialize, Serialize};
1528/// # use serde_with::{serde_as, Bytes};
1529/// # use std::borrow::Cow;
1530/// #
1531/// #[serde_as]
1532/// # #[derive(Debug, PartialEq)]
1533/// #[derive(Deserialize, Serialize)]
1534/// struct Test<'a> {
1535///     #[serde_as(as = "Bytes")]
1536///     array: [u8; 15],
1537///     #[serde_as(as = "Bytes")]
1538///     boxed: Box<[u8]>,
1539///     #[serde_as(as = "Bytes")]
1540///     #[serde(borrow)]
1541///     cow: Cow<'a, [u8]>,
1542///     #[serde_as(as = "Bytes")]
1543///     #[serde(borrow)]
1544///     cow_array: Cow<'a, [u8; 15]>,
1545///     #[serde_as(as = "Bytes")]
1546///     vec: Vec<u8>,
1547/// }
1548///
1549/// let value = Test {
1550///     array: *b"0123456789ABCDE",
1551///     boxed: b"...".to_vec().into_boxed_slice(),
1552///     cow: Cow::Borrowed(b"FooBar"),
1553///     cow_array: Cow::Borrowed(&[42u8; 15]),
1554///     vec: vec![0x41, 0x61, 0x21],
1555/// };
1556/// let expected = r#"(
1557///     array: b"0123456789ABCDE",
1558///     boxed: b"...",
1559///     cow: b"FooBar",
1560///     cow_array: b"***************",
1561///     vec: b"Aa!",
1562/// )"#;
1563///
1564/// # let pretty_config = ron::ser::PrettyConfig::new().new_line("\n");
1565/// assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
1566/// assert_eq!(value, ron::from_str(expected).unwrap());
1567/// # }
1568/// ```
1569///
1570/// Fully borrowed types can also be used but you'll need a Deserializer that
1571/// supports Serde's 0-copy deserialization:
1572///
1573/// ```
1574/// # #[cfg(feature = "macros")] {
1575/// # use serde::{Deserialize, Serialize};
1576/// # use serde_with::{serde_as, Bytes};
1577/// #
1578/// #[serde_as]
1579/// # #[derive(Debug, PartialEq)]
1580/// #[derive(Deserialize, Serialize)]
1581/// struct TestBorrows<'a> {
1582///     #[serde_as(as = "Bytes")]
1583///     #[serde(borrow)]
1584///     array_buf: &'a [u8; 15],
1585///     #[serde_as(as = "Bytes")]
1586///     #[serde(borrow)]
1587///     buf: &'a [u8],
1588/// }
1589///
1590/// let value = TestBorrows {
1591///     array_buf: &[10u8; 15],
1592///     buf: &[20u8, 21u8, 22u8],
1593/// };
1594/// let expected = r#"(
1595///     array_buf: b"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
1596///     buf: b"\x14\x15\x16",
1597/// )"#;
1598///
1599/// # let pretty_config = ron::ser::PrettyConfig::new().new_line("\n");
1600/// assert_eq!(expected, ron::ser::to_string_pretty(&value, pretty_config).unwrap());
1601/// // RON doesn't support borrowed deserialization of byte arrays
1602/// # }
1603/// ```
1604///
1605/// ## Alternative to [`BytesOrString`]
1606///
1607/// The [`Bytes`] can replace [`BytesOrString`].
1608/// [`Bytes`] is implemented for more types, which makes it better.
1609/// The serialization behavior of [`Bytes`] differs from [`BytesOrString`], therefore only `deserialize_as` should be used.
1610///
1611/// ```rust
1612/// # #[cfg(feature = "macros")] {
1613/// # use serde::Deserialize;
1614/// # use serde_json::json;
1615/// # use serde_with::{serde_as, Bytes};
1616/// #
1617/// #[serde_as]
1618/// # #[derive(Debug, PartialEq)]
1619/// #[derive(Deserialize, serde::Serialize)]
1620/// struct Test {
1621///     #[serde_as(deserialize_as = "Bytes")]
1622///     from_bytes: Vec<u8>,
1623///     #[serde_as(deserialize_as = "Bytes")]
1624///     from_str: Vec<u8>,
1625/// }
1626///
1627/// // Different serialized values ...
1628/// let j = json!({
1629///     "from_bytes": [70,111,111,45,66,97,114],
1630///     "from_str": "Foo-Bar",
1631/// });
1632///
1633/// // can be deserialized ...
1634/// let test = Test {
1635///     from_bytes: b"Foo-Bar".to_vec(),
1636///     from_str: b"Foo-Bar".to_vec(),
1637/// };
1638/// assert_eq!(test, serde_json::from_value(j).unwrap());
1639///
1640/// // and serialization will always be a byte sequence
1641/// # assert_eq!(json!(
1642/// {
1643///     "from_bytes": [70,111,111,45,66,97,114],
1644///     "from_str": [70,111,111,45,66,97,114],
1645/// }
1646/// # ), serde_json::to_value(&test).unwrap());
1647/// # }
1648/// ```
1649pub struct Bytes;
1650
1651/// Deserialize one or many elements
1652///
1653/// Sometimes it is desirable to have a shortcut in writing 1-element lists in a config file.
1654/// Usually, this is done by either writing a list or the list element itself.
1655/// This distinction is not semantically important on the Rust side, thus both forms should deserialize into the same `Vec`.
1656///
1657/// The `OneOrMany` adapter achieves exactly this use case.
1658/// 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`].
1659/// By default, [`PreferOne`] is assumed, which can also be omitted like `OneOrMany<_>`.
1660///
1661/// [`PreferMany`]: crate::formats::PreferMany
1662/// [`PreferOne`]: crate::formats::PreferOne
1663///
1664/// # Examples
1665///
1666/// ```rust
1667/// # #[cfg(feature = "macros")] {
1668/// # use serde::Deserialize;
1669/// # use serde_json::json;
1670/// # use serde_with::{serde_as, OneOrMany};
1671/// # use serde_with::formats::{PreferOne, PreferMany};
1672/// #
1673/// #[serde_as]
1674/// # #[derive(Debug, PartialEq)]
1675/// #[derive(Deserialize, serde::Serialize)]
1676/// struct Data {
1677///     #[serde_as(as = "OneOrMany<_, PreferOne>")]
1678///     countries: Vec<String>,
1679///     #[serde_as(as = "OneOrMany<_, PreferMany>")]
1680///     cities: Vec<String>,
1681/// }
1682///
1683/// // The adapter allows deserializing a `Vec` from either
1684/// // a single element
1685/// let j = json!({
1686///     "countries": "Spain",
1687///     "cities": "Berlin",
1688/// });
1689/// assert!(serde_json::from_value::<Data>(j).is_ok());
1690///
1691/// // or from a list.
1692/// let j = json!({
1693///     "countries": ["Germany", "France"],
1694///     "cities": ["Amsterdam"],
1695/// });
1696/// assert!(serde_json::from_value::<Data>(j).is_ok());
1697///
1698/// // For serialization you can choose how a single element should be encoded.
1699/// // Either directly, with `PreferOne` (default), or as a list with `PreferMany`.
1700/// let data = Data {
1701///     countries: vec!["Spain".to_string()],
1702///     cities: vec!["Berlin".to_string()],
1703/// };
1704/// let j = json!({
1705///     "countries": "Spain",
1706///     "cities": ["Berlin"],
1707/// });
1708/// assert_eq!(serde_json::to_value(data).unwrap(), j);
1709/// # }
1710/// ```
1711#[cfg(feature = "alloc")]
1712pub struct OneOrMany<T, FORMAT: formats::Format = formats::PreferOne>(PhantomData<(T, FORMAT)>);
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/// Deserialize a sequence into `Vec<T>`, skipping elements which fail to deserialize.
2185///
2186/// The serialization behavior is identical to `Vec<T>`. This is an alternative to `Vec<T>`
2187/// which is resilient against unexpected data.
2188///
2189/// # Examples
2190///
2191/// ```rust
2192/// # #[cfg(feature = "macros")] {
2193/// # use serde::{Deserialize, Serialize};
2194/// # use serde_with::{serde_as, VecSkipError};
2195/// #
2196/// # #[derive(Debug, PartialEq)]
2197/// #[derive(Deserialize, Serialize)]
2198/// # #[non_exhaustive]
2199/// enum Color {
2200///     Red,
2201///     Green,
2202///     Blue,
2203/// }
2204/// # use Color::*;
2205/// #[serde_as]
2206/// # #[derive(Debug, PartialEq)]
2207/// #[derive(Deserialize, Serialize)]
2208/// struct Palette(#[serde_as(as = "VecSkipError<_>")] Vec<Color>);
2209///
2210/// let data = Palette(vec![Blue, Green,]);
2211/// let source_json = r#"["Blue", "Yellow", "Green"]"#;
2212/// let data_json = r#"["Blue","Green"]"#;
2213/// // Ensure serialization and deserialization produce the expected results
2214/// assert_eq!(data_json, serde_json::to_string(&data).unwrap());
2215/// assert_eq!(data, serde_json::from_str(source_json).unwrap());
2216/// # }
2217/// ```
2218#[cfg(feature = "alloc")]
2219pub struct VecSkipError<T>(PhantomData<T>);
2220
2221/// Deserialize a map, skipping keys and values which fail to deserialize.
2222///
2223/// By default serde terminates if it fails to deserialize a key or a value when deserializing
2224/// a map. Sometimes a map has heterogeneous keys or values but we only care about some specific
2225/// types, and it is desirable to skip entries on errors.
2226///
2227/// It is especially useful in conjunction to `#[serde(flatten)]` to capture a map mixed in with
2228/// other entries which we don't want to exhaust in the type definition.
2229///
2230/// The serialization behavior is identical to the underlying map.
2231///
2232/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2233///
2234/// [`BTreeMap`]: std::collections::BTreeMap
2235/// [`HashMap`]: std::collections::HashMap
2236///
2237/// # Examples
2238///
2239/// ```rust
2240/// # #[cfg(feature = "macros")] {
2241/// # use serde::{Deserialize, Serialize};
2242/// # use std::collections::BTreeMap;
2243/// # use serde_with::{serde_as, DisplayFromStr, MapSkipError};
2244/// #
2245/// #[serde_as]
2246/// # #[derive(Debug, PartialEq)]
2247/// #[derive(Deserialize, Serialize)]
2248/// struct VersionNames {
2249///     yanked: Vec<u16>,
2250///     #[serde_as(as = "MapSkipError<DisplayFromStr, _>")]
2251///     #[serde(flatten)]
2252///     names: BTreeMap<u16, String>,
2253/// }
2254///
2255/// let data = VersionNames {
2256///     yanked: vec![2, 5],
2257///     names: BTreeMap::from_iter([
2258///         (0u16, "v0".to_string()),
2259///         (1, "v1".to_string()),
2260///         (4, "v4".to_string())
2261///     ]),
2262/// };
2263/// let source_json = r#"{
2264///   "0": "v0",
2265///   "1": "v1",
2266///   "4": "v4",
2267///   "yanked": [2, 5],
2268///   "last_updated": 1704085200
2269/// }"#;
2270/// let data_json = r#"{"yanked":[2,5],"0":"v0","1":"v1","4":"v4"}"#;
2271/// // Ensure serialization and deserialization produce the expected results
2272/// assert_eq!(data_json, serde_json::to_string(&data).unwrap());
2273/// assert_eq!(data, serde_json::from_str(source_json).unwrap());
2274/// # }
2275/// ```
2276#[cfg(feature = "alloc")]
2277pub struct MapSkipError<K, V>(PhantomData<(K, V)>);
2278
2279/// Deserialize a boolean from a number
2280///
2281/// Deserialize a number (of `u8`) and turn it into a boolean.
2282/// The adapter supports a [`Strict`](crate::formats::Strict) and [`Flexible`](crate::formats::Flexible) format.
2283/// In `Strict` mode, the number must be `0` or `1`.
2284/// All other values produce an error.
2285/// In `Flexible` mode, the number any non-zero value is converted to `true`.
2286///
2287/// During serialization only `0` or `1` are ever emitted.
2288///
2289/// # Examples
2290///
2291/// ```rust
2292/// # #[cfg(feature = "macros")] {
2293/// # use serde::{Deserialize, Serialize};
2294/// # use serde_json::json;
2295/// # use serde_with::{serde_as, BoolFromInt};
2296/// #
2297/// #[serde_as]
2298/// # #[derive(Debug, PartialEq)]
2299/// #[derive(Deserialize, Serialize)]
2300/// struct Data(#[serde_as(as = "BoolFromInt")] bool);
2301///
2302/// let data = Data(true);
2303/// let j = json!(1);
2304/// // Ensure serialization and deserialization produce the expected results
2305/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2306/// assert_eq!(data, serde_json::from_value(j).unwrap());
2307///
2308/// // false maps to 0
2309/// let data = Data(false);
2310/// let j = json!(0);
2311/// assert_eq!(j, serde_json::to_value(&data).unwrap());
2312/// assert_eq!(data, serde_json::from_value(j).unwrap());
2313//
2314/// #[serde_as]
2315/// # #[derive(Debug, PartialEq)]
2316/// #[derive(Deserialize, Serialize)]
2317/// struct Flexible(#[serde_as(as = "BoolFromInt<serde_with::formats::Flexible>")] bool);
2318///
2319/// // Flexible turns any non-zero number into true
2320/// let data = Flexible(true);
2321/// let j = json!(100);
2322/// assert_eq!(data, serde_json::from_value(j).unwrap());
2323/// # }
2324/// ```
2325pub struct BoolFromInt<S: formats::Strictness = formats::Strict>(PhantomData<S>);
2326
2327/// De/Serialize a delimited collection using [`Display`] and [`FromStr`] implementation
2328///
2329/// `StringWithSeparator` takes a second type, which needs to implement [`Display`]+[`FromStr`] and constitutes the inner type of the collection.
2330/// You can define an arbitrary separator, by specifying a type which implements [`Separator`].
2331/// Some common ones, like space and comma are already predefined and you can find them [here][`Separator`].
2332///
2333/// An empty string deserializes as an empty collection.
2334///
2335/// # Examples
2336///
2337/// ```
2338/// # #[cfg(feature = "macros")] {
2339/// # use serde::{Deserialize, Serialize};
2340/// #
2341/// # use serde_with::{serde_as, StringWithSeparator};
2342/// use serde_with::formats::{CommaSeparator, SpaceSeparator};
2343/// use std::collections::BTreeSet;
2344///
2345/// #[serde_as]
2346/// #[derive(Deserialize, Serialize)]
2347/// struct A {
2348///     #[serde_as(as = "StringWithSeparator::<SpaceSeparator, String>")]
2349///     tags: Vec<String>,
2350///     #[serde_as(as = "StringWithSeparator::<CommaSeparator, String>")]
2351///     more_tags: BTreeSet<String>,
2352/// }
2353///
2354/// let v: A = serde_json::from_str(r##"{
2355///     "tags": "#hello #world",
2356///     "more_tags": "foo,bar,bar"
2357/// }"##).unwrap();
2358/// assert_eq!(vec!["#hello", "#world"], v.tags);
2359/// assert_eq!(2, v.more_tags.len());
2360///
2361/// let x = A {
2362///     tags: vec!["1".to_string(), "2".to_string(), "3".to_string()],
2363///     more_tags: BTreeSet::new(),
2364/// };
2365/// assert_eq!(
2366///     r#"{"tags":"1 2 3","more_tags":""}"#,
2367///     serde_json::to_string(&x).unwrap()
2368/// );
2369/// # }
2370/// ```
2371///
2372/// [`Display`]: core::fmt::Display
2373/// [`FromStr`]: core::str::FromStr
2374/// [`Separator`]: crate::formats::Separator
2375/// [`serde_as`]: crate::guide::serde_as
2376pub struct StringWithSeparator<Sep, T>(PhantomData<(Sep, T)>);
2377
2378/// This serializes a list of tuples into a map
2379///
2380/// Normally, you want to use a [`HashMap`] or a [`BTreeMap`] when deserializing a map.
2381/// However, sometimes this is not possible due to type constraints, e.g., if the type implements neither [`Hash`] nor [`Ord`].
2382/// Another use case is deserializing a map with duplicate keys.
2383///
2384/// # Examples
2385///
2386/// `Wrapper` does not implement [`Hash`] nor [`Ord`], thus prohibiting the use [`HashMap`] or [`BTreeMap`].
2387/// The JSON also contains a duplicate key.
2388///
2389/// [`BTreeMap`]: std::collections::BTreeMap
2390/// [`HashMap`]: std::collections::HashMap
2391/// [`Vec`]: std::vec::Vec
2392///
2393/// ```rust
2394/// # #[cfg(feature = "macros")] {
2395/// # use serde::{Deserialize, Serialize};
2396/// # use serde_with::{serde_as, Map};
2397/// #
2398/// #[serde_as]
2399/// #[derive(Debug, Deserialize, Serialize, Default)]
2400/// struct S {
2401///     #[serde_as(as = "Map<_, _>")]
2402///     s: Vec<(Wrapper<i32>, String)>,
2403/// }
2404///
2405/// #[derive(Clone, Debug, Serialize, Deserialize)]
2406/// #[serde(transparent)]
2407/// struct Wrapper<T>(T);
2408///
2409/// let data = S {
2410///     s: vec![
2411///         (Wrapper(1), "a".to_string()),
2412///         (Wrapper(2), "b".to_string()),
2413///         (Wrapper(3), "c".to_string()),
2414///         (Wrapper(2), "d".to_string()),
2415///     ],
2416/// };
2417///
2418/// let json = r#"{
2419///   "s": {
2420///     "1": "a",
2421///     "2": "b",
2422///     "3": "c",
2423///     "2": "d"
2424///   }
2425/// }"#;
2426/// assert_eq!(json, serde_json::to_string_pretty(&data).unwrap());
2427/// # }
2428/// ```
2429pub struct Map<K, V>(PhantomData<(K, V)>);
2430
2431/// De/Serialize a Map into a list of tuples
2432///
2433/// Some formats, like JSON, have limitations on the types of keys for maps.
2434/// In case of JSON, keys are restricted to strings.
2435/// Rust features more powerful keys, for example tuples, which can not be serialized to JSON.
2436///
2437/// This helper serializes the Map into a list of tuples, which do not have the same type restrictions.
2438///
2439/// # Examples
2440///
2441/// ```rust
2442/// # #[cfg(feature = "macros")] {
2443/// # use serde::{Deserialize, Serialize};
2444/// # use serde_json::json;
2445/// # use serde_with::{serde_as, Seq};
2446/// # use std::collections::BTreeMap;
2447/// #
2448/// #[serde_as]
2449/// # #[derive(Debug, PartialEq)]
2450/// #[derive(Deserialize, Serialize)]
2451/// struct A {
2452///     #[serde_as(as = "Seq<(_, _)>")]
2453///     s: BTreeMap<(String, u32), u32>,
2454/// }
2455///
2456/// // This converts the Rust type
2457/// let data = A {
2458///     s: BTreeMap::from([
2459///         (("Hello".to_string(), 123), 0),
2460///         (("World".to_string(), 456), 1),
2461///     ]),
2462/// };
2463///
2464/// // into this JSON
2465/// let value = json!({
2466///     "s": [
2467///         [["Hello", 123], 0],
2468///         [["World", 456], 1]
2469///     ]
2470/// });
2471///
2472/// assert_eq!(value, serde_json::to_value(&data).unwrap());
2473/// assert_eq!(data, serde_json::from_value(value).unwrap());
2474/// # }
2475/// ```
2476pub struct Seq<V>(PhantomData<V>);
2477
2478/// Ensure no duplicate keys exist in a map.
2479///
2480/// By default serde has a last-value-wins implementation, if duplicate keys for a map exist.
2481/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
2482/// and it can indicate an error in the serialized data.
2483///
2484/// This helper returns an error if two identical keys exist in a map.
2485///
2486/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2487///
2488/// [`BTreeMap`]: std::collections::BTreeMap
2489/// [`HashMap`]: std::collections::HashMap
2490///
2491/// # Example
2492///
2493/// ```rust
2494/// # #[cfg(feature = "macros")] {
2495/// # use serde::Deserialize;
2496/// # use std::collections::HashMap;
2497/// # use serde_with::{serde_as, MapPreventDuplicates};
2498/// #
2499/// #[serde_as]
2500/// # #[derive(Debug, Eq, PartialEq)]
2501/// #[derive(Deserialize)]
2502/// struct Doc {
2503///     #[serde_as(as = "MapPreventDuplicates<_, _>")]
2504///     map: HashMap<usize, usize>,
2505/// }
2506///
2507/// // Maps are serialized normally,
2508/// let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
2509/// let mut v = Doc {
2510///     map: HashMap::new(),
2511/// };
2512/// v.map.insert(1, 1);
2513/// v.map.insert(2, 2);
2514/// v.map.insert(3, 3);
2515/// assert_eq!(v, serde_json::from_str(s).unwrap());
2516///
2517/// // but create an error if duplicate keys, like the `1`, exist.
2518/// let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
2519/// let res: Result<Doc, _> = serde_json::from_str(s);
2520/// assert!(res.is_err());
2521/// # }
2522/// ```
2523#[cfg(feature = "alloc")]
2524pub struct MapPreventDuplicates<K, V>(PhantomData<(K, V)>);
2525
2526/// Ensure that the first key is taken, if duplicate keys exist
2527///
2528/// By default serde has a last-key-wins implementation, if duplicate keys for a map exist.
2529/// Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.
2530///
2531/// The implementation supports both the [`HashMap`] and the [`BTreeMap`] from the standard library.
2532///
2533/// [`BTreeMap`]: std::collections::BTreeMap
2534/// [`HashMap`]: std::collections::HashMap
2535#[cfg(feature = "alloc")]
2536pub struct MapFirstKeyWins<K, V>(PhantomData<(K, V)>);
2537
2538/// Ensure no duplicate values exist in a set.
2539///
2540/// By default serde has a last-value-wins implementation, if duplicate values for a set exist.
2541/// Sometimes it is desirable to know when such an event happens, as the first value is overwritten
2542/// and it can indicate an error in the serialized data.
2543///
2544/// This helper returns an error if two identical values exist in a set.
2545///
2546/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
2547///
2548/// [`BTreeSet`]: std::collections::BTreeSet
2549/// [`HashSet`]: std::collections::HashSet
2550///
2551/// # Example
2552///
2553/// ```rust
2554/// # #[cfg(feature = "macros")] {
2555/// # use std::collections::HashSet;
2556/// # use serde::Deserialize;
2557/// # use serde_with::{serde_as, SetPreventDuplicates};
2558/// #
2559/// #[serde_as]
2560/// # #[derive(Debug, Eq, PartialEq)]
2561/// #[derive(Deserialize)]
2562/// struct Doc {
2563///     #[serde_as(as = "SetPreventDuplicates<_>")]
2564///     set: HashSet<usize>,
2565/// }
2566///
2567/// // Sets are serialized normally,
2568/// let s = r#"{"set": [1, 2, 3, 4]}"#;
2569/// let v = Doc {
2570///     set: HashSet::from_iter(vec![1, 2, 3, 4]),
2571/// };
2572/// assert_eq!(v, serde_json::from_str(s).unwrap());
2573///
2574/// // but create an error if duplicate values, like the `1`, exist.
2575/// let s = r#"{"set": [1, 2, 3, 4, 1]}"#;
2576/// let res: Result<Doc, _> = serde_json::from_str(s);
2577/// assert!(res.is_err());
2578/// # }
2579/// ```
2580#[cfg(feature = "alloc")]
2581pub struct SetPreventDuplicates<T>(PhantomData<T>);
2582
2583/// Ensure that the last value is taken, if duplicate values exist
2584///
2585/// By default serde has a first-value-wins implementation, if duplicate keys for a set exist.
2586/// Sometimes the opposite strategy is desired. This helper implements a first-value-wins strategy.
2587///
2588/// The implementation supports both the [`HashSet`] and the [`BTreeSet`] from the standard library.
2589///
2590/// [`BTreeSet`]: std::collections::BTreeSet
2591/// [`HashSet`]: std::collections::HashSet
2592#[cfg(feature = "alloc")]
2593pub struct SetLastValueWins<T>(PhantomData<T>);
2594
2595/// Helper for implementing [`JsonSchema`] on serializers whose output depends
2596/// on the type of the concrete field.
2597///
2598/// It is added implicitly by the [`#[serde_as]`](crate::serde_as) macro when any `schemars`
2599/// feature is enabled.
2600///
2601/// [`JsonSchema`]: ::schemars_0_8::JsonSchema
2602#[cfg(any(feature = "schemars_0_8", feature = "schemars_0_9"))]
2603pub struct Schema<T: ?Sized, TA>(PhantomData<T>, PhantomData<TA>);