1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use Deserialize;
pub use *;
pub use serde_value;
/// A trait for selectively overwriting fields in a struct from a deserializer.
///
/// The `Overwrite` trait provides a mechanism to update existing values in a struct
/// by deserializing only the fields present in the input data, leaving other fields
/// unchanged. This is particularly useful for configuration merging, partial updates,
/// and layered settings where you want to apply defaults first and then override
/// specific values.
///
/// # Behavior
///
/// - For primitive types and most standard library types, `overwrite` completely
/// replaces the existing value with the deserialized value.
/// - For structs that derive `Overwrite` (using `#[derive(Overwrite)]`), only the
/// fields present in the input are updated, while absent fields retain their
/// current values.
///
/// # Examples
///
/// ```rust
/// use serde::Deserialize;
/// use serde_extensions::Overwrite;
///
/// #[derive(Deserialize, Overwrite)]
/// struct Config {
/// host: String,
/// port: u16,
/// debug: bool,
/// }
///
/// let mut config = Config {
/// host: "localhost".to_string(),
/// port: 8080,
/// debug: false,
/// };
///
/// // Overwrite only the port, leaving host and debug unchanged
/// let partial = r#"port=3000"#;
/// config.overwrite(toml::from_str::<toml::Value>(partial).unwrap()).unwrap();
///
/// assert_eq!(config.host, "localhost");
/// assert_eq!(config.port, 3000);
/// assert_eq!(config.debug, false);
/// ```
///
/// # Implementing for Custom Types
///
/// For structs, you can derive `Overwrite` automatically:
///
/// ```rust
/// use serde_extensions::Overwrite;
///
/// #[derive(Overwrite)]
/// struct MyStruct {
/// field1: String,
/// field2: i32,
/// }
/// ```
///
/// For other types, implement the trait manually. Types that should be completely
/// replaced (rather than merged) should deserialize a new value and assign it:
///
/// ```rust
/// use serde::{Deserialize, Deserializer};
/// use serde_extensions::Overwrite;
///
/// #[derive(Deserialize)]
/// struct CustomType(i32);
///
/// impl Overwrite for CustomType {
/// fn overwrite<'de, D>(&mut self, d: D) -> Result<(), D::Error>
/// where
/// D: Deserializer<'de>,
/// {
/// *self = CustomType::deserialize(d)?;
/// Ok(())
/// }
/// }
/// ```