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-12 11:38:37 -05:00
|
|
|
///
|
|
|
|
/// The `From` trait is implemented for all the
|
|
|
|
/// types of values wrapped in the `JSONValue` enum
|
|
|
|
///
|
|
|
|
/// Additionally, `()` will convert to `JSONValue::Null`
|
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
|
|
|
|
///
|
2020-02-12 11:38:37 -05:00
|
|
|
/// This is a convenience method that calls the `from` method
|
|
|
|
/// for the appropriate type.
|
|
|
|
///
|
2020-02-11 19:12:01 -05:00
|
|
|
/// 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,
|
2020-02-12 11:22:02 -05:00
|
|
|
_ => unreachable!(),
|
2020-02-11 19:12:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-12 11:22:02 -05:00
|
|
|
impl From<JSONValue> for JSONArray {
|
2020-02-11 19:12:01 -05:00
|
|
|
/// Extracts the `Vec` in the `JSONValue` enum, if it exists.
|
|
|
|
/// Otherwise, panics.
|
|
|
|
fn from(val: JSONValue) -> JSONArray {
|
|
|
|
match val {
|
|
|
|
JSONValue::Array(a) => a,
|
2020-02-12 11:22:02 -05:00
|
|
|
_ => unreachable!(),
|
2020-02-11 19:12:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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,
|
2020-02-12 11:22:02 -05:00
|
|
|
_ => unreachable!(),
|
2020-02-11 19:12:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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,
|
2020-02-12 11:22:02 -05:00
|
|
|
_ => unreachable!(),
|
2020-02-11 19:12:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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,
|
2020-02-12 11:22:02 -05:00
|
|
|
_ => unreachable!(),
|
2020-02-11 19:12:01 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<JSONValue> for () {
|
|
|
|
/// This will just swallow the enum value and return a unit tuple
|
2020-02-12 11:22:02 -05:00
|
|
|
fn from(_: JSONValue) -> () {
|
|
|
|
()
|
|
|
|
}
|
2020-02-11 19:12:01 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
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-12 11:22:02 -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-12 11:22:02 -05:00
|
|
|
} else {
|
|
|
|
self.skip_whitespace();
|
2020-02-07 16:23:51 -05:00
|
|
|
}
|
|
|
|
|
2020-02-12 11:22:02 -05:00
|
|
|
let maybe_key = self.parse_string()?;
|
|
|
|
if maybe_key.is_none() {
|
|
|
|
return Err(ParseError::ExpectedObjectKey(format!(
|
|
|
|
"Expected an object key. Does the object have a trailing comma?"
|
|
|
|
)));
|
|
|
|
}
|
2020-02-07 16:23:51 -05:00
|
|
|
|
|
|
|
self.skip_whitespace();
|
2020-02-07 20:01:10 -05:00
|
|
|
self.eat(':')?;
|
2020-02-12 11:22:02 -05:00
|
|
|
|
|
|
|
let key = maybe_key.unwrap().into();
|
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
|
|
|
}
|
|
|
|
|
2020-02-12 11:22:02 -05:00
|
|
|
self.expect_not_end('}')?;
|
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;
|
|
|
|
}
|
|
|
|
|
2020-02-12 11:22:02 -05:00
|
|
|
self.expect_not_end(']')?;
|
2020-02-07 16:23:51 -05:00
|
|
|
// 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-12 11:22:02 -05:00
|
|
|
} else if ch == 'u' {
|
|
|
|
if 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);
|
|
|
|
|
|
|
|
self.increment(5);
|
|
|
|
} else {
|
|
|
|
return Err(ParseError::ExpectedUnicodeEscape(format!(
|
|
|
|
"Expected a unicode escape sequence"
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return Err(ParseError::ExpectedEscapeChar(format!(
|
|
|
|
"Expected an escape sequence"
|
|
|
|
)));
|
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-12 11:22:02 -05:00
|
|
|
self.expect_not_end('"')?;
|
|
|
|
self.increment(1);
|
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-12 11:22:02 -05:00
|
|
|
self.expect_digit(start, n)?;
|
2020-02-07 23:51:49 -05:00
|
|
|
}
|
|
|
|
|
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-12 11:22:02 -05:00
|
|
|
self.expect_digit(start, n)?;
|
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-12 11:22:02 -05:00
|
|
|
self.expect_digit(start, n)?;
|
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-12 11:22:02 -05:00
|
|
|
/// Check that the next character is a digit. If not, return ParseError.
|
|
|
|
fn expect_digit(&mut self, start: usize, end: usize) -> Result<(), ParseError> {
|
|
|
|
let current = String::from_iter(&self.chars[start..end]);
|
|
|
|
if !self.chars[end].is_ascii_digit() {
|
|
|
|
Err(ParseError::ExpectedDigit(format!(
|
|
|
|
"Expected a digit, received '{}' after numeric '{}'",
|
|
|
|
self.chars[end], current
|
|
|
|
)))
|
|
|
|
} else {
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Verify that we are not at the end of the input string
|
|
|
|
fn expect_not_end(&mut self, ch: char) -> Result<(), ParseError> {
|
|
|
|
if self.i == self.chars.len() {
|
|
|
|
Err(ParseError::UnexpectedEndOfInput(format!(
|
|
|
|
"Unexpected end of input. Expected '{}'",
|
|
|
|
ch
|
|
|
|
)))
|
|
|
|
} else {
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-07 20:01:10 -05:00
|
|
|
/// Convert a `&str` containing JSON into a `Result<JSONValue, ParseError>`
|
2020-02-12 11:38:37 -05:00
|
|
|
///
|
|
|
|
/// Example:
|
|
|
|
/// ```rust
|
|
|
|
/// use naive_json_parser::JSON;
|
|
|
|
///
|
|
|
|
/// // This should now be a set of nested `JSONValue` enums containing the parsed values
|
|
|
|
/// let parse_result = JSON::parse(r#"[1, 2.0, 3e4, "foo", {}, [], true, false, null]"#);
|
|
|
|
/// # assert!(parse_result.is_ok(), "Parse method example failed");
|
|
|
|
/// ```
|
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-12 11:22:02 -05:00
|
|
|
use super::JSONValue::{Array, Number, True};
|
2020-02-07 16:23:51 -05:00
|
|
|
use super::*;
|
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("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-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-07 16:23:51 -05:00
|
|
|
}
|