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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use rkyv::{Archive, Deserialize, Serialize};
use std::{collections::HashMap, fmt, hash::Hash};

#[derive(Archive, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct JsonKey(String);

impl AsRef<str> for JsonKey {
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

#[derive(Archive, Debug, Deserialize, Serialize, PartialEq)]
#[archive(
    bound(
        serialize = "__S: rkyv::ser::ScratchSpace + rkyv::ser::SharedSerializeRegistry + rkyv::ser::Serializer",
        deserialize = "__D: rkyv::de::SharedDeserializeRegistry"
    ),
    check_bytes
)]
#[archive_attr(
    check_bytes(
        bound = "__C: rkyv::validation::ArchiveContext, <__C as rkyv::Fallible>::Error: rkyv::bytecheck::Error"
    ),
    derive(Debug)
)]
pub enum JsonValue {
    Null,
    Bool(bool),
    Number(JsonNumber),
    String(String),
    Array(
        #[omit_bounds]
        #[archive_attr(omit_bounds)]
        Vec<JsonValue>,
    ),
    Object(
        #[omit_bounds]
        #[archive_attr(omit_bounds)]
        HashMap<String, JsonValue>,
    ),
}

impl PartialEq<JsonValue> for ArchivedJsonValue {
    fn eq(&self, other: &JsonValue) -> bool {
        match self {
            ArchivedJsonValue::Null => other.is_null(),
            ArchivedJsonValue::Bool(v) => Some(*v) == other.as_bool(),
            ArchivedJsonValue::Number(v) => match v {
                ArchivedJsonNumber::Float(v) => Some(*v) == other.as_f64(),
                ArchivedJsonNumber::PosInt(v) => Some(*v) == other.as_u64(),
                ArchivedJsonNumber::NegInt(v) => Some(*v) == other.as_i64(),
            },
            ArchivedJsonValue::String(v) => match other {
                JsonValue::String(s) => s.as_str() == v.as_str(),
                _ => false,
            },
            ArchivedJsonValue::Array(v) => {
                if other.is_array() {
                    let other = other.as_array().unwrap();
                    let o = other.len();
                    let l = v.len();
                    if o != l {
                        return false;
                    }
                    for i in 0..l {
                        if !v[i].eq(&other[i]) {
                            return false;
                        }
                    }
                    return true;
                }
                false
            }
            ArchivedJsonValue::Object(v) => {
                if other.is_object() {
                    let other = other.as_object().unwrap();
                    let o = other.len();
                    let l = v.len();
                    if o != l {
                        return false;
                    }
                    for (key, value) in other.iter() {
                        if !v.contains_key(key.as_str()) {
                            return false;
                        }
                        if !v.get(key.as_str()).unwrap().eq(value) {
                            return false;
                        }
                    }
                    return true;
                }
                false
            }
        }
    }
}

impl JsonValue {
    pub fn map() -> Self {
        Self::Object(HashMap::default())
    }

    pub fn is_null(&self) -> bool {
        match self {
            JsonValue::Null => true,
            _ => false,
        }
    }

    pub fn is_object(&self) -> bool {
        match self {
            JsonValue::Object(_) => true,
            _ => false,
        }
    }

    pub fn as_object(&self) -> Option<&HashMap<String, JsonValue>> {
        match self {
            JsonValue::Object(v) => Some(v),
            _ => None,
        }
    }

    pub fn is_array(&self) -> bool {
        match self {
            JsonValue::Array(_) => true,
            _ => false,
        }
    }

    pub fn as_array(&self) -> Option<&[JsonValue]> {
        match self {
            JsonValue::Array(v) => Some(v),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            JsonValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    pub fn as_number(&self) -> Option<&JsonNumber> {
        match self {
            JsonValue::Number(n) => Some(n),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            JsonValue::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        match self {
            JsonValue::Number(n) => match n {
                JsonNumber::Float(v) => Some(*v),
                _ => None,
            },
            _ => None,
        }
    }

    pub fn as_i64(&self) -> Option<i64> {
        match self {
            JsonValue::Number(n) => match n {
                JsonNumber::NegInt(v) => Some(*v),
                _ => None,
            },
            _ => None,
        }
    }

    pub fn as_u64(&self) -> Option<u64> {
        match self {
            JsonValue::Number(n) => match n {
                JsonNumber::PosInt(v) => Some(*v),
                _ => None,
            },
            _ => None,
        }
    }

    pub fn as_object_mut(&mut self) -> Option<&mut HashMap<String, JsonValue>> {
        match self {
            JsonValue::Object(obj) => Some(obj),
            _ => None,
        }
    }
}

impl fmt::Display for ArchivedJsonValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => write!(f, "null")?,
            Self::Bool(b) => write!(f, "{}", b)?,
            Self::Number(n) => write!(f, "{}", n)?,
            Self::String(s) => write!(f, "{}", s)?,
            Self::Array(a) => {
                write!(f, "[")?;
                for (i, value) in a.iter().enumerate() {
                    write!(f, "{}", value)?;
                    if i < a.len() - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, "]")?;
            }
            Self::Object(h) => {
                write!(f, "{{")?;
                for (i, (key, value)) in h.iter().enumerate() {
                    write!(f, "\"{}\": {}", key, value)?;
                    if i < h.len() - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, "}}")?;
            }
        }
        Ok(())
    }
}

#[derive(Archive, Debug, Deserialize, Serialize, PartialEq, PartialOrd)]
#[archive(check_bytes)]
#[archive_attr(derive(Debug))]
pub enum JsonNumber {
    PosInt(u64),
    NegInt(i64),
    Float(f64),
}

impl JsonNumber {
    pub fn as_f64(&self) -> f64 {
        match self {
            Self::PosInt(n) => *n as f64,
            Self::NegInt(n) => *n as f64,
            Self::Float(n) => *n,
        }
    }
}

impl fmt::Display for ArchivedJsonNumber {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PosInt(n) => write!(f, "{}", n),
            Self::NegInt(n) => write!(f, "{}", n),
            Self::Float(n) => write!(f, "{}", n),
        }
    }
}

impl PartialEq<JsonNumber> for ArchivedJsonNumber {
    fn eq(&self, other: &JsonNumber) -> bool {
        match self {
            ArchivedJsonNumber::PosInt(v) => JsonNumber::PosInt(*v).eq(other),
            ArchivedJsonNumber::NegInt(v) => JsonNumber::NegInt(*v).eq(other),
            ArchivedJsonNumber::Float(v) => JsonNumber::Float(*v).eq(other),
        }
    }
}

impl PartialOrd<JsonNumber> for ArchivedJsonNumber {
    fn partial_cmp(&self, other: &JsonNumber) -> Option<std::cmp::Ordering> {
        match self {
            ArchivedJsonNumber::PosInt(v) => JsonNumber::PosInt(*v).partial_cmp(other),
            ArchivedJsonNumber::NegInt(v) => JsonNumber::NegInt(*v).partial_cmp(other),
            ArchivedJsonNumber::Float(v) => JsonNumber::Float(*v).partial_cmp(other),
        }
    }
}