Skip to main content

deser_serde/
lib.rs

1//! Adapters to use [serde](https://serde.rs/) types with deser.
2//!
3//! This crate provides the [`Serde`] adapter which serializes and
4//! deserializes values with their serde implementations.  It's useful for
5//! types from crates which only support serde:
6//!
7//! ```
8//! use deser::{Deserialize, Serialize};
9//! use deser_serde::Serde;
10//!
11//! #[derive(serde::Serialize, serde::Deserialize)]
12//! struct Point {
13//!     x: i32,
14//!     y: i32,
15//! }
16//!
17//! #[derive(Serialize, Deserialize)]
18//! struct Shape {
19//!     name: String,
20//!     #[deser(as = Vec<Serde>)]
21//!     points: Vec<Point>,
22//!     #[deser(as = Serde)]
23//!     extra: serde_json::Value,
24//! }
25//!
26//! let shape: Shape = deser_json::from_str(
27//!     r#"{
28//!         "name": "line",
29//!         "points": [{"x": 1, "y": 2}, {"x": 3, "y": 4}],
30//!         "extra": [true]
31//!     }"#,
32//! )
33//! .unwrap();
34//! assert_eq!(shape.points[1].y, 4);
35//! assert_eq!(shape.extra, serde_json::json!([true]));
36//! ```
37//!
38//! Adapters compose with containers (`Vec<Serde>`, `Option<Serde>`, ...),
39//! for more information see [`deser::adapters`](deser_core::adapters).  To use the adapter
40//! outside of the derive, wrap values in [`As`](deser_core::adapters::As).
41//!
42//! # Data Model
43//!
44//! serde values are mapped to the deser data model like this:
45//!
46//! * Integers, floats, booleans, chars, strings and bytes map to the
47//!   respective atoms.  128 bit integers are extension values like the ones
48//!   of deser.
49//! * `None`, `()` and unit structs are null, `Some` and newtype structs are
50//!   the value they hold.
51//! * Sequences and tuples are sequences, maps and structs are maps.
52//! * Enums are externally tagged (the default in serde and deser): unit
53//!   variants are strings, all others are maps with the variant name as
54//!   single key.
55//!
56//! When deserializing, extension values that serde does not know (like
57//! date-times) are passed to serde as their fallback atom (for instance a
58//! string).  Map keys are also parsed from strings if serde asks for a
59//! number or boolean, so `HashMap<u32, _>` works with JSON.  Borrowing is
60//! supported: serde types which borrow (like `&'de str`) can borrow from
61//! the data if the format passes it on borrowed.
62//!
63//! [`is_human_readable`](serde::Serializer::is_human_readable) is always
64//! `true`.
65//!
66//! Missing struct fields are handled like serde: they are `None` if the
67//! type deserializes a missing value as option, which is the case for
68//! `Option<T>`.
69//!
70//! # Buffering
71//!
72//! serde and deser drive values in opposite directions: with serde the
73//! value is serialized into a serializer by nested calls and pulls
74//! from a deserializer, with deser the value is walked by the driver and
75//! events are pushed into deserializers.  So [`Serde`] buffers the events
76//! of compound values.  For atoms (the typical case, like `Url` or
77//! `IpAddr`) there is no buffering.
78#![doc(html_logo_url = "https://raw.githubusercontent.com/mitsuhiko/deser/main/artwork/logo.svg")]
79
80use std::borrow::Cow;
81
82use deser_core::Deserialize;
83use deser_core::Serialize;
84use deser_core::State;
85use deser_core::de::SinkHandle;
86use deser_core::ser::Emit;
87
88mod buffered;
89mod de;
90mod error;
91mod ser;
92mod sink;
93
94use crate::de::MissingDe;
95use crate::sink::RootSink;
96
97/// Returns the value for a missing field like serde does.
98fn missing_value<'de, T: serde::Deserialize<'de>>() -> Option<T> {
99    T::deserialize(MissingDe).ok()
100}
101
102/// Adapter that uses the serde implementations of a type.
103///
104/// Compound values are buffered, see the [crate documentation](crate) for
105/// more information.
106///
107/// ```
108/// use std::collections::BTreeMap;
109/// use deser::adapters::As;
110/// use deser_serde::Serde;
111///
112/// let value: As<BTreeMap<u32, String>, Serde> =
113///     deser_json::from_str(r#"{"1": "a"}"#).unwrap();
114/// assert_eq!(value[&1], "a");
115/// assert_eq!(deser_json::to_string(&value).unwrap(), r#"{"1":"a"}"#);
116/// ```
117pub struct Serde;
118
119impl<T: serde::Serialize + ?Sized> Serialize<T> for Serde {
120    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, deser_core::Error> {
121        buffered::serialize(value, state)
122    }
123
124    fn is_optional(value: &T) -> bool {
125        ser::is_none(value)
126    }
127}
128
129impl<'de, T: serde::Deserialize<'de> + Send> Deserialize<'de, T> for Serde {
130    fn deserialize_into<'out>(
131        out: &'out mut Option<T>,
132        state: &mut State,
133    ) -> SinkHandle<'out, 'de> {
134        SinkHandle::arena(RootSink::new(out, buffered::Buffer::default()), state)
135    }
136
137    fn expecting() -> Cow<'static, str> {
138        Cow::Borrowed("serde value")
139    }
140
141    fn initial_value() -> Option<T> {
142        missing_value()
143    }
144}