2020-02-07 20:01:10 -05:00
|
|
|
//! # Naive JSON Parser
|
2020-02-07 21:27:46 -05:00
|
|
|
//!
|
|
|
|
//! Based on [JSON Parser with JavaScript](https://lihautan.com/json-parser-with-javascript/)
|
|
|
|
#![forbid(unsafe_code)]
|
2020-02-07 16:23:51 -05:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::iter::FromIterator;
|
2020-02-07 22:55:09 -05:00
|
|
|
use std::{char, u16};
|
2020-02-07 16:23:51 -05:00
|
|
|
|
2020-02-11 16:18:37 -05:00
|
|
|
pub type JSONResult = Result<JSONValue, ParseError>;
|
2020-02-11 19:12:01 -05:00
|
|
|
pub type JSONArray = Vec<JSONValue>;
|
2020-02-11 16:18:37 -05:00
|
|
|
pub type JSONMap = HashMap<String, JSONValue>;
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// The type of JSON value
|
2020-02-11 16:18:37 -05:00
|
|
|
#[derive(Clone, Debug, PartialEq)]
|
2020-02-07 16:23:51 -05:00
|
|
|
pub enum JSONValue {
|
2020-02-07 21:27:46 -05:00
|
|
|
/// Object Literal
|
2020-02-07 16:23:51 -05:00
|
|
|
Object(HashMap<String, JSONValue>),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// Array Literal
|
2020-02-07 16:23:51 -05:00
|
|
|
Array(Vec<JSONValue>),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// String Literal
|
2020-02-07 16:23:51 -05:00
|
|
|
String(String),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// Number Literal
|
2020-02-07 16:23:51 -05:00
|
|
|
Number(f64),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// True Literal
|
2020-02-07 16:23:51 -05:00
|
|
|
True,
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// False Literal
|
2020-02-07 16:23:51 -05:00
|
|
|
False,
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// Null Literal
|
2020-02-07 16:23:51 -05:00
|
|
|
Null,
|
|
|
|
}
|
|
|
|
|
2020-02-11 19:12:01 -05:00
|
|
|
impl JSONValue {
|
|
|
|
/// Convert the wrapped JSONValue to its simpler rust value
|
|
|
|
///
|
|
|
|
/// Example:
|
|
|
|
/// ```
|
|
|
|
/// use naive_json_parser::JSONValue;
|
|
|
|
///
|
|
|
|
/// let str = "Four score and seven years ago...";
|
|
|
|
/// let wrapped = JSONValue::from(str);
|
|
|
|
///
|
|
|
|
/// // s is now the `String` that was in the `JSONValue` enum
|
|
|
|
/// let s: String = wrapped.unwrap();
|
|
|
|
///
|
|
|
|
/// # assert_eq!(str, &s);
|
|
|
|
/// ```
|
|
|
|
pub fn unwrap<T: From<JSONValue>>(self) -> T {
|
|
|
|
T::from(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONValue> for JSONMap {
|
|
|
|
/// Extracts the `HashMap` in the `JSONValue` enum, if it exists.
|
|
|
|
/// Otherwise, panics.
|
|
|
|
fn from(val: JSONValue) -> JSONMap {
|
|
|
|
match val {
|
|
|
|
JSONValue::Object(o) => o,
|
|
|
|
_ => panic!("Invalid type conversion")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONValue> for JSONArray{
|
|
|
|
/// Extracts the `Vec` in the `JSONValue` enum, if it exists.
|
|
|
|
/// Otherwise, panics.
|
|
|
|
fn from(val: JSONValue) -> JSONArray {
|
|
|
|
match val {
|
|
|
|
JSONValue::Array(a) => a,
|
|
|
|
_ => panic!("Invalid type conversion")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONValue> for f64 {
|
|
|
|
/// Extracts the `f64` in the `JSONValue` enum, if it exists.
|
|
|
|
/// Otherwise, panics.
|
|
|
|
fn from(val: JSONValue) -> f64 {
|
|
|
|
match val {
|
|
|
|
JSONValue::Number(n) => n,
|
|
|
|
_ => panic!("Invalid type conversion")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONValue> for String {
|
|
|
|
/// Extracts the `String` in the `JSONValue` enum, if it exists.
|
|
|
|
/// Otherwise, panics.
|
|
|
|
fn from(val: JSONValue) -> String {
|
|
|
|
match val {
|
|
|
|
JSONValue::String(s) => s,
|
|
|
|
_ => panic!("Invalid type conversion")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONValue> for bool {
|
|
|
|
/// Extracts the `bool` value from the `JSONValue` enum, if it exists.
|
|
|
|
/// Otherwise, panics.
|
|
|
|
fn from(val: JSONValue) -> bool {
|
|
|
|
match val {
|
|
|
|
JSONValue::True => true,
|
|
|
|
JSONValue::False => false,
|
|
|
|
_ => panic!("Invalid type conversion")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONValue> for () {
|
|
|
|
/// This will just swallow the enum value and return a unit tuple
|
|
|
|
fn from(_: JSONValue) -> () { () }
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONMap> for JSONValue {
|
|
|
|
/// Wraps the `HashMap` in the `JSONValue` enum
|
|
|
|
fn from(val: JSONMap) -> JSONValue {
|
|
|
|
Self::Object(val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONArray> for JSONValue {
|
|
|
|
/// Wraps the `Vec` in the `JSONValue` enum
|
|
|
|
fn from(val: JSONArray) -> JSONValue {
|
|
|
|
Self::Array(val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<bool> for JSONValue {
|
|
|
|
/// Sets the `JSONValue` enum to the `True` or `False` value
|
|
|
|
fn from(val: bool) -> Self {
|
|
|
|
match val {
|
|
|
|
true => Self::True,
|
|
|
|
false => Self::False,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<f64> for JSONValue {
|
|
|
|
/// Wraps the `f64` in the `JSONValue` enum
|
|
|
|
fn from(n: f64) -> Self {
|
|
|
|
Self::Number(n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<()> for JSONValue {
|
|
|
|
/// Sets the `JSONValue` enum to the `Null` value
|
|
|
|
fn from(_s: ()) -> Self {
|
|
|
|
Self::Null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<String> for JSONValue {
|
|
|
|
/// Wraps the `String` in the `JSONValue` enum
|
|
|
|
fn from(s: String) -> Self {
|
|
|
|
Self::String(s)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<&str> for JSONValue {
|
|
|
|
/// Creates a `String` and wraps it in the `JSONValue` enum
|
|
|
|
fn from(s: &str) -> Self {
|
|
|
|
Self::String(String::from(s))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// The type of error returned by the parser
|
2020-02-07 20:01:10 -05:00
|
|
|
#[derive(Debug, PartialEq)]
|
2020-02-07 16:23:51 -05:00
|
|
|
pub enum ParseError {
|
2020-02-07 21:27:46 -05:00
|
|
|
/// The input looks like JSON, but seems to end
|
2020-02-07 16:23:51 -05:00
|
|
|
UnexpectedEndOfInput(String),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// Looks like JSON, but seems to have characters after it should
|
2020-02-07 16:23:51 -05:00
|
|
|
ExpectedEndOfInput(String),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// Wasn't this supposed to be an object literal?
|
2020-02-07 16:23:51 -05:00
|
|
|
ExpectedObjectKey(String),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// Hey, wasn't there supposed to be...?
|
2020-02-07 16:23:51 -05:00
|
|
|
ExpectedToken(String),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// What's this character?
|
2020-02-07 16:23:51 -05:00
|
|
|
UnexpectedToken(String),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// Shouldn't this be a numeral?
|
2020-02-07 16:23:51 -05:00
|
|
|
ExpectedDigit(String),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// There's a backslash...were you going somewhere with that?
|
2020-02-07 16:23:51 -05:00
|
|
|
ExpectedEscapeChar(String),
|
2020-02-07 21:27:46 -05:00
|
|
|
|
|
|
|
/// Should be a unicode escape character...missing a few digits?
|
2020-02-07 16:23:51 -05:00
|
|
|
ExpectedUnicodeEscape(String),
|
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// This struct holds a little state for parsing
|
2020-02-07 20:01:10 -05:00
|
|
|
#[derive(Debug, PartialEq)]
|
2020-02-07 16:23:51 -05:00
|
|
|
pub struct JSON {
|
2020-02-07 21:27:46 -05:00
|
|
|
/// The input JSON String as a character array
|
2020-02-07 16:23:51 -05:00
|
|
|
chars: Vec<char>,
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// The internal parsing index
|
|
|
|
i: usize,
|
|
|
|
}
|
2020-02-07 16:23:51 -05:00
|
|
|
|
2020-02-11 14:06:08 -05:00
|
|
|
/// Cut down the if boilerplate
|
|
|
|
///
|
|
|
|
/// Thanks to `uwaterloodudette` on reddit
|
|
|
|
macro_rules! try_parse {
|
|
|
|
($( $e:expr ),* ) => {
|
|
|
|
$(
|
|
|
|
if let Some(v) = $e? {
|
|
|
|
return Ok(v);
|
|
|
|
}
|
|
|
|
)*
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-02-07 16:23:51 -05:00
|
|
|
impl JSON {
|
2020-02-07 21:27:46 -05:00
|
|
|
/// Private constructor
|
2020-02-07 16:23:51 -05:00
|
|
|
fn new(json: &str) -> Self {
|
2020-02-07 21:27:46 -05:00
|
|
|
JSON {
|
|
|
|
chars: json.chars().collect(),
|
|
|
|
i: 0,
|
|
|
|
}
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// Parse a `JSONValue` from the current JSON string
|
2020-02-11 16:18:37 -05:00
|
|
|
fn parse_value(&mut self) -> JSONResult {
|
2020-02-07 16:23:51 -05:00
|
|
|
self.skip_whitespace();
|
|
|
|
|
2020-02-11 14:06:08 -05:00
|
|
|
// Go through the parser methods, until you find
|
|
|
|
// one that doesn't return a `None`
|
|
|
|
try_parse!(
|
|
|
|
self.parse_string(),
|
|
|
|
self.parse_number(),
|
|
|
|
self.parse_object(),
|
|
|
|
self.parse_array(),
|
|
|
|
self.parse_keyword("true", JSONValue::True),
|
|
|
|
self.parse_keyword("false", JSONValue::False),
|
|
|
|
self.parse_keyword("null", JSONValue::Null)
|
|
|
|
);
|
|
|
|
|
|
|
|
// Every parser failed, so the syntax is probably incorrect
|
2020-02-11 19:12:01 -05:00
|
|
|
Err(ParseError::UnexpectedEndOfInput(format!("Doesn't seem to be valid JSON")))
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// See if there's a `JSONValue::Object` next in the JSON
|
|
|
|
fn parse_object(&mut self) -> Result<Option<JSONValue>, ParseError> {
|
2020-02-07 16:23:51 -05:00
|
|
|
if self.chars[self.i] != '{' {
|
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 16:23:51 -05:00
|
|
|
|
|
|
|
self.skip_whitespace();
|
|
|
|
|
2020-02-11 16:18:37 -05:00
|
|
|
let mut result: JSONMap = HashMap::new();
|
2020-02-07 16:23:51 -05:00
|
|
|
|
|
|
|
let mut initial = true;
|
|
|
|
|
|
|
|
// if it is not '}',
|
|
|
|
// we take the path of string -> whitespace -> ':' -> value -> ...
|
|
|
|
while self.chars[self.i] != '}' {
|
2020-02-10 15:16:46 -05:00
|
|
|
self.skip_whitespace();
|
|
|
|
|
2020-02-07 16:23:51 -05:00
|
|
|
if initial == false {
|
2020-02-07 20:01:10 -05:00
|
|
|
self.eat(',')?;
|
2020-02-07 16:23:51 -05:00
|
|
|
self.skip_whitespace();
|
|
|
|
}
|
|
|
|
|
2020-02-10 15:16:46 -05:00
|
|
|
self.skip_whitespace();
|
|
|
|
|
2020-02-07 16:23:51 -05:00
|
|
|
let key = match self.parse_string()? {
|
|
|
|
Some(value) => match value {
|
|
|
|
JSONValue::String(s) => s,
|
|
|
|
_ => panic!("parse_string returned non-string value"),
|
|
|
|
},
|
2020-02-11 14:06:08 -05:00
|
|
|
None => String::new(),
|
2020-02-07 16:23:51 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
self.skip_whitespace();
|
2020-02-07 20:01:10 -05:00
|
|
|
self.eat(':')?;
|
2020-02-07 16:23:51 -05:00
|
|
|
let value = self.parse_value()?;
|
|
|
|
|
|
|
|
result.insert(key, value);
|
|
|
|
|
|
|
|
initial = false;
|
2020-02-10 15:34:10 -05:00
|
|
|
|
|
|
|
self.skip_whitespace();
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Move to the next character: '}'
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 16:23:51 -05:00
|
|
|
|
2020-02-12 09:12:00 -05:00
|
|
|
Ok(Some(JSONValue::from(result)))
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// See if there's a `JSONValue::Array` next in the JSON
|
|
|
|
fn parse_array(&mut self) -> Result<Option<JSONValue>, ParseError> {
|
2020-02-07 16:23:51 -05:00
|
|
|
if self.chars[self.i] != '[' {
|
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 16:23:51 -05:00
|
|
|
self.skip_whitespace();
|
|
|
|
|
|
|
|
let mut result: Vec<JSONValue> = vec![];
|
|
|
|
let mut initial = true;
|
|
|
|
|
|
|
|
while self.chars[self.i] != ']' {
|
2020-02-10 15:16:46 -05:00
|
|
|
self.skip_whitespace();
|
|
|
|
|
2020-02-07 16:23:51 -05:00
|
|
|
if initial == false {
|
2020-02-07 20:01:10 -05:00
|
|
|
self.eat(',')?;
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
let value = self.parse_value()?;
|
|
|
|
result.push(value);
|
|
|
|
initial = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// move to next character: ']'
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 16:23:51 -05:00
|
|
|
|
2020-02-12 09:12:00 -05:00
|
|
|
Ok(Some(JSONValue::from(result)))
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// See if there's a `JSONValue::String` next in the JSON
|
|
|
|
fn parse_string(&mut self) -> Result<Option<JSONValue>, ParseError> {
|
|
|
|
if self.chars[self.i] != '"' {
|
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 21:27:46 -05:00
|
|
|
let mut result = String::new();
|
|
|
|
|
2020-02-10 12:26:54 -05:00
|
|
|
while self.chars[self.i] != '"' && self.i < self.chars.len() - 1 {
|
2020-02-07 22:55:09 -05:00
|
|
|
// All the escape sequences...
|
2020-02-07 21:29:41 -05:00
|
|
|
if self.chars[self.i] == '\\' {
|
2020-02-07 22:55:09 -05:00
|
|
|
let ch = self.chars[self.i + 1];
|
2020-02-11 16:18:37 -05:00
|
|
|
if ch == '"' {
|
|
|
|
result.push_str("\"");
|
|
|
|
self.increment(1);
|
|
|
|
} else if ['\\', '/'].contains(&ch) {
|
2020-02-07 22:55:09 -05:00
|
|
|
let escaped = ch.escape_default().next().unwrap_or(ch);
|
|
|
|
|
|
|
|
result.push(escaped);
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 22:55:09 -05:00
|
|
|
} else if ['b', 'f', 'n', 'r', 't'].contains(&ch) {
|
|
|
|
let ch = match ch {
|
|
|
|
'b' => '\u{8}',
|
|
|
|
'f' => '\x0C',
|
|
|
|
'n' => '\n',
|
|
|
|
'r' => '\r',
|
|
|
|
't' => '\t',
|
|
|
|
_ => panic!("Shouldn't be possible!"),
|
|
|
|
};
|
|
|
|
result.push(ch);
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 22:55:09 -05:00
|
|
|
} else if ch == 'u'
|
|
|
|
&& self.chars[self.i + 2].is_ascii_hexdigit()
|
|
|
|
&& self.chars[self.i + 3].is_ascii_hexdigit()
|
|
|
|
&& self.chars[self.i + 4].is_ascii_hexdigit()
|
|
|
|
&& self.chars[self.i + 5].is_ascii_hexdigit()
|
|
|
|
{
|
|
|
|
// Blech, parse out a JSON unicode (utf16) escape code. Handles surrogate pairs
|
|
|
|
// by giving you the replacement character...because...yeah
|
|
|
|
let char_str = String::from_iter(&self.chars[self.i + 2..=self.i + 5]);
|
|
|
|
let code = u16::from_str_radix(&char_str, 16)
|
|
|
|
.expect("Failed to parse unicode escape number");
|
|
|
|
let string = String::from_utf16_lossy(&[code]);
|
|
|
|
|
|
|
|
result.push_str(&string);
|
|
|
|
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(5);
|
2020-02-07 22:55:09 -05:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
result.push(self.chars[self.i]);
|
2020-02-07 21:27:46 -05:00
|
|
|
}
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 21:27:46 -05:00
|
|
|
}
|
|
|
|
|
2020-02-10 15:16:46 -05:00
|
|
|
self.eat('"')?;
|
2020-02-07 22:55:09 -05:00
|
|
|
|
2020-02-12 09:12:00 -05:00
|
|
|
Ok(Some(JSONValue::from(result)))
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// See if there's a `JSONValue::Number` next in the JSON
|
|
|
|
fn parse_number(&mut self) -> Result<Option<JSONValue>, ParseError> {
|
2020-02-10 15:16:46 -05:00
|
|
|
let start = self.i;
|
|
|
|
|
2020-02-10 12:26:54 -05:00
|
|
|
// If it doesn't start with 0-9 or a minus sign, it's probably not a number
|
2020-02-11 10:57:48 -05:00
|
|
|
if !(self.chars[start].is_ascii_digit() || self.chars[start] == '-') {
|
2020-02-10 12:26:54 -05:00
|
|
|
return Ok(None);
|
|
|
|
}
|
2020-02-07 23:51:49 -05:00
|
|
|
|
|
|
|
// All this looping basically just counts the number of characters in the number
|
|
|
|
let max = self.chars.len() - 1;
|
|
|
|
let mut n = start;
|
|
|
|
|
2020-02-10 14:59:28 -05:00
|
|
|
// Minus sign
|
2020-02-07 23:51:49 -05:00
|
|
|
if self.chars[n] == '-' && n < max {
|
|
|
|
n += 1;
|
|
|
|
}
|
|
|
|
|
2020-02-10 14:59:28 -05:00
|
|
|
// Integer Part
|
|
|
|
while self.chars[n].is_ascii_digit() && n < max {
|
2020-02-07 23:51:49 -05:00
|
|
|
n += 1;
|
|
|
|
}
|
|
|
|
|
2020-02-10 14:59:28 -05:00
|
|
|
// Decimal Part
|
2020-02-07 23:51:49 -05:00
|
|
|
if self.chars[n] == '.' && n < max {
|
|
|
|
n += 1;
|
2020-02-10 14:59:28 -05:00
|
|
|
while self.chars[n].is_ascii_digit() && n < max {
|
|
|
|
n += 1;
|
2020-02-07 23:51:49 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-10 14:59:28 -05:00
|
|
|
// Scientific notation part
|
2020-02-07 23:51:49 -05:00
|
|
|
if self.chars[n] == 'e' || self.chars[n] == 'E' && n < max {
|
|
|
|
n += 1;
|
|
|
|
|
|
|
|
if self.chars[n] == '-' || self.chars[n] == '+' && n < max {
|
|
|
|
n += 1;
|
|
|
|
}
|
2020-02-10 15:16:46 -05:00
|
|
|
|
|
|
|
// Exponent base
|
2020-02-10 14:59:28 -05:00
|
|
|
while self.chars[n].is_ascii_digit() && n < max {
|
|
|
|
n += 1;
|
2020-02-07 23:51:49 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-10 14:10:48 -05:00
|
|
|
// If there are numeric digits attempt to parse the digits as a number
|
2020-02-07 23:51:49 -05:00
|
|
|
if n > start {
|
2020-02-11 10:57:48 -05:00
|
|
|
let mut end = if n < self.chars.len() { n } else { max };
|
2020-02-07 23:51:49 -05:00
|
|
|
|
2020-02-10 14:59:28 -05:00
|
|
|
// Hack to remove non-number characters
|
|
|
|
if !self.chars[end].is_ascii_digit() {
|
|
|
|
end -= 1;
|
|
|
|
}
|
|
|
|
|
2020-02-07 23:51:49 -05:00
|
|
|
let str = String::from_iter(&self.chars[start..=end]);
|
|
|
|
|
|
|
|
match str.parse::<f64>() {
|
2020-02-10 14:59:28 -05:00
|
|
|
Ok(number) => {
|
|
|
|
self.increment(str.len());
|
2020-02-11 19:12:01 -05:00
|
|
|
return Ok(Some(JSONValue::from(number)));
|
2020-02-11 10:57:48 -05:00
|
|
|
}
|
2020-02-10 14:10:48 -05:00
|
|
|
Err(e) => Err(ParseError::ExpectedDigit(format!("'{}', {:#?}", str, e))),
|
2020-02-07 23:51:49 -05:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Ok(None)
|
|
|
|
}
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// See if there's a `JSONValue::True`, `JSONValue::False`, or a `JSONValue::Null` next in the JSON
|
|
|
|
fn parse_keyword(
|
|
|
|
&mut self,
|
|
|
|
search: &str,
|
|
|
|
value: JSONValue,
|
|
|
|
) -> Result<Option<JSONValue>, ParseError> {
|
2020-02-07 20:01:10 -05:00
|
|
|
let start = self.i;
|
|
|
|
let end = if self.i + search.len() > self.chars.len() {
|
|
|
|
self.chars.len()
|
|
|
|
} else {
|
|
|
|
self.i + search.len()
|
|
|
|
};
|
|
|
|
|
|
|
|
let slice = &String::from_iter(&self.chars[start..end]);
|
2020-02-07 16:23:51 -05:00
|
|
|
if slice == search {
|
2020-02-07 21:27:46 -05:00
|
|
|
self.i += search.len();
|
2020-02-07 16:23:51 -05:00
|
|
|
|
|
|
|
return Ok(Some(value));
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// Increment the internal index until the next character is not a whitespace character
|
2020-02-07 16:23:51 -05:00
|
|
|
fn skip_whitespace(&mut self) {
|
|
|
|
while self.chars[self.i].is_ascii_whitespace() {
|
2020-02-10 12:26:54 -05:00
|
|
|
self.increment(1);
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-07 21:27:46 -05:00
|
|
|
/// 'Eat' the specified character
|
|
|
|
///
|
|
|
|
/// * If the next `char` matches the one passed, the internal index is incremented
|
|
|
|
/// * If the next `char` does not match the one passed, a `ParseError::ExpectedToken`
|
|
|
|
/// error is returned
|
2020-02-07 20:01:10 -05:00
|
|
|
fn eat(&mut self, ch: char) -> Result<(), ParseError> {
|
2020-02-07 16:23:51 -05:00
|
|
|
if self.chars[self.i] != ch {
|
2020-02-10 14:10:48 -05:00
|
|
|
let msg = format!("Expected {}.", ch);
|
2020-02-07 16:23:51 -05:00
|
|
|
return Err(ParseError::ExpectedToken(msg));
|
|
|
|
}
|
|
|
|
|
2020-02-11 16:18:37 -05:00
|
|
|
self.increment(1);
|
2020-02-07 16:23:51 -05:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-02-10 14:59:28 -05:00
|
|
|
/// Do a checked increment of the internal pointer index
|
2020-02-10 12:26:54 -05:00
|
|
|
fn increment(&mut self, amount: usize) {
|
|
|
|
let current = self.i;
|
|
|
|
if current + amount >= self.chars.len() {
|
|
|
|
self.i = self.chars.len() - 1;
|
|
|
|
} else {
|
|
|
|
self.i += amount;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-07 20:01:10 -05:00
|
|
|
/// Convert a `&str` containing JSON into a `Result<JSONValue, ParseError>`
|
2020-02-11 16:18:37 -05:00
|
|
|
pub fn parse(json: &str) -> JSONResult {
|
2020-02-07 16:23:51 -05:00
|
|
|
JSON::new(json).parse_value()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2020-02-11 16:42:33 -05:00
|
|
|
use super::JSONValue::{Array, False, Null, Number, Object, True};
|
2020-02-07 16:23:51 -05:00
|
|
|
use super::*;
|
2020-02-11 16:18:37 -05:00
|
|
|
|
2020-02-11 19:12:01 -05:00
|
|
|
#[test]
|
|
|
|
fn value_conversion() {
|
|
|
|
let map: JSONMap = HashMap::new();
|
|
|
|
let num = 9.380831539;
|
|
|
|
let str = "applesauce";
|
|
|
|
let arr: JSONArray = vec![JSONValue::from(map.clone()), JSONValue::from(num), JSONValue::from(str)];
|
|
|
|
|
|
|
|
assert_eq!(map.clone(), JSONMap::from(JSONValue::from(map.clone())));
|
|
|
|
assert_eq!(num, f64::from(JSONValue::from(num)));
|
|
|
|
assert_eq!(String::from(str), String::from(JSONValue::from(str)));
|
|
|
|
assert_eq!(arr.clone(), JSONArray::from(JSONValue::from(arr.clone())));
|
|
|
|
assert_eq!(true, bool::from(JSONValue::from(true)));
|
|
|
|
assert_eq!(false, bool::from(JSONValue::from(false)));
|
|
|
|
assert_eq!((), <()>::from(JSONValue::from(())));
|
|
|
|
}
|
2020-02-11 16:18:37 -05:00
|
|
|
|
2020-02-11 19:12:01 -05:00
|
|
|
#[test]
|
|
|
|
fn wrap_and_unwrap() {
|
|
|
|
let map: JSONMap = HashMap::new();
|
|
|
|
let num = 9.380831539;
|
|
|
|
let str = "applesauce";
|
|
|
|
let arr: JSONArray = vec![JSONValue::from(map.clone()), JSONValue::from(num), JSONValue::from(str)];
|
|
|
|
|
|
|
|
let s: String = JSONValue::from(str).unwrap();
|
|
|
|
let a: JSONArray = JSONValue::from(arr.clone()).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(map.clone(), JSONValue::from(map.clone()).unwrap());
|
|
|
|
assert_eq!(num, JSONValue::from(num).unwrap());
|
|
|
|
assert_eq!(str, &s);
|
|
|
|
assert_eq!(arr.clone(), a);
|
|
|
|
assert_eq!(true, JSONValue::from(true).unwrap());
|
|
|
|
assert_eq!(false, JSONValue::from(false).unwrap());
|
|
|
|
assert_eq!((), JSONValue::from(()).unwrap());
|
2020-02-11 16:18:37 -05:00
|
|
|
}
|
2020-02-07 16:23:51 -05:00
|
|
|
|
|
|
|
#[test]
|
2020-02-07 20:01:10 -05:00
|
|
|
fn parse_keyword() {
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new(r#""foobarbaz""#).parse_keyword("true", JSONValue::True);
|
2020-02-07 20:01:10 -05:00
|
|
|
assert_eq!(res, Ok(None));
|
|
|
|
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new("true").parse_keyword("true", JSONValue::True);
|
2020-02-11 16:18:37 -05:00
|
|
|
assert_eq!(res, Ok(Some(True)));
|
2020-02-07 20:01:10 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn skip_whitespace() {
|
|
|
|
let mut parser = JSON::new(" \t\r\nx");
|
|
|
|
parser.skip_whitespace();
|
|
|
|
assert_eq!('x', parser.chars[parser.i]);
|
|
|
|
}
|
|
|
|
|
2020-02-07 22:55:09 -05:00
|
|
|
#[test]
|
|
|
|
fn parse_string() {
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new(r#""\t""#).parse_string();
|
2020-02-11 19:12:01 -05:00
|
|
|
assert_eq!(res, Ok(Some(JSONValue::from("\t"))));
|
2020-02-07 22:55:09 -05:00
|
|
|
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new(r#""\u203d""#).parse_string();
|
2020-02-11 19:12:01 -05:00
|
|
|
assert_eq!(res, Ok(Some(JSONValue::from("‽"))));
|
2020-02-07 22:55:09 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 20:01:10 -05:00
|
|
|
#[test]
|
|
|
|
fn parse_empty_array() {
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new("[]").parse_value();
|
2020-02-11 16:18:37 -05:00
|
|
|
assert_eq!(res, Ok(Array(vec![])));
|
2020-02-07 20:01:10 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 23:51:49 -05:00
|
|
|
#[test]
|
|
|
|
fn parse_number() {
|
2020-02-10 14:10:48 -05:00
|
|
|
// This function works like I think, right?
|
2020-02-10 19:29:24 -05:00
|
|
|
assert_eq!(','.is_ascii_digit(), false);
|
2020-02-10 14:10:48 -05:00
|
|
|
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new(r#""foo""#).parse_number();
|
2020-02-10 12:26:54 -05:00
|
|
|
assert_eq!(res, Ok(None));
|
|
|
|
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new("3.14159").parse_number();
|
2020-02-11 16:18:37 -05:00
|
|
|
assert_eq!(res, Ok(Some(Number(3.14159f64))));
|
2020-02-07 23:51:49 -05:00
|
|
|
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new("3e4").parse_number();
|
2020-02-11 16:18:37 -05:00
|
|
|
assert_eq!(res, Ok(Some(Number(3e4f64))));
|
2020-02-10 14:10:48 -05:00
|
|
|
|
2020-02-10 19:29:24 -05:00
|
|
|
let res = JSON::new("1.234,").parse_number();
|
2020-02-11 16:18:37 -05:00
|
|
|
assert_eq!(res, Ok(Some(Number(1.234f64))));
|
2020-02-07 23:51:49 -05:00
|
|
|
}
|
|
|
|
|
2020-02-07 20:01:10 -05:00
|
|
|
#[test]
|
|
|
|
fn can_parse_array_of_keywords() {
|
|
|
|
let result = JSON::parse("[true,false,null]");
|
|
|
|
|
2020-02-11 16:42:33 -05:00
|
|
|
assert_eq!(result, Ok(Array(vec![True, False, Null])));
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
2020-02-07 23:51:49 -05:00
|
|
|
|
2020-02-10 14:59:28 -05:00
|
|
|
#[test]
|
|
|
|
fn parse_object() {
|
2020-02-10 19:29:24 -05:00
|
|
|
let result = JSON::new(r#"{"foo": "bar"}"#).parse_object();
|
2020-02-10 15:16:46 -05:00
|
|
|
|
2020-02-11 16:18:37 -05:00
|
|
|
let mut hash_map: JSONMap = HashMap::new();
|
2020-02-11 19:12:01 -05:00
|
|
|
hash_map.insert(String::from("foo"), JSONValue::from("bar"));
|
2020-02-10 15:16:46 -05:00
|
|
|
|
2020-02-10 14:59:28 -05:00
|
|
|
assert_eq!(result, Ok(Some(JSONValue::Object(hash_map))));
|
|
|
|
}
|
|
|
|
|
2020-02-10 12:26:54 -05:00
|
|
|
#[test]
|
|
|
|
fn parse_json_types() {
|
|
|
|
// Boolean / Null
|
|
|
|
let res = JSON::parse("true");
|
2020-02-11 16:18:37 -05:00
|
|
|
assert_eq!(res, Ok(True));
|
2020-02-10 12:26:54 -05:00
|
|
|
let res = JSON::parse("false");
|
2020-02-11 16:18:37 -05:00
|
|
|
assert_eq!(res, Ok(False));
|
2020-02-10 12:26:54 -05:00
|
|
|
let res = JSON::parse("null");
|
2020-02-11 16:18:37 -05:00
|
|
|
assert_eq!(res, Ok(Null));
|
2020-02-10 12:26:54 -05:00
|
|
|
|
|
|
|
// Number
|
|
|
|
let res = JSON::parse("9.38083151965");
|
2020-02-11 16:42:33 -05:00
|
|
|
assert_eq!(res, Ok(Number(9.38083151965)), "Failed to parse number");
|
2020-02-10 12:26:54 -05:00
|
|
|
|
|
|
|
// String
|
|
|
|
let res = JSON::parse(r#""/^$/""#);
|
2020-02-11 10:57:48 -05:00
|
|
|
assert_eq!(
|
|
|
|
res,
|
2020-02-11 19:12:01 -05:00
|
|
|
Ok(JSONValue::from("/^$/")),
|
2020-02-11 10:57:48 -05:00
|
|
|
"Failed to parse string"
|
|
|
|
);
|
2020-02-10 14:59:28 -05:00
|
|
|
|
|
|
|
// Number array
|
|
|
|
let res = JSON::parse("[1, 2, 3]");
|
2020-02-11 10:57:48 -05:00
|
|
|
assert_eq!(
|
|
|
|
res,
|
2020-02-11 16:42:33 -05:00
|
|
|
Ok(Array(vec![Number(1f64), Number(2f64), Number(3f64)]))
|
2020-02-11 10:57:48 -05:00
|
|
|
);
|
2020-02-10 12:26:54 -05:00
|
|
|
|
2020-02-10 15:16:46 -05:00
|
|
|
// Object array
|
2020-02-10 14:10:48 -05:00
|
|
|
let result = JSON::parse("[{}]");
|
2020-02-11 16:42:33 -05:00
|
|
|
assert_eq!(result, Ok(JSONValue::Array(vec![Object(HashMap::new())])));
|
2020-02-10 15:16:46 -05:00
|
|
|
}
|
2020-02-10 14:10:48 -05:00
|
|
|
|
2020-02-10 15:16:46 -05:00
|
|
|
#[test]
|
|
|
|
fn parse_nested_object() {
|
|
|
|
let res = JSON::parse(r#"{"a": {"b": []}}"#);
|
2020-02-11 16:18:37 -05:00
|
|
|
let mut outermap: JSONMap = HashMap::new();
|
|
|
|
let mut innermap: JSONMap = HashMap::new();
|
|
|
|
|
|
|
|
innermap.insert(String::from("b"), Array(vec![]));
|
|
|
|
outermap.insert(String::from("a"), Object(innermap));
|
|
|
|
|
|
|
|
let expected = Ok(Object(outermap));
|
|
|
|
|
|
|
|
assert_eq!(res, expected);
|
2020-02-10 15:16:46 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2020-02-11 16:18:37 -05:00
|
|
|
fn parse_object_with_number_values() {
|
2020-02-10 15:34:10 -05:00
|
|
|
let result = JSON::parse(r#"[{ "a": 9.38083151965, "b": 4e3 }]"#);
|
2020-02-11 16:18:37 -05:00
|
|
|
let mut map: JSONMap = HashMap::new();
|
|
|
|
map.insert(String::from("a"), Number(9.38083151965f64));
|
|
|
|
map.insert(String::from("b"), Number(4e3f64));
|
2020-02-10 15:34:10 -05:00
|
|
|
|
2020-02-11 16:18:37 -05:00
|
|
|
let expected = Ok(Array(vec![Object(map)]));
|
|
|
|
|
2020-02-11 16:42:33 -05:00
|
|
|
assert_eq!(
|
|
|
|
result, expected,
|
|
|
|
"Failed on just number values: {:#?}",
|
|
|
|
result
|
|
|
|
);
|
2020-02-11 16:18:37 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn parse_weird_character_array() {
|
2020-02-11 16:42:33 -05:00
|
|
|
let result =
|
|
|
|
JSON::parse(r#"["\"", "\\", "/", "\b", "\f", "\n", "\r", "\t", "\u0001", "\uface"]"#);
|
2020-02-11 16:18:37 -05:00
|
|
|
let expected = Ok(Array(vec![
|
2020-02-11 19:12:01 -05:00
|
|
|
JSONValue::from("\""),
|
|
|
|
JSONValue::from("\\"),
|
|
|
|
JSONValue::from("/"),
|
|
|
|
JSONValue::from("\u{8}"),
|
|
|
|
JSONValue::from("\x0C"),
|
|
|
|
JSONValue::from("\n"),
|
|
|
|
JSONValue::from("\r"),
|
|
|
|
JSONValue::from("\t"),
|
|
|
|
JSONValue::from("\u{1}"),
|
|
|
|
JSONValue::from("\u{face}"),
|
2020-02-11 16:18:37 -05:00
|
|
|
]));
|
|
|
|
|
|
|
|
assert_eq!(result, expected);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn parse_full_json_example() {
|
2020-02-07 23:51:49 -05:00
|
|
|
let result = JSON::parse(
|
2020-02-11 16:42:33 -05:00
|
|
|
r#"[{
|
2020-02-07 23:51:49 -05:00
|
|
|
"a": 9.38083151965,
|
|
|
|
"b": 4e3,
|
|
|
|
"c": [1, 2, 3],
|
|
|
|
"d": "foo",
|
|
|
|
"e": {
|
|
|
|
"f": {
|
|
|
|
"g": {
|
|
|
|
"h": null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
"i": ["\"", "\\", "/", "\b", "\f", "\n", "\r", "\t", "\u0001", "\uface"]
|
2020-02-11 10:57:48 -05:00
|
|
|
}]"#,
|
|
|
|
);
|
2020-02-11 16:18:37 -05:00
|
|
|
|
|
|
|
let mut map: JSONMap = HashMap::new();
|
|
|
|
let mut emap: JSONMap = HashMap::new();
|
|
|
|
let mut fmap: JSONMap = HashMap::new();
|
|
|
|
let mut gmap: JSONMap = HashMap::new();
|
|
|
|
|
|
|
|
gmap.insert(String::from("h"), Null);
|
|
|
|
fmap.insert(String::from("g"), Object(gmap));
|
|
|
|
emap.insert(String::from("f"), Object(fmap));
|
|
|
|
|
|
|
|
map.insert(String::from("a"), Number(9.38083151965f64));
|
|
|
|
map.insert(String::from("b"), Number(4e3f64));
|
2020-02-11 16:42:33 -05:00
|
|
|
map.insert(
|
|
|
|
String::from("c"),
|
|
|
|
Array(vec![Number(1f64), Number(2f64), Number(3f64)]),
|
|
|
|
);
|
2020-02-11 19:12:01 -05:00
|
|
|
map.insert(String::from("d"), JSONValue::from("foo"));
|
2020-02-11 16:18:37 -05:00
|
|
|
map.insert(String::from("e"), Object(emap));
|
|
|
|
|
2020-02-11 16:42:33 -05:00
|
|
|
map.insert(
|
|
|
|
String::from("i"),
|
|
|
|
Array(vec![
|
2020-02-11 19:12:01 -05:00
|
|
|
JSONValue::from("\""),
|
|
|
|
JSONValue::from("\\"),
|
|
|
|
JSONValue::from("/"),
|
|
|
|
JSONValue::from("\u{8}"),
|
|
|
|
JSONValue::from("\x0C"),
|
|
|
|
JSONValue::from("\n"),
|
|
|
|
JSONValue::from("\r"),
|
|
|
|
JSONValue::from("\t"),
|
|
|
|
JSONValue::from("\u{1}"),
|
|
|
|
JSONValue::from("\u{face}"),
|
2020-02-11 16:42:33 -05:00
|
|
|
]),
|
|
|
|
);
|
2020-02-11 16:18:37 -05:00
|
|
|
|
2020-02-07 23:51:49 -05:00
|
|
|
assert!(result.is_ok(), format!("{:#?}", result));
|
2020-02-11 19:12:01 -05:00
|
|
|
|
|
|
|
let outer_array: Vec<JSONValue> = result.unwrap().unwrap();
|
|
|
|
let result_map: JSONMap = outer_array[0].clone().unwrap();
|
2020-02-11 16:18:37 -05:00
|
|
|
|
|
|
|
for (k, v) in &map {
|
2020-02-11 16:42:33 -05:00
|
|
|
assert_eq!(
|
|
|
|
result_map.get(k).unwrap(),
|
|
|
|
v,
|
|
|
|
"HashMap Entry Differs: {:#?}, {:#?}",
|
|
|
|
result_map.get(k).unwrap(),
|
|
|
|
v
|
|
|
|
);
|
2020-02-11 16:18:37 -05:00
|
|
|
}
|
2020-02-07 23:51:49 -05:00
|
|
|
}
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|