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