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
use locspan::Meta;
use crate::{object::Entry, Value};
pub enum SerdeJsonFragment<'a> {
Key(&'a str),
Value(&'a serde_json::Value),
}
impl<M> Value<M> {
pub fn from_serde_json(
value: serde_json::Value,
f: impl Clone + Fn(SerdeJsonFragment) -> M,
) -> Meta<Self, M> {
let meta = f(SerdeJsonFragment::Value(&value));
let v = match value {
serde_json::Value::Null => Self::Null,
serde_json::Value::Bool(b) => Self::Boolean(b),
serde_json::Value::Number(n) => Self::Number(n.into()),
serde_json::Value::String(s) => Self::String(s.into()),
serde_json::Value::Array(a) => Self::Array(
a.into_iter()
.map(|i| Self::from_serde_json(i, f.clone()))
.collect(),
),
serde_json::Value::Object(o) => Self::Object(
o.into_iter()
.map(|(k, v)| {
let k_meta = f(SerdeJsonFragment::Key(&k));
Entry::new(Meta(k.into(), k_meta), Self::from_serde_json(v, f.clone()))
})
.collect(),
),
};
Meta(v, meta)
}
pub fn into_serde_json(Meta(this, _): Meta<Self, M>) -> serde_json::Value {
this.into()
}
}
impl<M: Default> From<serde_json::Value> for Value<M> {
#[inline(always)]
fn from(value: serde_json::Value) -> Self {
Value::from_serde_json(value, |_| M::default()).into_value()
}
}
impl<M> From<Value<M>> for serde_json::Value {
fn from(value: Value<M>) -> Self {
match value {
Value::Null => Self::Null,
Value::Boolean(b) => Self::Bool(b),
Value::Number(n) => Self::Number(n.into()),
Value::String(s) => Self::String(s.into_string()),
Value::Array(a) => Self::Array(a.into_iter().map(Value::into_serde_json).collect()),
Value::Object(o) => Self::Object(
o.into_iter()
.map(
|Entry {
key: Meta(key, _),
value,
}| { (key.into_string(), Value::into_serde_json(value)) },
)
.collect(),
),
}
}
}