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
#![macro_use]
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use thiserror::Error;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PropValue {
Number(i64),
String(String),
}
pub type Object = HashMap<String, PropValue>;
#[derive(Error, Debug)]
pub enum ConversionError {
#[error("field {0} is missing")]
FieldMissing(String),
#[error("field {0} can't be converted to {1}")]
FieldWrongType(String, String),
#[error("fixed field {0} should be {1:?}, is {2:?}")]
FixedFieldWrongValue(String, PropValue, PropValue),
}
pub trait ObjectShape:
std::convert::TryFrom<Object, Error = ConversionError> + std::convert::Into<Object>
{
}
#[macro_export]
macro_rules! object {
( $($key:expr => $value:expr $(,)?)* ) => {{
let mut object = Object::new();
$(object.insert($key.into(), $value.into());)*
object
}};
() => {
Object::new()
};
}
impl PropValue {
pub fn as_str(&self) -> Option<&String> {
match self {
PropValue::String(s) => Some(s),
_ => None,
}
}
pub fn as_number(&self) -> Option<i64> {
match self {
PropValue::Number(n) => Some(*n),
_ => None,
}
}
}
impl From<serde_json::Value> for PropValue {
fn from(x: serde_json::Value) -> Self {
match x {
serde_json::Value::String(s) => PropValue::String(s),
serde_json::Value::Number(n) => PropValue::Number(n.as_i64().unwrap()),
_ => {
panic!("attempt to create PropValue from serde_json::Value not a Number or String")
}
}
}
}
impl From<&serde_json::Value> for PropValue {
fn from(x: &serde_json::Value) -> Self {
PropValue::from(x.clone())
}
}
impl<'a> From<&'a str> for PropValue {
fn from(s: &str) -> Self {
PropValue::String(s.to_string())
}
}
impl From<String> for PropValue {
fn from(s: String) -> Self {
PropValue::String(s.clone())
}
}
impl From<&String> for PropValue {
fn from(s: &String) -> Self {
PropValue::String(s.clone())
}
}
impl From<i64> for PropValue {
fn from(s: i64) -> Self {
PropValue::Number(s.clone())
}
}