yan_json 0.2.0

A lightweight library for easily handling JSON
Documentation
use std::{collections::HashMap, fmt::Display, iter::Peekable};

mod macros;
pub mod prelude;

#[cfg(test)]
mod tests;

#[derive(Debug, PartialEq)]
pub enum JsonNode {
    Object(HashMap<String, Self>),
    Array(Vec<Self>),
    String(String),
    Number(f64),
    Bool(bool),
    Null,
}

const WHITE_SPACES: &[char] = &[' ', '\n'];

impl JsonNode {
    pub fn parse(s: &str) -> Option<Self> {
        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_object(mut s: &str) -> Vec<[String; 2]> {
        assert_eq!(s.chars().next(), Some('{'));
        assert_eq!(s.chars().last(), Some('}'));
        s = &s[1..s.len() - 1];

        let mut result: Vec<[String; 2]> = Vec::new();

        let mut it = s.chars().peekable();
        loop {
            Self::iter_advance_while(&mut it, WHITE_SPACES);
            if it.peek().is_none() {
                break;
            }

            assert_eq!(it.next(), Some('"'));

            // reading the key
            let mut key = String::new();
            let mut next_to_be_escaped = false;
            for c in it.by_ref() {
                if next_to_be_escaped {
                    next_to_be_escaped = false;
                    continue;
                }
                match c {
                    '\\' => next_to_be_escaped = true,
                    '"' => break,
                    c => key.push(c),
                }
            }
            Self::iter_advance_while(&mut it, WHITE_SPACES);
            assert_eq!(it.next(), Some(':'));

            // reading the value
            let mut val = String::new();
            let mut stack: Vec<char> = Vec::new();
            let mut next_to_be_escaped = false;
            for c in it.by_ref() {
                match c {
                    c if next_to_be_escaped => {
                        val.push(c);
                        next_to_be_escaped = false;
                    }
                    '\\' => next_to_be_escaped = true,
                    c if Self::is_bracket(c) => {
                        Self::update_bracket_stack(&mut stack, c);
                        val.push(c);
                    }
                    ',' if stack.is_empty() => break,
                    c if stack.is_empty() && WHITE_SPACES.contains(&c) => {}
                    _ => val.push(c),
                }
            }
            result.push([key, val]);
        }
        result
    }

    fn iter_advance_while<I>(it: &mut Peekable<I>, allowed: &[char])
    where
        I: Iterator<Item = char>,
    {
        while let Some(c) = it.peek() {
            if !allowed.contains(c) {
                return;
            }
            it.next();
        }
    }

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

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

        let mut it = s.chars().peekable();
        loop {
            Self::iter_advance_while(&mut it, WHITE_SPACES);
            if it.peek().is_none() {
                break;
            }

            // reading the value
            let mut val = String::new();
            let mut stack: Vec<char> = Vec::new();
            let mut next_to_be_escaped = false;
            for c in it.by_ref() {
                match c {
                    c if next_to_be_escaped => {
                        val.push(c);
                        next_to_be_escaped = false;
                    }
                    '\\' => next_to_be_escaped = true,
                    c if Self::is_bracket(c) => {
                        Self::update_bracket_stack(&mut stack, c);
                        val.push(c);
                    }
                    ',' if stack.is_empty() => break,
                    c if stack.is_empty() && WHITE_SPACES.contains(&c) => {}
                    _ => val.push(c),
                }
            }
            result.push(val);
        }
        result
    }
    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) {
        let open = ['[', '{'];
        let close = [']', '}'];

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

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

            _ => panic!("{top:?}, {c}"),
        }
    }
}

impl Display for JsonNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Object(kv_pairs) => {
                write!(f, "{{")?;
                for (i, (key, val)) in kv_pairs.iter().enumerate() {
                    write!(f, "\"{key}\":{val}")?;
                    if i != kv_pairs.len() - 1 {
                        write!(f, ",")?;
                    }
                }
                write!(f, "}}")?;
            }
            Self::Array(elements) => {
                write!(f, "[")?;
                for (i, e) in elements.iter().enumerate() {
                    write!(f, "{e}")?;
                    if i != elements.len() - 1 {
                        write!(f, ",")?;
                    }
                }
                write!(f, "]")?;
            }
            Self::String(s) => write!(f, "\"{s}\"")?,
            Self::Number(x) => write!(f, "{x}")?,
            Self::Bool(b) => write!(f, "{b}")?,
            Self::Null => write!(f, "null")?,
        }
        Ok(())
    }
}

impl From<&str> for JsonNode {
    fn from(value: &str) -> Self {
        JsonNode::String(value.to_string())
    }
}

impl From<f64> for JsonNode {
    fn from(value: f64) -> Self {
        JsonNode::Number(value)
    }
}

impl From<i32> for JsonNode {
    fn from(value: i32) -> Self {
        JsonNode::Number(value as f64)
    }
}

impl From<bool> for JsonNode {
    fn from(value: bool) -> Self {
        JsonNode::Bool(value)
    }
}