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
|
use super::Value;
impl Value {
pub fn class_name(&self) -> Option<&String> {
if let Value::Object { class, .. } = self {
Some(class)
} else {
None
}
}
pub fn as_string(self) -> Option<String> {
if let Value::String(s) = self {
Some(s)
} else {
None
}
}
pub fn as_i64(&self) -> Option<i64> {
if let Value::I64(s) = self {
Some(*s)
} else {
None
}
}
pub fn as_i32(&self) -> Option<i32> {
if let Value::I32(s) = self {
Some(*s)
} else {
None
}
}
pub fn as_u32(&self) -> Option<u32> {
if let Value::U32(s) = self {
Some(*s)
} else {
None
}
}
pub fn as_u8(&self) -> Option<u8> {
if let Value::U8(s) = self {
Some(*s)
} else {
None
}
}
pub fn as_u64(&self) -> Option<u64> {
match self {
Self::U64(x) => Some(*x),
Self::U32(x) => Some(*x as u64),
_ => None,
}
}
pub fn as_f32(&self) -> Option<f32> {
if let Value::F32(s) = self {
Some(*s)
} else {
None
}
}
pub fn as_u16(&self) -> Option<u16> {
if let Value::U16(s) = self {
Some(*s)
} else {
None
}
}
pub fn as_bool(&self) -> Option<bool> {
if let Value::Bool(s) = self {
Some(*s)
} else {
None
}
}
pub fn as_array(self) -> Option<Vec<Value>> {
if let Value::Array(s) = self {
Some(s)
} else {
None
}
}
pub fn as_typeless(self) -> Option<Vec<u8>> {
if let Value::Typeless(s) = self {
Some(s)
} else {
None
}
}
pub fn to_json(self) -> serde_json::Value {
use serde_json::{Number, Value as V};
match self {
Value::Bool(x) => V::Bool(x),
Value::U8(x) => V::Number(x.into()),
Value::I8(x) => V::Number(x.into()),
Value::U16(x) => V::Number(x.into()),
Value::I16(x) => V::Number(x.into()),
Value::U32(x) => V::Number(x.into()),
Value::U64(x) => V::Number(x.into()),
Value::I32(x) => V::Number(x.into()),
Value::F32(x) => V::Number(Number::from_f64(x as f64).unwrap_or(0.into())),
Value::I64(x) => V::Number(x.into()),
Value::F64(x) => V::Number(Number::from_f64(x).unwrap()),
Value::String(x) => V::String(x),
Value::Typeless(values) => {
V::Array(values.into_iter().map(|e| V::Number(e.into())).collect())
}
Value::Array(values) => V::Array(values.into_iter().map(Value::to_json).collect()),
Value::Object { class, fields, .. } => V::Object(
fields
.into_iter()
.map(|(k, v)| (k, v.to_json()))
.chain(Some(("@class".to_string(), V::String(class))))
.collect(),
),
}
}
}
|