yan_json 0.2.3

A lightweight library for easily handling JSON
Documentation
use crate::prelude::*;

impl JsonNode {
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim();
        let surrounded = |a, b| s.starts_with(a) && s.ends_with(b);
        Some(match s {
            s if surrounded('{', '}') => Self::Object(
                Self::parse_object(s)?
                    .into_iter()
                    .map(|(k, v)| Self::parse(v).map(|v| (k, v)))
                    .collect::<Option<HashMap<String, JsonNode>>>()?,
            ),
            s if surrounded('[', ']') => JsonNode::Array(
                Self::parse_array(s)?
                    .iter()
                    .map(|s| Self::parse(s))
                    .collect::<Option<Vec<Self>>>()?,
            ),
            s if surrounded('"', '"') => {
                let s: &str = &s[1..s.len() - 1];
                Self::String(s.to_string())
            }
            s if s.parse::<f64>().is_ok() => JsonNode::Number(s.parse().unwrap()),
            "false" => Self::Bool(false),
            "true" => Self::Bool(true),
            "null" => Self::Null,

            _ => return None,
        })
    }

    fn parse_token_with_stack<'a>(s: &'a str, i: &mut usize) -> Option<(&'a str, Option<char>)> {
        let bytes = s.as_bytes();

        let mut stack: Vec<char> = Vec::new();
        let mut next_to_be_escaped = false;

        // skip whitespaces
        while let Some(c) = s[*i..].chars().next() {
            if !c.is_whitespace() {
                break;
            }
            *i += c.len_utf8();
        }

        let i_start = *i;

        while *i < bytes.len() {
            let c = s[*i..].chars().next().unwrap();
            let c_len = c.len_utf8();

            if next_to_be_escaped {
                *i += c_len;
                next_to_be_escaped = false;
                continue;
            }
            if is_bracket(c) {
                if stack.last() == Some(&'"') {
                    if c == '"' {
                        stack.pop();
                    }
                    *i += c_len;
                    continue;
                }
                update_bracket_stack(&mut stack, c);
                if stack.is_empty() {
                    *i += c_len;
                    break;
                }
            }

            if stack.is_empty() && is_seperator(c) {
                break;
            }
            if c == '\\' {
                next_to_be_escaped = true;
                continue;
            }
            *i += c_len;
        }
        let i_end = *i;

        // skip whitespaces
        while let Some(c) = s[*i..].chars().next() {
            if !c.is_whitespace() {
                break;
            }
            *i += c.len_utf8();
        }
        let slice = &s[i_start..i_end];
        let sep = s[*i..].chars().next();

        *i += 1;

        Some((slice, sep))
    }

    fn parse_object(mut s: &str) -> Option<Vec<(String, &str)>> {
        assert_eq!(s.chars().next(), Some('{'));
        assert_eq!(s.chars().last(), Some('}'));
        s = s[1..s.len() - 1].trim();

        let mut result: Vec<(String, &str)> = Vec::new();
        let mut i = 0;

        while i < s.len() {
            // reading the key
            let (key, sep) = Self::parse_token_with_stack(s, &mut i)?;
            if sep != Some(':') {
                return None;
            }

            let key = if key.chars().next()? == '"' && key.chars().last()? == '"' {
                key[1..key.len() - 1].to_string()
            } else {
                return None;
            };

            let (val, sep) = Self::parse_token_with_stack(s, &mut i)?;
            result.push((key, val));

            if sep.is_none() {
                break;
            }
            if sep == Some(',') {
                // trailing comma not allowed
                s[i..].chars().next()?;
            } else {
                return None;
            }
        }
        Some(result)
    }

    fn parse_array(s: &str) -> Option<Vec<&str>> {
        assert_eq!(s.chars().next(), Some('['));
        assert_eq!(s.chars().last(), Some(']'));
        let s = s[1..s.len() - 1].trim();

        let mut result: Vec<&str> = Vec::new();

        let mut i = 0;
        loop {
            let (val, sep) = Self::parse_token_with_stack(s, &mut i)?;

            if !val.is_empty() {
                result.push(val);
            }

            if sep.is_none() {
                break;
            }
            if sep == Some(',') {
                // trailing comma not allowed
                s[i..].chars().next()?;
            } else {
                return None;
            }
        }
        Some(result)
    }
}

fn is_seperator(c: char) -> bool {
    c.is_whitespace() || [',', ':', '[', ']', '{', '}'].contains(&c)
}

fn is_bracket(c: char) -> bool {
    ['"', '[', ']', '{', '}'].contains(&c)
}
fn brackets_match(a: char, b: char) -> bool {
    a == '[' && b == ']' || a == '{' && b == '}'
}
fn update_bracket_stack(stack: &mut Vec<char>, c: char) -> Option<()> {
    const OPENING: &[char] = &['[', '{'];
    const CLOSING: &[char] = &[']', '}'];

    let top = stack.last();
    match (top, c) {
        (None, '"') => stack.push('"'),
        (None, c) if CLOSING.contains(&c) => panic!(),
        (_, c) if OPENING.contains(&c) => stack.push(c),

        (Some('"'), '"') => {
            stack.pop();
        }
        (Some(top), c) if brackets_match(*top, c) => {
            stack.pop();
        }
        (Some(_), '"') => stack.push('"'),

        _ => return None,
    }
    Some(())
}