about summary refs log tree commit diff
path: root/src/json.rs
blob: 0ed2efab8df310c50330359cc22663f2d1e206e8 (plain)
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
use crate::error::{ Error, Result };

use std::collections::HashMap;
use std::str::FromStr;

use json_event_parser::{ JsonEvent, SliceJsonParser };


#[allow(unused)]
#[derive(Debug)]
pub enum Value {
  Object(Object),
  Array(Array),
  Integer(i64),
  Float(f64),
  String(String),
  Boolean(bool),
  Null,
}
pub type Object = HashMap<String, Value>;
pub type Array = Vec<Value>;


pub fn parse_json(json: &[u8]) -> Result<Value> {
  let mut parser = SliceJsonParser::new(json);

  if let Some(event) = parser.next() {
    match event? {
      JsonEvent::StartObject => {
        Ok(Value::Object(parse_json_object(&mut parser)?))
      }
      JsonEvent::StartArray => {
        Ok(Value::Array(parse_json_array(&mut parser)?))
      }
      JsonEvent::String(_) => {
        Err(Error::custom("JSON: unexpected string at top level"))
      }
      JsonEvent::Number(_) => {
        Err(Error::custom("JSON: unexpected number at top level"))
      }
      JsonEvent::Boolean(_) => {
        Err(Error::custom("JSON: unexpected Boolean at top level"))
      }
      JsonEvent::Null => {
        Err(Error::custom("JSON: unexpected null at top level"))
      }
      JsonEvent::ObjectKey(_) => {
        Err(Error::custom("JSON: unexpected key at top level"))
      }
      JsonEvent::EndObject => {
        Err(Error::custom("JSON: unexpected object end at top level"))
      }
      JsonEvent::EndArray => {
        Err(Error::custom("JSON: unexpected array end at top level"))
      }
    }
  } else {
    Err(Error::custom("JSON: unexpected end at top level"))
  }
}


fn parse_json_object(parser: &mut SliceJsonParser) -> Result<Object> {
  let mut object = HashMap::new();

  loop {
    if let Some(event) = parser.next() {
      match event? {
        JsonEvent::EndObject => {
          return Ok(object);
        }

        JsonEvent::ObjectKey(key) => {
          if object.contains_key(key.as_ref()) {
            return Err(Error::custom(&format!("JSON: duplicate key {}", key)));
          }

          let value = parse_json_value(parser)?;
          object.insert(key.into_owned(), value);
        }

        JsonEvent::StartObject => {
          return Err(Error::custom("JSON: unexpected object instead of key"));
        }
        JsonEvent::StartArray => {
          return Err(Error::custom("JSON: unexpected array instead of key"));
        }

        JsonEvent::String(_) => {
          return Err(Error::custom("JSON: unexpected string instead of key"));
        }
        JsonEvent::Number(_) => {
          return Err(Error::custom("JSON: unexpected number instead of key"));
        }
        JsonEvent::Boolean(_) => {
          return Err(Error::custom("JSON: unexpected Boolean instead of key"));
        }
        JsonEvent::Null => {
          return Err(Error::custom("JSON: unexpected null instead of key"));
        }

        JsonEvent::EndArray => {
          return Err(Error::custom("JSON: unexpected array end instead of key"));
        }
      }
    } else {
      return Err(Error::custom("JSON: unexpected end instead of key"));
    }
  }
}


fn parse_json_array(parser: &mut SliceJsonParser) -> Result<Array> {
  let mut array = Vec::new();

  loop {
    if let Some(event) = parser.next() {
      match event? {
        JsonEvent::EndArray => {
          return Ok(array);
        }

        JsonEvent::StartObject => {
          array.push(Value::Object(parse_json_object(parser)?));
        }
        JsonEvent::StartArray => {
          array.push(Value::Array(parse_json_array(parser)?));
        }
        other => {
          array.push(parse_json_atomic_value(other)?);
        }
      }
    } else {
      return Err(Error::custom("JSON: unexpected end instead of value"));
    }
  }
}


fn parse_json_value(parser: &mut SliceJsonParser) -> Result<Value> {
  if let Some(event) = parser.next() {
    match event? {
      JsonEvent::StartObject => {
        Ok(Value::Object(parse_json_object(parser)?))
      }
      JsonEvent::StartArray => {
        Ok(Value::Array(parse_json_array(parser)?))
      }
      other => parse_json_atomic_value(other),
    }
  } else {
    Err(Error::custom("JSON: unexpected end instead of value"))
  }
}


fn parse_json_atomic_value(event: JsonEvent) -> Result<Value> {
  match event {
    JsonEvent::String(string) => {
      Ok(Value::String(string.into_owned()))
    }
    JsonEvent::Number(token) => {
      parse_json_number(&token)
    }
    JsonEvent::Boolean(value) => {
      Ok(Value::Boolean(value))
    }
    JsonEvent::Null => {
      Ok(Value::Null)
    }

    JsonEvent::ObjectKey(_) => {
      Err(Error::custom("JSON: unexpected key instead of value"))
    }
    JsonEvent::EndObject => {
      Err(Error::custom("JSON: unexpected object end instead of value"))
    }
    JsonEvent::EndArray => {
      Err(Error::custom("JSON: unexpected array end instead of value"))
    }

    /*   These ones don't actually come up from how we're called, but it's
     * better to handle the cases exhaustively.
     */
    JsonEvent::StartObject => {
      Err(Error::custom(
          "JSON: unexpected object start instead of atomic value"))
    }
    JsonEvent::StartArray => {
      Err(Error::custom(
          "JSON: unexpected array start instead of atomic value"))
    }
  }
}


fn parse_json_number(token: &str) -> Result<Value> {
  if let Ok(number) = i64::from_str_radix(&token, 10) {
    Ok(Value::Integer(number))
  } else if let Ok(number) = f64::from_str(&token) {
    Ok(Value::Float(number))
  } else {
    /* JSON is highly permissive about numbers, but we aren't. */
    Err(Error::custom("JSON: unsupported number syntax"))
  }
}