forked from vectordotdev/vector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserde.rs
More file actions
49 lines (42 loc) · 1.4 KB
/
Copy pathserde.rs
File metadata and controls
49 lines (42 loc) · 1.4 KB
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
use indexmap::map::IndexMap;
use serde::{Deserialize, Serialize};
pub fn default_true() -> bool {
true
}
pub fn default_false() -> bool {
false
}
pub fn to_string(value: impl serde::Serialize) -> String {
let value = serde_json::to_value(value).unwrap();
value.as_str().unwrap().into()
}
/// Answers "Is it possible to skip serializing this value, because it's the
/// default?"
pub(crate) fn skip_serializing_if_default<E: Default + PartialEq>(e: &E) -> bool {
e == &E::default()
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum FieldsOrValue<V> {
Fields(Fields<V>),
Value(V),
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Fields<V>(IndexMap<String, FieldsOrValue<V>>);
impl<V: 'static> Fields<V> {
pub fn all_fields(self) -> impl Iterator<Item = (String, V)> {
self.0
.into_iter()
.map(|(k, v)| -> Box<dyn Iterator<Item = (String, V)>> {
match v {
// boxing is used as a way to avoid incompatible types of the match arms
FieldsOrValue::Value(v) => Box::new(std::iter::once((k, v))),
FieldsOrValue::Fields(f) => Box::new(
f.all_fields()
.map(move |(nested_k, v)| (format!("{}.{}", k, nested_k), v)),
),
}
})
.flatten()
}
}