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
|
use super::Value;
use anyhow::{Context, Result, anyhow, bail};
use std::collections::BTreeMap;
pub trait FromValue: Sized {
fn from_value(v: Value) -> Result<Self>;
}
impl Value {
pub fn parse<T: FromValue>(self) -> Result<T> {
T::from_value(self)
}
pub fn as_class(self, name: &'static str) -> Result<Fields> {
if let Value::Object { class, fields, .. } = self {
if class == name {
Ok(Fields {
class: name,
fields,
})
} else {
bail!("expected class {name} but found {class}")
}
} else {
bail!("expected class {name} but found something else")
}
}
}
pub struct Fields {
class: &'static str,
fields: BTreeMap<String, Value>,
}
impl Fields {
pub fn field<T: FromValue>(&mut self, name: &str) -> Result<T> {
self.fields
.remove(name)
.ok_or(anyhow!("expected {name} field in {}", self.class))?
.parse()
.context(anyhow!("in {}.{name} field", self.class))
}
pub fn remove(&mut self, key: &str) -> Option<Value> {
self.fields.remove(key)
}
}
impl FromValue for Value {
fn from_value(v: Value) -> Result<Self> {
Ok(v)
}
}
impl FromValue for u8 {
fn from_value(v: Value) -> anyhow::Result<Self> {
v.as_u8().ok_or(anyhow!("expected u8"))
}
}
impl FromValue for u16 {
fn from_value(v: Value) -> anyhow::Result<Self> {
v.as_u16().ok_or(anyhow!("expected u16"))
}
}
impl FromValue for f32 {
fn from_value(v: Value) -> anyhow::Result<Self> {
v.as_f32().ok_or(anyhow!("expected f32"))
}
}
impl FromValue for u32 {
fn from_value(v: Value) -> anyhow::Result<Self> {
v.as_u32().ok_or(anyhow!("expected u32"))
}
}
impl FromValue for i32 {
fn from_value(v: Value) -> anyhow::Result<Self> {
v.as_i32().ok_or(anyhow!("expected i32"))
}
}
impl FromValue for u64 {
fn from_value(v: Value) -> anyhow::Result<Self> {
v.as_u64().ok_or(anyhow!("expected u64"))
}
}
impl FromValue for bool {
fn from_value(v: Value) -> anyhow::Result<Self> {
v.as_bool().ok_or(anyhow!("expected bool"))
}
}
impl FromValue for String {
fn from_value(v: Value) -> anyhow::Result<Self> {
v.as_string().ok_or(anyhow!("expected string"))
}
}
impl Value {
pub fn as_vector(self) -> Option<Vec<Value>> {
self.as_class("vector").ok()?.remove("Array")?.as_array()
}
}
impl<K: FromValue + Ord, V: FromValue> FromValue for BTreeMap<K, V> {
fn from_value(v: Value) -> Result<Self> {
v.as_class("map")?
.remove("Array")
.ok_or(anyhow!("map is missing Array field"))?
.as_array()
.ok_or(anyhow!("map Array field is not an array"))?
.into_iter()
.map(|e| {
let mut fields = e.as_class("pair")?;
Ok((fields.field("first")?, fields.field("second")?))
})
.collect::<Result<BTreeMap<_, _>>>()
}
}
|