Debian Codegraph @

third_party/rust/serde_with/src/lib.rs

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