Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
261 lines
9.1 KiB
Rust
261 lines
9.1 KiB
Rust
//! Methods of `Parser`: `ws`, `err`, `lit`, `hex4` and 10 more.
|
|
//! Methods of `Json`: `get`, `req`, `str`, `uint` and 4 more. Functions: `simple_escape`, `parse_json`.
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
impl Parser<'_> {
|
|
pub(super) fn ws(&mut self) {
|
|
while self.at < self.b.len() && matches!(self.b[self.at], b' ' | b'\t' | b'\n' | b'\r') {
|
|
self.at += 1;
|
|
}
|
|
}
|
|
pub(super) fn err<T>(&self, what: &str) -> Result<T, String> {
|
|
Err(format!("JSON error at byte {}: {what}", self.at))
|
|
}
|
|
pub(super) fn lit(&mut self, word: &str, v: Json) -> Result<Json, String> {
|
|
if self.b[self.at..].starts_with(word.as_bytes()) {
|
|
self.at += word.len();
|
|
Ok(v)
|
|
} else {
|
|
self.err("unknown literal")
|
|
}
|
|
}
|
|
pub(super) fn hex4(&mut self) -> Result<u32, String> {
|
|
if self.at + 4 > self.b.len() {
|
|
return self.err("short \\u escape");
|
|
}
|
|
let s = std::str::from_utf8(&self.b[self.at..self.at + 4]).map_err(|_| "bad \\u escape".to_owned())?;
|
|
let v = u32::from_str_radix(s, 16).map_err(|_| "bad \\u escape".to_owned())?;
|
|
self.at += 4;
|
|
Ok(v)
|
|
}
|
|
pub(super) fn string(&mut self) -> Result<String, String> {
|
|
self.at += 1;
|
|
let mut out: Vec<u8> = Vec::new();
|
|
loop {
|
|
let Some(&c) = self.b.get(self.at) else { return self.err("unterminated string") };
|
|
self.at += 1;
|
|
match c {
|
|
b'"' => return String::from_utf8(out).map_err(|_| "string is not UTF-8".to_owned()),
|
|
b'\\' => {
|
|
let ch = self.escape()?;
|
|
let mut buf = [0u8; 4];
|
|
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
|
|
}
|
|
0..=0x1f => return self.err("control character in string"),
|
|
_ => out.push(c),
|
|
}
|
|
}
|
|
}
|
|
/// The character after a backslash (the cursor is on the escape letter).
|
|
fn escape(&mut self) -> Result<char, String> {
|
|
let Some(&e) = self.b.get(self.at) else { return self.err("unterminated escape") };
|
|
self.at += 1;
|
|
if e == b'u' {
|
|
return self.unicode_escape();
|
|
}
|
|
match simple_escape(e) {
|
|
Some(ch) => Ok(ch),
|
|
None => self.err("unknown escape"),
|
|
}
|
|
}
|
|
fn unicode_escape(&mut self) -> Result<char, String> {
|
|
let hi = self.hex4()?;
|
|
let cp = if (0xD800..0xDC00).contains(&hi) { self.low_surrogate(hi)? } else { hi };
|
|
match char::from_u32(cp) {
|
|
Some(c) => Ok(c),
|
|
None => self.err("lone surrogate"),
|
|
}
|
|
}
|
|
/// The code point of a surrogate pair whose high half `hi` was read.
|
|
fn low_surrogate(&mut self, hi: u32) -> Result<u32, String> {
|
|
if !self.b[self.at..].starts_with(b"\\u") {
|
|
return self.err("lone surrogate");
|
|
}
|
|
self.at += 2;
|
|
let lo = self.hex4()?;
|
|
if !(0xDC00..0xE000).contains(&lo) {
|
|
return self.err("lone surrogate");
|
|
}
|
|
Ok(0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00))
|
|
}
|
|
pub(super) fn number(&mut self) -> Result<Json, String> {
|
|
let start = self.at;
|
|
while self.at < self.b.len() && matches!(self.b[self.at], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') {
|
|
self.at += 1;
|
|
}
|
|
let text = std::str::from_utf8(&self.b[start..self.at]).map_err(|_| "bad number".to_owned())?;
|
|
if text.parse::<f64>().is_err() {
|
|
return self.err("bad number");
|
|
}
|
|
Ok(Json::Num(text.to_owned()))
|
|
}
|
|
pub(super) fn value(&mut self, depth: usize) -> Result<Json, String> {
|
|
if depth > 32 {
|
|
return self.err("nesting deeper than 32");
|
|
}
|
|
self.ws();
|
|
match self.b.get(self.at) {
|
|
None => self.err("unexpected end"),
|
|
Some(b'{') => self.object(depth),
|
|
Some(b'[') => self.array(depth),
|
|
Some(b'"') => self.string().map(Json::Str),
|
|
Some(b't') => self.lit("true", Json::Bool(true)),
|
|
Some(b'f') => self.lit("false", Json::Bool(false)),
|
|
Some(b'n') => self.lit("null", Json::Null),
|
|
Some(b'-' | b'0'..=b'9') => self.number(),
|
|
Some(_) => self.err("unexpected character"),
|
|
}
|
|
}
|
|
fn object(&mut self, depth: usize) -> Result<Json, String> {
|
|
self.at += 1;
|
|
let mut items: Vec<(String, Json)> = Vec::new();
|
|
self.ws();
|
|
if self.b.get(self.at) == Some(&b'}') {
|
|
self.at += 1;
|
|
return Ok(Json::Obj(items));
|
|
}
|
|
loop {
|
|
let member = self.member(&items, depth)?;
|
|
items.push(member);
|
|
if self.separator(b'}', "',' or '}' expected")? {
|
|
return Ok(Json::Obj(items));
|
|
}
|
|
}
|
|
}
|
|
/// One `"key": value` pair of an object; a repeated key is refused.
|
|
fn member(&mut self, items: &[(String, Json)], depth: usize) -> Result<(String, Json), String> {
|
|
self.ws();
|
|
if self.b.get(self.at) != Some(&b'"') {
|
|
return self.err("object key expected");
|
|
}
|
|
let key = self.string()?;
|
|
if items.iter().any(|(k, _)| *k == key) {
|
|
return self.err(&format!("duplicate key {key:?}"));
|
|
}
|
|
self.ws();
|
|
if self.b.get(self.at) != Some(&b':') {
|
|
return self.err("':' expected");
|
|
}
|
|
self.at += 1;
|
|
let v = self.value(depth + 1)?;
|
|
Ok((key, v))
|
|
}
|
|
fn array(&mut self, depth: usize) -> Result<Json, String> {
|
|
self.at += 1;
|
|
let mut items = Vec::new();
|
|
self.ws();
|
|
if self.b.get(self.at) == Some(&b']') {
|
|
self.at += 1;
|
|
return Ok(Json::Arr(items));
|
|
}
|
|
loop {
|
|
items.push(self.value(depth + 1)?);
|
|
if self.separator(b']', "',' or ']' expected")? {
|
|
return Ok(Json::Arr(items));
|
|
}
|
|
}
|
|
}
|
|
/// After an element: a comma continues (false), the closing byte ends the container (true), anything else is
|
|
/// `expected`.
|
|
fn separator(&mut self, close: u8, expected: &str) -> Result<bool, String> {
|
|
self.ws();
|
|
match self.b.get(self.at) {
|
|
Some(b',') => {
|
|
self.at += 1;
|
|
Ok(false)
|
|
}
|
|
Some(&c) if c == close => {
|
|
self.at += 1;
|
|
Ok(true)
|
|
}
|
|
_ => self.err(expected),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The character of a single-letter escape (`\n`, `\t`, ...), None for an unknown letter.
|
|
fn simple_escape(e: u8) -> Option<char> {
|
|
Some(match e {
|
|
b'"' => '"',
|
|
b'\\' => '\\',
|
|
b'/' => '/',
|
|
b'b' => '\u{8}',
|
|
b'f' => '\u{c}',
|
|
b'n' => '\n',
|
|
b'r' => '\r',
|
|
b't' => '\t',
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
pub(super) fn parse_json(bytes: &[u8]) -> Result<Json, String> {
|
|
let mut p = Parser { b: bytes, at: 0 };
|
|
let v = p.value(0)?;
|
|
p.ws();
|
|
if p.at != bytes.len() {
|
|
return p.err("trailing data");
|
|
}
|
|
Ok(v)
|
|
}
|
|
|
|
impl Json {
|
|
pub(super) fn get(&self, key: &str) -> Option<&Json> {
|
|
match self {
|
|
Json::Obj(items) => items.iter().find(|(k, _)| k == key).map(|(_, v)| v),
|
|
_ => None,
|
|
}
|
|
}
|
|
pub(super) fn req(&self, key: &str) -> Result<&Json, String> {
|
|
self.get(key).ok_or_else(|| format!("missing key {key:?}"))
|
|
}
|
|
pub(super) fn str(&self, key: &str) -> Result<&str, String> {
|
|
match self.req(key)? {
|
|
Json::Str(s) => Ok(s),
|
|
_ => Err(format!("key {key:?} is not a string")),
|
|
}
|
|
}
|
|
pub(super) fn uint(&self, key: &str) -> Result<u64, String> {
|
|
match self.req(key)? {
|
|
Json::Num(n) => n.parse::<u64>().map_err(|_| format!("key {key:?} is not an unsigned integer")),
|
|
_ => Err(format!("key {key:?} is not a number")),
|
|
}
|
|
}
|
|
pub(super) fn float(&self, key: &str) -> Result<f64, String> {
|
|
match self.req(key)? {
|
|
Json::Num(n) => n
|
|
.parse::<f64>()
|
|
.ok()
|
|
.filter(|v| v.is_finite())
|
|
.ok_or_else(|| format!("key {key:?} is not a finite number")),
|
|
_ => Err(format!("key {key:?} is not a number")),
|
|
}
|
|
}
|
|
/// A number, or None for a JSON null (the C++ writer prints null for a value it could not measure).
|
|
pub(super) fn float_or_null(&self, key: &str) -> Result<Option<f64>, String> {
|
|
match self.req(key)? {
|
|
Json::Null => Ok(None),
|
|
_ => self.float(key).map(Some),
|
|
}
|
|
}
|
|
pub(super) fn flag(&self, key: &str) -> Result<bool, String> {
|
|
match self.req(key)? {
|
|
Json::Bool(b) => Ok(*b),
|
|
_ => Err(format!("key {key:?} is not a boolean")),
|
|
}
|
|
}
|
|
pub(super) fn array(&self, key: &str) -> Result<&[Json], String> {
|
|
match self.req(key)? {
|
|
Json::Arr(a) => Ok(a),
|
|
_ => Err(format!("key {key:?} is not an array")),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl InHeader {
|
|
pub(super) fn input_at(&self) -> usize {
|
|
IN_HEADER + self.gate + self.up + self.down_bytes
|
|
}
|
|
}
|