serde_deserialize_over/
lib.rs

1//! Traits and macros for deserializing data onto an existing instance of a
2//! struct via serde. It is somewhat like a more featureful version of adding
3//! `#[serde::default(...)]` annotations everywhere except that it is able to
4//! use runtime data instead of hardcoded defaults.
5//!
6//! # Usage
7//! The main trait for this crate is the [`DeserializeOver`] trait and its
8//! corresponding derive macro. It works analogously to serde's [`Deserialize`]
9//! trait except that struct fields that are not present within the data being
10//! deserialized keep their values as is.
11//!
12//! For a simple struct, this ends up looking something like this:
13//! ```
14//! use serde_deserialize_over::DeserializeOver;
15//! # use serde_json::Deserializer;
16//! # use serde_json::de::StrRead;
17//!
18//! #[derive(DeserializeOver)]
19//! struct MyStruct {
20//!     pub a: String,
21//!     pub b: i32
22//! }
23//!
24//! let json = r#"{ "a": "test" }"#;
25//! let mut inst = MyStruct {
26//!     a: "a string".to_owned(),
27//!     b: 32
28//! };
29//!
30//! let mut de = Deserializer::new(StrRead::new(json));
31//! inst.deserialize_over(&mut de)
32//!     .expect("Failed to deserialize JSON");
33//!
34//! assert_eq!(inst.a, "test");
35//! assert_eq!(inst.b, 32);
36//! ```
37//!
38//! Here, the serialized json only has a value for the `a` field so when it gets
39//! deserialized over the existing instance the `a` field is updated while the
40//! `b` field remains unchanged.
41//!
42//! # Nested Structs
43//! By default, the fields of the struct are deserialized using serde's
44//! [`Deserialize`]. This means that, by default, nested structs must be
45//! deserialized in entirety and cannot be deserialized on top of existing data.
46//! To mark that subfields should instead be deserialized via
47//! [`DeserializeOver`] the derive macro supports the `#[deserialize_over]`
48//! attribute.
49//!
50//! ```
51//! use serde_deserialize_over::DeserializeOver;
52//! # use serde_json::Deserializer;
53//! # use serde_json::de::StrRead;
54//!
55//! #[derive(DeserializeOver, Default)]
56//! struct Inner {
57//!     a: i32,
58//!     b: i32
59//! }
60//!
61//! #[derive(DeserializeOver, Default)]
62//! struct Outer {
63//!     #[deserialize_over]
64//!     inner: Inner,
65//!     c: i32
66//! }
67//!
68//! let json = r#"{ "inner": { "b": 5 } }"#;
69//! let mut inst = Outer::default();
70//!
71//! let mut de = Deserializer::new(StrRead::new(json));
72//! inst.deserialize_over(&mut de)
73//!     .expect("Failed to deserialize JSON");
74//!
75//! assert_eq!(inst.inner.a, 0);
76//! assert_eq!(inst.inner.b, 5);
77//! assert_eq!(inst.c, 0);
78//! ```
79//!
80//! # Extras
81//! This crate also provides the [`DeserializeInto`] extension trait on all
82//! serde [`Deserializer`]s which takes the operands in the other order.
83//!
84//! ```
85//! use serde_deserialize_over::{DeserializeOver, DeserializeInto};
86//! # use serde_json::Deserializer;
87//! # use serde_json::de::StrRead;
88//!
89//! #[derive(DeserializeOver, Default)]
90//! struct MyStruct {
91//!     pub a: String,
92//!     pub b: i32
93//! }
94//!
95//! let json = r#"{ "a": "test" }"#;
96//! let mut inst = MyStruct::default();
97//!
98//! let mut de = Deserializer::new(StrRead::new(json));
99//! de.deserialize_into(&mut inst)
100//!   .expect("Failed to deserialize JSON");
101//!
102//! assert_eq!(inst.a, "test");
103//! assert_eq!(inst.b, 0);
104//! ```
105//!
106//! [`Deserialize`]: serde::Deserialize
107//! [`Deserializer`]: serde::Deserializer
108
109mod support;
110mod tests;
111
112#[doc(hidden)]
113pub mod export {
114  pub use serde::de::{DeserializeSeed, Error, MapAccess, SeqAccess, Unexpected, Visitor};
115  pub use serde::{Deserialize, Deserializer};
116
117  pub use std::fmt;
118  pub use std::marker::PhantomData;
119  pub use std::option::Option::{None, Some};
120  pub use std::result::Result::{self, Err, Ok};
121
122  pub use crate::support::{DeserializeOverWrapper, DeserializeWrapper};
123  pub use crate::DeserializeOver;
124}
125
126pub use serde_deserialize_over_derive::DeserializeOver;
127
128use crate::support::DeserializeOverWrapper;
129use serde::Deserializer;
130
131/// Deserialize on top of an existing struct instance.
132///
133/// See the [crate-level documentation](crate) for usage details.
134pub trait DeserializeOver<'de> {
135  /// Deserialize from `de` on top of this struct instance.
136  fn deserialize_over<D>(&mut self, de: D) -> Result<(), D::Error>
137  where
138    D: Deserializer<'de>;
139}
140
141/// Helper trait to allow calling `deserialize_over` on the deserializer itself
142/// instead of on the object.
143///
144/// This trait has a blanket implementation on all deserializers is just meant
145/// to be a helper for a different call style.
146///
147/// # Example
148/// ```
149/// use serde_deserialize_over::{DeserializeOver, DeserializeInto};
150/// # use serde_json::Deserializer;
151/// # use serde_json::de::StrRead;
152///
153/// #[derive(DeserializeOver, Default)]
154/// struct MyStruct {
155///     pub a: String,
156///     pub b: i32
157/// }
158///
159/// let json = r#"{ "a": "test" }"#;
160/// let mut inst = MyStruct::default();
161///
162/// let mut de = Deserializer::new(StrRead::new(json));
163/// de.deserialize_into(&mut inst)
164///   .expect("Failed to deserialize JSON");
165///
166/// assert_eq!(inst.a, "test");
167/// assert_eq!(inst.b, 0);
168/// ```
169pub trait DeserializeInto<'de>: Deserializer<'de> {
170  /// Deserialize a `T` into `target`.
171  fn deserialize_into<T>(self, target: &mut T) -> Result<(), Self::Error>
172  where
173    T: DeserializeOver<'de>,
174  {
175    target.deserialize_over(self)
176  }
177}
178
179impl<'de, D> DeserializeInto<'de> for D where D: Deserializer<'de> {}