use crate::error::messages::*;
use crate::io::traits::ISource;
use crate::nodes::node::Node;
use crate::nodes::node::Numeric;
use crate::parser::config::ParserConfig;
use crate::parser::constants::*;
#[cfg(feature = "std")]
use std::collections::HashMap;
#[cfg(not(feature = "std"))]
use alloc::{
collections::BTreeMap as HashMap,
format,
string::{String, ToString},
vec::Vec,
};
use smallvec::SmallVec;
pub fn parse(source: &mut dyn ISource) -> Result<Node, String> {
parse_with_config(
source,
&ParserConfig::unlimited().with_max_depth(Some(256)),
)
}
pub fn from_str(s: &str) -> Result<Node, String> {
use babbel_core::io::SliceSource;
let mut source = SliceSource::new(s);
parse(&mut source)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Node, String> {
if let Ok(s) = core::str::from_utf8(bytes) {
use babbel_core::io::SliceSource;
let mut source = SliceSource::new(s);
parse(&mut source)
} else {
Err(ERR_INVALID_UTF8.to_string())
}
}
pub fn parse_with_config(source: &mut dyn ISource, config: &ParserConfig) -> Result<Node, String> {
let node = parse_value(source, config, 0)?;
skip_whitespace(source);
if let Some(c) = source.current() {
return Err(format!("{}{}", ERR_UNEXPECTED_CHAR, c));
}
Ok(node)
}
fn parse_value(
source: &mut dyn ISource,
config: &ParserConfig,
depth: usize,
) -> Result<Node, String> {
if let Some(max_depth) = config.max_depth {
if depth >= max_depth {
use arrayvec::ArrayString;
use core::fmt::Write;
let mut msg: ArrayString<64> = ArrayString::new();
let _ = write!(&mut msg, "Maximum nesting depth of {} exceeded", max_depth);
return Err(msg.to_string());
}
}
skip_whitespace(source);
match source.current() {
Some(OBJECT_START) => parse_object_with_config(source, config, depth),
Some(ARRAY_START) => parse_array_with_config(source, config, depth),
Some(QUOTE) => parse_string_with_config(source, config),
Some(TRUE_START) => parse_true(source),
Some(FALSE_START) => parse_false(source),
Some(NULL_START) => parse_null(source),
Some(c) if c.is_digit(10) || c == MINUS => parse_number(source),
Some(c) => Err(format!("{}{}", ERR_UNEXPECTED_CHAR, c)),
None => Err(ERR_EMPTY_INPUT.to_string()),
}
}
#[inline]
fn skip_whitespace(source: &mut dyn ISource) {
while let Some(c) = source.current() {
if !is_json_whitespace(c) {
break;
}
source.next();
}
}
#[allow(dead_code)]
fn parse_object(source: &mut dyn ISource) -> Result<Node, String> {
parse_object_with_config(source, &ParserConfig::unlimited(), 0)
}
fn parse_object_with_config(
source: &mut dyn ISource,
config: &ParserConfig,
depth: usize,
) -> Result<Node, String> {
let mut pairs: SmallVec<[(String, Node); 8]> = SmallVec::new();
source.next();
skip_whitespace(source);
if let Some(OBJECT_END) = source.current() {
source.next();
return Ok(Node::Object(HashMap::new()));
}
loop {
if let Some(max_size) = config.max_object_size {
if pairs.len() >= max_size {
use arrayvec::ArrayString;
use core::fmt::Write;
let mut msg: ArrayString<64> = ArrayString::new();
let _ = write!(&mut msg, "Maximum object size of {} exceeded", max_size);
return Err(msg.to_string());
}
}
skip_whitespace(source);
let key = match parse_string_with_config(source, config)? {
Node::Str(s) => s,
_ => return Err(ERR_OBJECT_KEY.to_string()),
};
skip_whitespace(source);
match source.current() {
Some(COLON) => source.next(),
_ => return Err(ERR_EXPECT_COLON.to_string()),
}
skip_whitespace(source);
let value = parse_value(source, config, depth + 1)?;
pairs.push((key, value));
skip_whitespace(source);
match source.current() {
Some(COMMA) => {
source.next();
continue;
}
Some(OBJECT_END) => {
source.next();
break;
}
_ => return Err(ERR_EXPECT_OBJECT_END.to_string()),
}
}
let mut map = HashMap::with_capacity((pairs.len() * 4) / 3 + 1);
for (k, v) in pairs {
map.insert(k, v);
}
Ok(Node::Object(map))
}
#[allow(dead_code)]
fn parse_array(source: &mut dyn ISource) -> Result<Node, String> {
parse_array_with_config(source, &ParserConfig::unlimited(), 0)
}
fn parse_array_with_config(
source: &mut dyn ISource,
config: &ParserConfig,
depth: usize,
) -> Result<Node, String> {
let mut vec: SmallVec<[Node; 8]> = SmallVec::new();
source.next();
skip_whitespace(source);
if let Some(ARRAY_END) = source.current() {
source.next();
return Ok(Node::Array(vec.into_vec()));
}
loop {
if let Some(max_size) = config.max_array_size {
if vec.len() >= max_size {
use arrayvec::ArrayString;
use core::fmt::Write;
let mut msg: ArrayString<64> = ArrayString::new();
let _ = write!(&mut msg, "Maximum array size of {} exceeded", max_size);
return Err(msg.to_string());
}
}
vec.push(parse_value(source, config, depth + 1)?);
skip_whitespace(source);
match source.current() {
Some(COMMA) => {
source.next();
continue;
}
Some(ARRAY_END) => {
source.next();
break;
}
_ => return Err(ERR_EXPECT_ARRAY_END.to_string()),
}
}
Ok(Node::Array(vec.into_vec()))
}
#[allow(dead_code)]
fn parse_string(source: &mut dyn ISource) -> Result<Node, String> {
parse_string_with_config(source, &ParserConfig::unlimited())
}
fn parse_string_with_config(
source: &mut dyn ISource,
config: &ParserConfig,
) -> Result<Node, String> {
use arrayvec::ArrayVec;
let mut buf: ArrayVec<u8, 64> = ArrayVec::new();
let mut heap_buf: Option<Vec<u8>> = None;
source.next();
while let Some(c) = source.current() {
let cur_len = if let Some(ref v) = heap_buf {
v.len()
} else {
buf.len()
};
if let Some(max_len) = config.max_string_length {
if cur_len >= max_len {
use arrayvec::ArrayString;
use core::fmt::Write;
let mut msg: ArrayString<64> = ArrayString::new();
let _ = write!(
&mut msg,
"Maximum string length of {} bytes exceeded",
max_len
);
return Err(msg.to_string());
}
}
match c {
QUOTE => {
source.next();
if let Some(v) = heap_buf {
return Ok(Node::Str(unsafe { String::from_utf8_unchecked(v) }));
} else {
return Ok(Node::Str(unsafe {
String::from_utf8_unchecked(buf.into_iter().collect())
}));
}
}
BACKSLASH => {
source.next();
let push_byte =
|b: u8, buf: &mut ArrayVec<u8, 64>, heap_buf: &mut Option<Vec<u8>>| {
if let Some(v) = heap_buf {
v.push(b);
} else if buf.try_push(b).is_err() {
let mut v = buf.clone().into_iter().collect::<Vec<u8>>();
v.push(b);
*heap_buf = Some(v);
}
};
match source.current() {
Some('"') => push_byte(b'"', &mut buf, &mut heap_buf),
Some('\\') => push_byte(b'\\', &mut buf, &mut heap_buf),
Some('/') => push_byte(b'/', &mut buf, &mut heap_buf),
Some('b') => push_byte(b'\x08', &mut buf, &mut heap_buf),
Some('f') => push_byte(b'\x0c', &mut buf, &mut heap_buf),
Some('n') => push_byte(b'\n', &mut buf, &mut heap_buf),
Some('r') => push_byte(b'\r', &mut buf, &mut heap_buf),
Some('t') => push_byte(b'\t', &mut buf, &mut heap_buf),
Some('u') => {
source.next();
let mut hex: ArrayVec<u8, 4> = ArrayVec::new();
for _ in 0..4 {
match source.current() {
Some(d) if d.is_ascii_hexdigit() => {
let _ = hex.push(d as u8);
source.next();
}
_ => return Err(ERR_INVALID_ESCAPE.to_string()),
}
}
let hex_str = core::str::from_utf8(&hex)
.map_err(|_| ERR_INVALID_ESCAPE.to_string())?;
let code = u32::from_str_radix(hex_str, 16)
.map_err(|_| ERR_INVALID_ESCAPE.to_string())?;
let decoded_char = if (0xD800..=0xDBFF).contains(&code) {
if source.current() == Some('\\') {
source.next();
if source.current() == Some('u') {
source.next();
let mut low_hex: ArrayVec<u8, 4> = ArrayVec::new();
for _ in 0..4 {
match source.current() {
Some(d) if d.is_ascii_hexdigit() => {
let _ = low_hex.push(d as u8);
source.next();
}
_ => return Err(ERR_INVALID_ESCAPE.to_string()),
}
}
let low_hex_str = core::str::from_utf8(&low_hex)
.map_err(|_| ERR_INVALID_ESCAPE.to_string())?;
let low_code = u32::from_str_radix(low_hex_str, 16)
.map_err(|_| ERR_INVALID_ESCAPE.to_string())?;
if (0xDC00..=0xDFFF).contains(&low_code) {
let scalar = 0x10000
+ (((code - 0xD800) << 10) | (low_code - 0xDC00));
char::from_u32(scalar)
.ok_or_else(|| ERR_INVALID_ESCAPE.to_string())?
} else {
return Err(ERR_INVALID_ESCAPE.to_string());
}
} else {
return Err(ERR_INVALID_ESCAPE.to_string());
}
} else {
return Err(ERR_INVALID_ESCAPE.to_string());
}
} else if (0xDC00..=0xDFFF).contains(&code) {
return Err(ERR_INVALID_ESCAPE.to_string());
} else {
char::from_u32(code).ok_or_else(|| ERR_INVALID_ESCAPE.to_string())?
};
let mut utf8_buf = [0u8; 4];
let encoded = decoded_char.encode_utf8(&mut utf8_buf);
for b in encoded.as_bytes() {
if let Some(ref mut v) = heap_buf {
v.push(*b);
} else if buf.try_push(*b).is_err() {
let mut v = buf.clone().into_iter().collect::<Vec<u8>>();
v.push(*b);
heap_buf = Some(v);
}
}
continue;
}
_ => return Err(ERR_INVALID_ESCAPE.to_string()),
}
source.next();
}
c if (c as u32) < 0x20 => {
return Err(ERR_UNESCAPED_CONTROL_CHAR.to_string());
}
_ => {
let mut utf8_buf = [0u8; 4];
let encoded = c.encode_utf8(&mut utf8_buf);
for b in encoded.as_bytes() {
if let Some(ref mut v) = heap_buf {
v.push(*b);
} else if buf.try_push(*b).is_err() {
let mut v = buf.clone().into_iter().collect::<Vec<u8>>();
v.push(*b);
heap_buf = Some(v);
}
}
source.next();
}
}
}
Err(ERR_UNTERMINATED_STRING.to_string())
}
fn parse_number(source: &mut dyn ISource) -> Result<Node, String> {
use arrayvec::ArrayString;
let mut num_buf: ArrayString<256> = ArrayString::new();
let mut is_float = false;
if source.current() == Some(MINUS) {
num_buf.try_push(MINUS).map_err(|_| ERR_INVALID_NUMBER.to_string())?;
source.next();
}
match source.current() {
Some('0') => {
num_buf.try_push('0').map_err(|_| ERR_INVALID_NUMBER.to_string())?;
source.next();
if let Some(c) = source.current() {
if c.is_ascii_digit() {
return Err(ERR_INVALID_NUMBER.to_string());
}
}
}
Some(c) if c.is_ascii_digit() => {
while let Some(d) = source.current() {
if d.is_ascii_digit() {
num_buf.try_push(d).map_err(|_| ERR_INVALID_NUMBER.to_string())?;
source.next();
} else {
break;
}
}
}
_ => return Err(ERR_INVALID_NUMBER.to_string()),
}
if source.current() == Some(DECIMAL_POINT) {
is_float = true;
num_buf.try_push(DECIMAL_POINT).map_err(|_| ERR_INVALID_NUMBER.to_string())?;
source.next();
match source.current() {
Some(d) if d.is_ascii_digit() => {
while let Some(d) = source.current() {
if d.is_ascii_digit() {
num_buf.try_push(d).map_err(|_| ERR_INVALID_NUMBER.to_string())?;
source.next();
} else {
break;
}
}
}
_ => return Err(ERR_INVALID_NUMBER.to_string()),
}
}
if matches!(source.current(), Some(EXPONENT_LOWER) | Some(EXPONENT_UPPER)) {
is_float = true;
let exp_char = source.current().unwrap();
num_buf.try_push(exp_char).map_err(|_| ERR_INVALID_NUMBER.to_string())?;
source.next();
if let Some(sign) = source.current() {
if sign == PLUS || sign == MINUS {
num_buf.try_push(sign).map_err(|_| ERR_INVALID_NUMBER.to_string())?;
source.next();
}
}
match source.current() {
Some(d) if d.is_ascii_digit() => {
while let Some(d) = source.current() {
if d.is_ascii_digit() {
num_buf.try_push(d).map_err(|_| ERR_INVALID_NUMBER.to_string())?;
source.next();
} else {
break;
}
}
}
_ => return Err(ERR_INVALID_NUMBER.to_string()),
}
}
let num_str: &str = num_buf.as_str();
if is_float {
match num_str.parse::<f64>() {
Ok(n) => Ok(Node::Number(Numeric::Float(n))),
Err(_) => Err(ERR_INVALID_FLOAT.to_string()),
}
} else {
match num_str.parse::<i64>() {
Ok(n) => Ok(Node::Number(Numeric::Integer(n))),
Err(_) => match num_str.parse::<f64>() {
Ok(n) => Ok(Node::Number(Numeric::Float(n))),
Err(_) => Err(ERR_INVALID_INTEGER.to_string()),
},
}
}
}
fn parse_true(source: &mut dyn ISource) -> Result<Node, String> {
source.next(); for c in ['r', 'u', 'e'] {
if source.current() != Some(c) {
return Err(ERR_EXPECT_TRUE.to_string());
}
source.next();
}
Ok(Node::Boolean(true))
}
fn parse_false(source: &mut dyn ISource) -> Result<Node, String> {
source.next(); for c in ['a', 'l', 's', 'e'] {
if source.current() != Some(c) {
return Err(ERR_EXPECT_FALSE.to_string());
}
source.next();
}
Ok(Node::Boolean(false))
}
fn parse_null(source: &mut dyn ISource) -> Result<Node, String> {
source.next(); for c in ['u', 'l', 'l'] {
if source.current() != Some(c) {
return Err(ERR_EXPECT_NULL.to_string());
}
source.next();
}
Ok(Node::None)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::io::sources::buffer::Buffer;
#[test]
fn test_parse_null() {
let mut source = Buffer::new(b"null");
assert!(matches!(parse(&mut source), Ok(Node::None)));
}
#[test]
fn test_parse_true() {
let mut source = Buffer::new(b"true");
assert!(matches!(parse(&mut source), Ok(Node::Boolean(true))));
}
#[test]
fn test_parse_false() {
let mut source = Buffer::new(b"false");
assert!(matches!(parse(&mut source), Ok(Node::Boolean(false))));
}
#[test]
fn test_parse_string() {
let mut source = Buffer::new(b"\"hello\"");
assert!(matches!(parse(&mut source), Ok(Node::Str(s)) if s == "hello"));
}
#[test]
fn test_parse_escaped_string() {
let mut source = Buffer::new(b"\"hello\\\"world\"");
assert!(matches!(parse(&mut source), Ok(Node::Str(s)) if s == "hello\"world"));
}
#[test]
fn test_parse_number_integer() {
let mut source = Buffer::new(b"123");
assert!(matches!(
parse(&mut source),
Ok(Node::Number(Numeric::Integer(123)))
));
}
#[test]
fn test_parse_number_float() {
let mut source = Buffer::new(b"123.45");
assert!(
matches!(parse(&mut source), Ok(Node::Number(Numeric::Float(n))) if (n - 123.45).abs() < f64::EPSILON)
);
}
#[test]
fn test_parse_array() {
let mut source = Buffer::new(b"[1,2,3]");
match parse(&mut source) {
Ok(Node::Array(arr)) => assert_eq!(arr.len(), 3),
_ => panic!("Expected array"),
}
}
#[test]
fn test_parse_object() {
let mut source = Buffer::new(b"{\"key\":\"value\"}");
match parse(&mut source) {
Ok(Node::Object(obj)) => assert_eq!(obj.len(), 1),
_ => panic!("Expected object"),
}
}
#[test]
fn test_parse_empty_array() {
let mut source = Buffer::new(b"[]");
match parse(&mut source) {
Ok(Node::Array(arr)) => assert_eq!(arr.len(), 0),
_ => panic!("Expected empty array"),
}
}
#[test]
fn test_parse_empty_object() {
let mut source = Buffer::new(b"{}");
match parse(&mut source) {
Ok(Node::Object(obj)) => assert_eq!(obj.len(), 0),
_ => panic!("Expected empty object"),
}
}
#[test]
fn test_invalid_number() {
let mut source = Buffer::new(b"12.34.56");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_invalid_escape() {
let mut source = Buffer::new(b"\"\\x\"");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_unterminated_string() {
let mut source = Buffer::new(b"\"unterminated");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_whitespace() {
let mut source = Buffer::new(b" \t\n\r{} ");
match parse(&mut source) {
Ok(Node::Object(obj)) => assert_eq!(obj.len(), 0),
_ => panic!("Expected empty object"),
}
}
#[test]
fn test_unicode_escape() {
let mut source = Buffer::new(b"\"\\u0048\\u0065\\u006c\\u006c\\u006f\"");
assert!(matches!(parse(&mut source), Ok(Node::Str(s)) if s == "Hello"));
}
#[test]
fn test_mixed_unicode_escape() {
let mut source = Buffer::new(b"\"Hello, \\u0057\\u006f\\u0072\\u006c\\u0064!\"");
assert!(matches!(parse(&mut source), Ok(Node::Str(s)) if s == "Hello, World!"));
}
#[test]
fn test_invalid_unicode_escape() {
let mut source = Buffer::new(b"\"\\u00\"");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_invalid_unicode_hex() {
let mut source = Buffer::new(b"\"\\u00zz\"");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_parse_negative_number() {
let mut source = Buffer::new(b"-123");
assert!(matches!(
parse(&mut source),
Ok(Node::Number(Numeric::Integer(-123)))
));
let mut source = Buffer::new(b"-123.45");
assert!(
matches!(parse(&mut source), Ok(Node::Number(Numeric::Float(n))) if (n - -123.45).abs() < f64::EPSILON)
);
}
#[test]
fn test_parse_scientific_notation() {
let mut source = Buffer::new(b"1.23e+2");
assert!(
matches!(parse(&mut source), Ok(Node::Number(Numeric::Float(n))) if (n - 123.0).abs() < f64::EPSILON)
);
let mut source = Buffer::new(b"1.23E-2");
assert!(
matches!(parse(&mut source), Ok(Node::Number(Numeric::Float(n))) if (n - 0.0123).abs() < f64::EPSILON)
);
}
#[test]
fn test_parse_complex_object() {
let mut source =
Buffer::new(b"{\"array\":[1,{\"nested\":true},null],\"string\":\"value\"}");
match parse(&mut source) {
Ok(Node::Object(obj)) => {
assert_eq!(obj.len(), 2);
assert!(obj.contains_key("array"));
assert!(obj.contains_key("string"));
}
_ => panic!("Expected complex object"),
}
}
#[test]
fn test_invalid_syntax() {
let mut source = Buffer::new(b"{\"key\": value}");
assert!(parse(&mut source).is_err());
let mut source = Buffer::new(b"[1,2,]");
assert!(parse(&mut source).is_err());
let mut source = Buffer::new(b"{,}");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_string_escapes() {
let mut source = Buffer::new(b"\"\\\"\\\\\\/\\b\\f\\n\\r\\t\"");
assert!(matches!(parse(&mut source), Ok(Node::Str(s)) if s == "\"\\/\x08\x0c\n\r\t"));
}
#[test]
fn test_string_unicode_escapes() {
let mut source = Buffer::new(b"\"\\u0048\\u0065\\u006c\\u006c\\u006f\"");
assert!(matches!(parse(&mut source), Ok(Node::Str(s)) if s == "Hello"));
}
#[test]
fn test_string_unicode_escapes_mixed() {
let mut source = Buffer::new(b"\"Hello, \\u0057\\u006f\\u0072\\u006c\\u0064!\"");
assert!(matches!(parse(&mut source), Ok(Node::Str(s)) if s == "Hello, World!"));
}
#[test]
fn test_string_unicode_escapes_invalid() {
let mut source = Buffer::new(b"\"\\u00\"");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_string_unicode_escapes_invalid_hex() {
let mut source = Buffer::new(b"\"\\u00zz\"");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_max_depth_exceeded() {
let config = ParserConfig::new().with_max_depth(Some(2));
let mut source = Buffer::new(b"{\"a\":{\"b\":{\"c\":1}}}");
let result = parse_with_config(&mut source, &config);
assert!(result.is_err());
assert!(result.unwrap_err().contains("depth"));
}
#[test]
fn test_max_depth_within_limit() {
let config = ParserConfig::new().with_max_depth(Some(4));
let mut source = Buffer::new(b"{\"a\":{\"b\":{\"c\":1}}}");
let result = parse_with_config(&mut source, &config);
assert!(result.is_ok());
}
#[test]
fn test_max_string_length_exceeded() {
let config = ParserConfig::new().with_max_string_length(Some(5));
let mut source = Buffer::new(b"\"verylongstring\"");
let result = parse_with_config(&mut source, &config);
assert!(result.is_err());
assert!(result.unwrap_err().contains("string length"));
}
#[test]
fn test_max_string_length_within_limit() {
let config = ParserConfig::new().with_max_string_length(Some(10));
let mut source = Buffer::new(b"\"short\"");
let result = parse_with_config(&mut source, &config);
assert!(result.is_ok());
}
#[test]
fn test_max_array_size_exceeded() {
let config = ParserConfig::new().with_max_array_size(Some(3));
let mut source = Buffer::new(b"[1,2,3,4,5]");
let result = parse_with_config(&mut source, &config);
assert!(result.is_err());
assert!(result.unwrap_err().contains("array size"));
}
#[test]
fn test_max_array_size_within_limit() {
let config = ParserConfig::new().with_max_array_size(Some(5));
let mut source = Buffer::new(b"[1,2,3]");
let result = parse_with_config(&mut source, &config);
assert!(result.is_ok());
}
#[test]
fn test_max_object_size_exceeded() {
let config = ParserConfig::new().with_max_object_size(Some(2));
let mut source = Buffer::new(b"{\"a\":1,\"b\":2,\"c\":3}");
let result = parse_with_config(&mut source, &config);
assert!(result.is_err());
assert!(result.unwrap_err().contains("object size"));
}
#[test]
fn test_max_object_size_within_limit() {
let config = ParserConfig::new().with_max_object_size(Some(5));
let mut source = Buffer::new(b"{\"a\":1,\"b\":2}");
let result = parse_with_config(&mut source, &config);
assert!(result.is_ok());
}
#[test]
fn test_strict_config() {
let config = ParserConfig::strict();
let mut source = Buffer::new(b"[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]");
let result = parse_with_config(&mut source, &config);
assert!(result.is_err());
}
#[test]
fn test_unlimited_config() {
let config = ParserConfig::unlimited();
let mut source = Buffer::new(b"[[[[[[[[[[[[[[[[[[[[1]]]]]]]]]]]]]]]]]]]]");
let result = parse_with_config(&mut source, &config);
assert!(result.is_ok());
}
#[test]
fn test_from_str_null() {
assert!(matches!(from_str("null"), Ok(Node::None)));
}
#[test]
fn test_from_str_boolean() {
assert!(matches!(from_str("true"), Ok(Node::Boolean(true))));
assert!(matches!(from_str("false"), Ok(Node::Boolean(false))));
}
#[test]
fn test_from_str_integer() {
assert!(matches!(
from_str("42"),
Ok(Node::Number(Numeric::Integer(42)))
));
}
#[test]
fn test_from_str_negative_float() {
let result = from_str("-3.14").unwrap();
match result {
Node::Number(Numeric::Float(n)) => assert!((n - (-3.14)).abs() < f64::EPSILON),
_ => panic!("Expected float"),
}
}
#[test]
fn test_from_str_string() {
assert!(matches!(from_str("\"hello\""), Ok(Node::Str(s)) if s == "hello"));
}
#[test]
fn test_from_str_array() {
let node = from_str("[1,2,3]").unwrap();
match node {
Node::Array(arr) => assert_eq!(arr.len(), 3),
_ => panic!("Expected array"),
}
}
#[test]
fn test_from_str_object() {
let node = from_str("{\"x\":1}").unwrap();
match node {
Node::Object(obj) => assert!(obj.contains_key("x")),
_ => panic!("Expected object"),
}
}
#[test]
fn test_from_str_error() {
assert!(from_str("").is_err());
assert!(from_str("{bad}").is_err());
}
#[test]
fn test_from_bytes_null() {
assert!(matches!(from_bytes(b"null"), Ok(Node::None)));
}
#[test]
fn test_from_bytes_boolean() {
assert!(matches!(from_bytes(b"true"), Ok(Node::Boolean(true))));
assert!(matches!(from_bytes(b"false"), Ok(Node::Boolean(false))));
}
#[test]
fn test_from_bytes_integer() {
assert!(matches!(
from_bytes(b"0"),
Ok(Node::Number(Numeric::Integer(0)))
));
}
#[test]
fn test_from_bytes_string() {
assert!(matches!(from_bytes(b"\"world\""), Ok(Node::Str(s)) if s == "world"));
}
#[test]
fn test_from_bytes_array() {
let node = from_bytes(b"[true,false,null]").unwrap();
match node {
Node::Array(arr) => assert_eq!(arr.len(), 3),
_ => panic!("Expected array"),
}
}
#[test]
fn test_from_bytes_object() {
let node = from_bytes(b"{\"k\":\"v\"}").unwrap();
match node {
Node::Object(obj) => {
assert_eq!(obj.len(), 1);
assert!(matches!(obj.get("k"), Some(Node::Str(s)) if s == "v"));
}
_ => panic!("Expected object"),
}
}
#[test]
fn test_from_bytes_error() {
assert!(from_bytes(b"").is_err());
assert!(from_bytes(b"[1,2,").is_err());
}
#[test]
fn test_parse_zero() {
let mut source = Buffer::new(b"0");
assert!(matches!(
parse(&mut source),
Ok(Node::Number(Numeric::Integer(0)))
));
}
#[test]
fn test_parse_large_integer() {
let mut source = Buffer::new(b"9007199254740991");
assert!(matches!(
parse(&mut source),
Ok(Node::Number(Numeric::Integer(9007199254740991)))
));
}
#[test]
fn test_parse_scientific_no_decimal() {
let mut source = Buffer::new(b"5e2");
match parse(&mut source) {
Ok(Node::Number(Numeric::Float(n))) => assert!((n - 500.0).abs() < f64::EPSILON),
_ => panic!("Expected float"),
}
}
#[test]
fn test_parse_float_zero() {
let mut source = Buffer::new(b"0.0");
match parse(&mut source) {
Ok(Node::Number(Numeric::Float(n))) => assert!(n == 0.0),
_ => panic!("Expected float"),
}
}
#[test]
fn test_array_mixed_types() {
let node = from_bytes(b"[1,\"two\",true,null,3.14]").unwrap();
match node {
Node::Array(arr) => {
assert_eq!(arr.len(), 5);
assert!(matches!(arr[0], Node::Number(Numeric::Integer(1))));
assert!(matches!(&arr[1], Node::Str(s) if s == "two"));
assert!(matches!(arr[2], Node::Boolean(true)));
assert!(matches!(arr[3], Node::None));
match arr[4] {
Node::Number(Numeric::Float(n)) => assert!((n - 3.14).abs() < 1e-10),
_ => panic!("Expected float"),
}
}
_ => panic!("Expected array"),
}
}
#[test]
fn test_object_multiple_keys() {
let node = from_str(r#"{"a":1,"b":"two","c":true,"d":null}"#).unwrap();
match node {
Node::Object(obj) => {
assert_eq!(obj.len(), 4);
assert!(matches!(
obj.get("a"),
Some(Node::Number(Numeric::Integer(1)))
));
assert!(matches!(obj.get("b"), Some(Node::Str(s)) if s == "two"));
assert!(matches!(obj.get("c"), Some(Node::Boolean(true))));
assert!(matches!(obj.get("d"), Some(Node::None)));
}
_ => panic!("Expected object"),
}
}
#[test]
fn test_object_with_whitespace() {
let node = from_str("{ \"key\" : \"value\" }").unwrap();
match node {
Node::Object(obj) => {
assert_eq!(obj.len(), 1);
assert!(matches!(obj.get("key"), Some(Node::Str(s)) if s == "value"));
}
_ => panic!("Expected object"),
}
}
#[test]
fn test_array_with_whitespace() {
let node = from_str("[ 1 , 2 , 3 ]").unwrap();
match node {
Node::Array(arr) => assert_eq!(arr.len(), 3),
_ => panic!("Expected array"),
}
}
#[test]
fn test_empty_input_error() {
let mut source = Buffer::new(b"");
let err = parse(&mut source).unwrap_err();
assert!(!err.is_empty());
}
#[test]
fn test_missing_colon_error() {
let mut source = Buffer::new(b"{\"key\" \"value\"}");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_missing_object_end_error() {
let mut source = Buffer::new(b"{\"k\":1");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_missing_array_end_error() {
let mut source = Buffer::new(b"[1,2,3");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_unexpected_char_error() {
let mut source = Buffer::new(b"@");
assert!(parse(&mut source).is_err());
}
#[test]
fn test_depth_exactly_at_limit() {
let config = ParserConfig::new().with_max_depth(Some(3));
let mut source = Buffer::new(b"{\"a\":{\"b\":1}}");
assert!(parse_with_config(&mut source, &config).is_ok());
}
#[test]
fn test_array_size_exactly_at_limit() {
let config = ParserConfig::new().with_max_array_size(Some(3));
let mut source = Buffer::new(b"[1,2,3]");
assert!(parse_with_config(&mut source, &config).is_ok());
}
#[test]
fn test_array_size_one_over_limit() {
let config = ParserConfig::new().with_max_array_size(Some(3));
let mut source = Buffer::new(b"[1,2,3,4]");
let err = parse_with_config(&mut source, &config).unwrap_err();
assert!(err.contains("array size"));
}
#[test]
fn test_object_size_exactly_at_limit() {
let config = ParserConfig::new().with_max_object_size(Some(2));
let mut source = Buffer::new(b"{\"a\":1,\"b\":2}");
assert!(parse_with_config(&mut source, &config).is_ok());
}
#[test]
fn test_string_length_within_limit() {
let config = ParserConfig::new().with_max_string_length(Some(5));
let mut source = Buffer::new(b"\"abcd\"");
assert!(parse_with_config(&mut source, &config).is_ok());
}
#[test]
fn test_string_length_one_over_limit() {
let config = ParserConfig::new().with_max_string_length(Some(5));
let mut source = Buffer::new(b"\"toolong\"");
let err = parse_with_config(&mut source, &config).unwrap_err();
assert!(err.contains("string length"));
}
#[test]
fn test_multibyte_utf8_string() {
let node = from_str("\"\\u4e2d\\u6587\"").unwrap();
assert!(matches!(node, Node::Str(s) if s == "中文"));
}
#[test]
fn test_unicode_escape_emoji_plane() {
let mut source = Buffer::new(b"\"\\u0041\"");
assert!(matches!(parse(&mut source), Ok(Node::Str(s)) if s == "A"));
}
#[test]
fn test_nested_array_in_object() {
let node = from_str(r#"{"nums":[10,20,30]}"#).unwrap();
match node {
Node::Object(obj) => match obj.get("nums") {
Some(Node::Array(arr)) => assert_eq!(arr.len(), 3),
_ => panic!("Expected array value"),
},
_ => panic!("Expected object"),
}
}
#[test]
fn test_nested_object_in_array() {
let node = from_bytes(b"[{\"x\":1},{\"y\":2}]").unwrap();
match node {
Node::Array(arr) => {
assert_eq!(arr.len(), 2);
assert!(matches!(&arr[0], Node::Object(_)));
assert!(matches!(&arr[1], Node::Object(_)));
}
_ => panic!("Expected array"),
}
}
#[test]
fn test_parse_with_config_no_limits() {
let config = ParserConfig::new();
let mut source = Buffer::new(b"{\"deep\":[[[1,2,3]]]}");
assert!(parse_with_config(&mut source, &config).is_ok());
}
}