json/
ast.rs

1//! JSON AST definition.
2use std::borrow::Borrow;
3use std::collections::HashMap;
4
5#[derive(Clone, Debug, PartialEq)]
6pub enum Json {
7    Bool(bool),
8    Number(f64),
9    String(String),
10    Array(Vec<Json>),
11    Object(HashMap<String, Json>),
12    Null
13}
14
15/// A reference to some `Json` value.
16///
17/// Mostly used for navigating complex `Json` values
18/// and extracting values from specific locations.
19pub struct Ref<'r> {
20    value: Option<&'r Json>
21}
22
23impl<'r> Ref<'r> {
24    pub fn new(v: &'r Json) -> Ref<'r> {
25        Ref { value: Some(v) }
26    }
27
28    fn of(v: Option<&'r Json>) -> Ref<'r> {
29        Ref { value: v }
30    }
31
32    pub fn at(&self, i: usize) -> Ref<'r> {
33        match self.value {
34            Some(&Json::Array(ref a)) => Ref::of(a.get(i)),
35            _                         => Ref::of(None)
36        }
37    }
38
39    pub fn get<K: Borrow<str>>(&self, k: K) -> Ref<'r> {
40        match self.value {
41            Some(&Json::Object(ref m)) => Ref::of(m.get(k.borrow())),
42            _                          => Ref::of(None)
43        }
44    }
45
46    pub fn value(&self) -> Option<&Json> {
47        self.value
48    }
49
50    pub fn opt(&self) -> Option<Ref<'r>> {
51        match self.value {
52            Some(&Json::Null) => None,
53            Some(ref v)       => Some(Ref::new(v)),
54            _                 => None
55        }
56    }
57
58    pub fn bool(&self) -> Option<bool> {
59        match self.value {
60            Some(&Json::Bool(x)) => Some(x),
61            _                    => None
62        }
63    }
64
65    pub fn string(&self) -> Option<&str> {
66        match self.value {
67            Some(&Json::String(ref x)) => Some(x),
68            _                          => None
69        }
70    }
71
72    pub fn number(&self) -> Option<f64> {
73        match self.value {
74            Some(&Json::Number(x)) => Some(x),
75            _                      => None
76        }
77    }
78
79    pub fn slice(&self) -> Option<&[Json]> {
80        match self.value {
81            Some(&Json::Array(ref v)) => Some(v),
82            _                         => None
83        }
84    }
85}