-
Notifications
You must be signed in to change notification settings - Fork 246
/
mod.rs
273 lines (234 loc) · 8.17 KB
/
mod.rs
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! Support for capturing other fields.
#![allow(unknown_lints, non_local_definitions)] // TODO: remove when proptest-derive updates
use alloc::collections::BTreeMap;
use core::{
fmt,
ops::{Deref, DerefMut},
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[cfg(any(test, feature = "arbitrary"))]
mod arbitrary_;
/// Generic type for capturing additional fields when deserializing structs.
///
/// For example, the [optimism `eth_getTransactionByHash` request][optimism] returns additional
/// fields that this type will capture instead.
///
/// Use `deserialize_as` or `deserialize_into` with a struct that captures the unknown fields, or
/// deserialize the individual fields manually with `get_deserialized`.
///
/// This type must be used with [`#[serde(flatten)]`][flatten].
///
/// [optimism]: https://docs.alchemy.com/alchemy/apis/optimism/eth-gettransactionbyhash
/// [flatten]: https://serde.rs/field-attrs.html#flatten
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct OtherFields {
inner: BTreeMap<String, serde_json::Value>,
}
impl OtherFields {
/// Creates a new [`OtherFields`] instance.
pub const fn new(inner: BTreeMap<String, serde_json::Value>) -> Self {
Self { inner }
}
/// Deserialized this type into another container type.
pub fn deserialize_as<T: DeserializeOwned>(&self) -> serde_json::Result<T> {
let map = self.inner.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
serde_json::from_value(serde_json::Value::Object(map))
}
/// Deserialized this type into another container type.
pub fn deserialize_into<T: DeserializeOwned>(self) -> serde_json::Result<T> {
let map = self.inner.into_iter().collect();
serde_json::from_value(serde_json::Value::Object(map))
}
/// Returns the deserialized value of the field, if it exists.
/// Deserializes the value with the given closure
pub fn get_with<F, V>(&self, key: impl AsRef<str>, with: F) -> Option<V>
where
F: FnOnce(serde_json::Value) -> V,
{
self.inner.get(key.as_ref()).cloned().map(with)
}
/// Returns the deserialized value of the field, if it exists
pub fn get_deserialized<V: DeserializeOwned>(
&self,
key: impl AsRef<str>,
) -> Option<serde_json::Result<V>> {
self.get_with(key, serde_json::from_value)
}
/// Removes the deserialized value of the field, if it exists
///
/// **Note:** this will also remove the value if deserializing it resulted in an error
pub fn remove_deserialized<V: DeserializeOwned>(
&mut self,
key: impl AsRef<str>,
) -> Option<serde_json::Result<V>> {
self.inner.remove(key.as_ref()).map(serde_json::from_value)
}
/// Removes the deserialized value of the field, if it exists.
/// Deserializes the value with the given closure
///
/// **Note:** this will also remove the value if deserializing it resulted in an error
pub fn remove_with<F, V>(&mut self, key: impl AsRef<str>, with: F) -> Option<V>
where
F: FnOnce(serde_json::Value) -> V,
{
self.inner.remove(key.as_ref()).map(with)
}
/// Removes the deserialized value of the field, if it exists and also returns the key
///
/// **Note:** this will also remove the value if deserializing it resulted in an error
pub fn remove_entry_deserialized<V: DeserializeOwned>(
&mut self,
key: impl AsRef<str>,
) -> Option<(String, serde_json::Result<V>)> {
self.inner
.remove_entry(key.as_ref())
.map(|(key, value)| (key, serde_json::from_value(value)))
}
}
impl fmt::Debug for OtherFields {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("OtherFields ")?;
self.inner.fmt(f)
}
}
impl TryFrom<serde_json::Value> for OtherFields {
type Error = serde_json::Error;
fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
serde_json::from_value(value).map(Self::new)
}
}
impl<K> FromIterator<(K, serde_json::Value)> for OtherFields
where
K: Into<String>,
{
fn from_iter<T: IntoIterator<Item = (K, serde_json::Value)>>(iter: T) -> Self {
Self { inner: iter.into_iter().map(|(key, value)| (key.into(), value)).collect() }
}
}
impl Deref for OtherFields {
type Target = BTreeMap<String, serde_json::Value>;
#[inline]
fn deref(&self) -> &BTreeMap<String, serde_json::Value> {
self.as_ref()
}
}
impl DerefMut for OtherFields {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl AsRef<BTreeMap<String, serde_json::Value>> for OtherFields {
fn as_ref(&self) -> &BTreeMap<String, serde_json::Value> {
&self.inner
}
}
impl IntoIterator for OtherFields {
type Item = (String, serde_json::Value);
type IntoIter = alloc::collections::btree_map::IntoIter<String, serde_json::Value>;
fn into_iter(self) -> Self::IntoIter {
self.inner.into_iter()
}
}
impl<'a> IntoIterator for &'a OtherFields {
type Item = (&'a String, &'a serde_json::Value);
type IntoIter = alloc::collections::btree_map::Iter<'a, String, serde_json::Value>;
fn into_iter(self) -> Self::IntoIter {
self.as_ref().iter()
}
}
/// An extension to a struct that allows to capture additional fields when deserializing.
///
/// See [`OtherFields`] for more information.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
#[cfg_attr(
any(test, feature = "arbitrary"),
derive(proptest_derive::Arbitrary, arbitrary::Arbitrary)
)]
pub struct WithOtherFields<T> {
/// The inner struct.
#[serde(flatten)]
pub inner: T,
/// All fields not present in the inner struct.
#[serde(flatten)]
pub other: OtherFields,
}
impl<T> WithOtherFields<T> {
/// Creates a new [`WithOtherFields`] instance.
pub fn new(inner: T) -> Self {
Self { inner, other: Default::default() }
}
}
impl<T> Deref for WithOtherFields<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> DerefMut for WithOtherFields<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl<'de, T> Deserialize<'de> for WithOtherFields<T>
where
T: Deserialize<'de> + Serialize,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct WithOtherFieldsHelper<T> {
#[serde(flatten)]
inner: T,
#[serde(flatten)]
other: OtherFields,
}
let mut helper = WithOtherFieldsHelper::deserialize(deserializer)?;
// remove all fields present in the inner struct from the other fields, this is to avoid
// duplicate fields in the catch all other fields because serde flatten does not exclude
// already deserialized fields when deserializing the other fields.
if let Value::Object(map) =
serde_json::to_value(&helper.inner).map_err(serde::de::Error::custom)?
{
for key in map.keys() {
helper.other.remove(key);
}
}
Ok(Self { inner: helper.inner, other: helper.other })
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::Rng;
#[test]
fn other_fields_arbitrary() {
let mut bytes = [0u8; 1024];
rand::thread_rng().fill(bytes.as_mut_slice());
let _ = arbitrary::Unstructured::new(&bytes).arbitrary::<OtherFields>().unwrap();
}
#[test]
fn test_correct_other() {
#[derive(Serialize, Deserialize)]
struct Inner {
a: u64,
}
#[derive(Serialize, Deserialize)]
struct InnerWrapper {
#[serde(flatten)]
inner: Inner,
}
let with_other: WithOtherFields<InnerWrapper> =
serde_json::from_str("{\"a\": 1, \"b\": 2}").unwrap();
assert_eq!(with_other.inner.inner.a, 1);
assert_eq!(
with_other.other,
OtherFields::new(BTreeMap::from_iter([("b".to_string(), serde_json::json!(2))]))
);
}
}