1use std::borrow::Borrow;
3use std::collections::HashMap;
4
5#[derive(Clone, Debug, PartialEq)]
6pub enum Json {
7 Bool(bool),
8 I128(i128),
9 U128(u128),
10 String(String),
11 Array(Vec<Json>),
12 Object(HashMap<String, Json>),
13 Null,
14}
15
16pub struct Ref<'r> {
21 value: Option<&'r Json>,
22}
23
24impl<'r> Ref<'r> {
25 pub fn new(v: &'r Json) -> Ref<'r> {
26 Ref { value: Some(v) }
27 }
28
29 fn of(v: Option<&'r Json>) -> Ref<'r> {
30 Ref { value: v }
31 }
32
33 pub fn at(&self, i: usize) -> Ref<'r> {
34 match self.value {
35 Some(&Json::Array(ref a)) => Ref::of(a.get(i)),
36 _ => Ref::of(None),
37 }
38 }
39
40 pub fn get<K: Borrow<str>>(&self, k: K) -> Ref<'r> {
41 match self.value {
42 Some(&Json::Object(ref m)) => Ref::of(m.get(k.borrow())),
43 _ => Ref::of(None),
44 }
45 }
46
47 pub fn value(&self) -> Option<&Json> {
48 self.value
49 }
50
51 pub fn opt(&self) -> Option<Ref<'r>> {
52 match self.value {
53 Some(&Json::Null) => None,
54 Some(ref v) => Some(Ref::new(v)),
55 _ => None,
56 }
57 }
58
59 pub fn bool(&self) -> Option<bool> {
60 match self.value {
61 Some(&Json::Bool(x)) => Some(x),
62 _ => None,
63 }
64 }
65
66 pub fn string(&self) -> Option<&str> {
67 match self.value {
68 Some(&Json::String(ref x)) => Some(x),
69 _ => None,
70 }
71 }
72
73 pub fn i128(&self) -> Option<i128> {
74 match self.value {
75 Some(&Json::I128(x)) => Some(x),
76 _ => None,
77 }
78 }
79
80 pub fn u128(&self) -> Option<u128> {
81 match self.value {
82 Some(&Json::U128(x)) => Some(x),
83 _ => None,
84 }
85 }
86
87 pub fn slice(&self) -> Option<&[Json]> {
88 match self.value {
89 Some(&Json::Array(ref v)) => Some(v),
90 _ => None,
91 }
92 }
93}