| // Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| //! Streaming JSON / JSON5-subset cursor lexing, string decoding, container | |
| //! iteration, and depth-bounded iterative value skipping. | |
| use vx_core::ascii::is_ascii_digit; | |
| use vx_core::slice::starts_with; | |
| use vx_core::str::from_utf8; | |
| use crate::types::{JsonCursor, JsonDialect, JsonError, MAX_JSON_DEPTH, NumberSpan}; | |
| #[inline(always)] | |
| const fn is_json_ws(b: u8) -> bool { | |
| b == b' ' || b == b'\t' || b == b'\r' || b == b'\n' | |
| } | |
| #[inline(always)] | |
| pub(crate) const fn hex_nibble(b: u8) -> Option<u8> { | |
| if b >= b'0' && b <= b'9' { | |
| Some(b - b'0') | |
| } else if b >= b'a' && b <= b'f' { | |
| Some(b - b'a' + 10) | |
| } else if b >= b'A' && b <= b'F' { | |
| Some(b - b'A' + 10) | |
| } else { | |
| None | |
| } | |
| } | |
| #[inline(always)] | |
| pub(crate) const fn simple_escape_byte(esc: u8) -> Option<u8> { | |
| match esc { | |
| b'"' => Some(b'"'), | |
| b'\\' => Some(b'\\'), | |
| b'/' => Some(b'/'), | |
| b'b' => Some(0x08), | |
| b'f' => Some(0x0C), | |
| b'n' => Some(b'\n'), | |
| b'r' => Some(b'\r'), | |
| b't' => Some(b'\t'), | |
| _ => None, | |
| } | |
| } | |
| /// Encode one BMP Unicode scalar value (`code` not in `0xD800..=0xDFFF`) as | |
| /// 1-3 UTF-8 bytes into `out[*len..]`, updating `*len`. | |
| #[curry::verified] | |
| pub(crate) fn encode_bmp_utf8(code: u16, out: &mut [u8], len: &mut usize) -> Result<(), JsonError> { | |
| if (0xD800..=0xDFFF).contains(&code) { | |
| return Err(JsonError::InvalidEscape); | |
| } | |
| let idx = *len; | |
| if code < 0x80 { | |
| let slot = out.get_mut(idx).ok_or(JsonError::BufferTooSmall)?; | |
| *slot = code as u8; | |
| *len = idx + 1; | |
| return Ok(()); | |
| } | |
| if code < 0x800 { | |
| let end = idx.checked_add(2).ok_or(JsonError::BufferTooSmall)?; | |
| if end > out.len() { | |
| return Err(JsonError::BufferTooSmall); | |
| } | |
| if let Some(s0) = out.get_mut(idx) { | |
| *s0 = 0xC0 | ((code >> 6) as u8); | |
| } | |
| if let Some(s1) = out.get_mut(idx + 1) { | |
| *s1 = 0x80 | ((code & 0x3F) as u8); | |
| } | |
| *len = end; | |
| return Ok(()); | |
| } | |
| let end = idx.checked_add(3).ok_or(JsonError::BufferTooSmall)?; | |
| if end > out.len() { | |
| return Err(JsonError::BufferTooSmall); | |
| } | |
| if let Some(s0) = out.get_mut(idx) { | |
| *s0 = 0xE0 | ((code >> 12) as u8); | |
| } | |
| if let Some(s1) = out.get_mut(idx + 1) { | |
| *s1 = 0x80 | (((code >> 6) & 0x3F) as u8); | |
| } | |
| if let Some(s2) = out.get_mut(idx + 2) { | |
| *s2 = 0x80 | ((code & 0x3F) as u8); | |
| } | |
| *len = end; | |
| Ok(()) | |
| } | |
| #[curry::verified] | |
| fn finish_string_utf8(out: &[u8], len: usize, out_len: &mut usize) -> Result<(), JsonError> { | |
| let slice = out.get(..len).ok_or(JsonError::BufferTooSmall)?; | |
| if from_utf8(slice).is_err() { | |
| return Err(JsonError::InvalidUtf8); | |
| } | |
| *out_len = len; | |
| Ok(()) | |
| } | |
| #[curry::verified] | |
| fn finish_bounded_string( | |
| out: &[u8], | |
| len: usize, | |
| overflow: bool, | |
| out_len: &mut usize, | |
| out_overflow: &mut bool, | |
| ) -> Result<(), JsonError> { | |
| if overflow { | |
| *out_len = 0; | |
| *out_overflow = true; | |
| return Ok(()); | |
| } | |
| let slice = out.get(..len).ok_or(JsonError::BufferTooSmall)?; | |
| if from_utf8(slice).is_err() { | |
| return Err(JsonError::InvalidUtf8); | |
| } | |
| *out_len = len; | |
| *out_overflow = false; | |
| Ok(()) | |
| } | |
| #[curry::verified] | |
| fn copy_small_bytes(src: &[u8], dst: &mut [u8], len: &mut usize) -> bool { | |
| let start = *len; | |
| let Some(end) = start.checked_add(src.len()) else { | |
| return false; | |
| }; | |
| if end > dst.len() { | |
| return false; | |
| } | |
| let mut i: usize = 0; | |
| while i < src.len() { | |
| if let (Some(&b), Some(slot)) = (src.get(i), dst.get_mut(start + i)) { | |
| *slot = b; | |
| } | |
| i += 1; | |
| } | |
| *len = end; | |
| true | |
| } | |
| impl<'a> JsonCursor<'a> { | |
| #[curry::verified] | |
| fn skip_line_comment(&mut self) { | |
| self.pos += 2; | |
| while let Some(b) = self.peek() { | |
| self.pos += 1; | |
| if b == b'\n' { | |
| break; | |
| } | |
| } | |
| } | |
| #[curry::verified] | |
| fn skip_block_comment(&mut self) -> Result<(), JsonError> { | |
| self.pos += 2; | |
| while self.pos + 1 < self.input.len() { | |
| let b0 = self.input.get(self.pos).copied(); | |
| let b1 = self.input.get(self.pos + 1).copied(); | |
| if b0 == Some(b'*') && b1 == Some(b'/') { | |
| self.pos += 2; | |
| return Ok(()); | |
| } | |
| self.pos += 1; | |
| } | |
| Err(JsonError::UnexpectedEof) | |
| } | |
| /// Skip ASCII JSON whitespace; in [`JsonDialect::Json5`], also skip `//` | |
| /// line comments and `/* ... */` block comments. | |
| #[curry::verified] | |
| pub fn skip_ws(&mut self) -> Result<(), JsonError> { | |
| while let Some(b) = self.peek() { | |
| if is_json_ws(b) { | |
| self.pos += 1; | |
| } else if b == b'/' && self.dialect == JsonDialect::Json5 { | |
| let next = self.input.get(self.pos + 1).copied(); | |
| if next == Some(b'/') { | |
| self.skip_line_comment(); | |
| } else if next == Some(b'*') { | |
| self.skip_block_comment()?; | |
| } else { | |
| break; | |
| } | |
| } else { | |
| break; | |
| } | |
| } | |
| Ok(()) | |
| } | |
| /// Skip whitespace (and comments in `Json5`) and peek at the next token byte. | |
| #[curry::verified] | |
| pub fn peek_token(&mut self) -> Result<Option<u8>, JsonError> { | |
| self.skip_ws()?; | |
| Ok(self.peek()) | |
| } | |
| /// Skip whitespace (and comments in `Json5`) and consume one expected byte. | |
| #[curry::verified] | |
| pub fn expect_byte(&mut self, expected: u8) -> Result<(), JsonError> { | |
| self.skip_ws()?; | |
| match self.peek() { | |
| Some(b) if b == expected => { | |
| self.pos += 1; | |
| Ok(()) | |
| } | |
| Some(_) => Err(JsonError::UnexpectedToken), | |
| None => Err(JsonError::UnexpectedEof), | |
| } | |
| } | |
| /// Consume exact byte sequence `lit` at `self.pos` if present, advancing | |
| /// `self.pos` and returning `true`; otherwise leave `self.pos` unchanged and | |
| /// return `false`. | |
| #[curry::verified] | |
| pub fn consume_literal(&mut self, lit: &[u8]) -> bool { | |
| if !starts_with(self.remaining(), lit) { | |
| return false; | |
| } | |
| self.pos += lit.len(); | |
| true | |
| } | |
| /// Read a JSON boolean (`true` or `false`). | |
| #[curry::verified] | |
| pub fn read_bool(&mut self) -> Result<bool, JsonError> { | |
| self.skip_ws()?; | |
| if self.consume_literal(b"true") { | |
| return Ok(true); | |
| } | |
| if self.consume_literal(b"false") { | |
| return Ok(false); | |
| } | |
| Err(JsonError::UnexpectedToken) | |
| } | |
| /// Advance past a comma or closing delimiter (`}` / `]`) inside a container. | |
| /// | |
| /// Permits trailing commas iff `self.dialect == JsonDialect::Json5`. | |
| /// Writes `true` to `*out_has_more` if another item follows, or `false` | |
| /// after consuming `close_delim`. | |
| #[curry::verified] | |
| pub fn next_container_item( | |
| &mut self, | |
| close_delim: u8, | |
| first: bool, | |
| out_has_more: &mut bool, | |
| ) -> Result<(), JsonError> { | |
| self.skip_ws()?; | |
| let b = self.peek().ok_or(JsonError::UnexpectedEof)?; | |
| if b == close_delim { | |
| self.pos += 1; | |
| *out_has_more = false; | |
| return Ok(()); | |
| } | |
| if !first { | |
| if b != b',' { | |
| return Err(JsonError::UnexpectedToken); | |
| } | |
| self.pos += 1; | |
| self.skip_ws()?; | |
| let after = self.peek().ok_or(JsonError::UnexpectedEof)?; | |
| if after == close_delim { | |
| if self.dialect == JsonDialect::Json5 { | |
| self.pos += 1; | |
| *out_has_more = false; | |
| return Ok(()); | |
| } | |
| return Err(JsonError::UnexpectedToken); | |
| } | |
| } | |
| *out_has_more = true; | |
| Ok(()) | |
| } | |
| #[curry::verified] | |
| fn read_hex_digit(&mut self) -> Result<u16, JsonError> { | |
| let b = self.peek().ok_or(JsonError::UnexpectedEof)?; | |
| self.pos += 1; | |
| let digit = hex_nibble(b).ok_or(JsonError::InvalidEscape)?; | |
| Ok(digit as u16) | |
| } | |
| #[curry::verified] | |
| pub(crate) fn read_hex4(&mut self) -> Result<u16, JsonError> { | |
| let mut acc: u16 = 0; | |
| let mut i: usize = 0; | |
| while i < 4 { | |
| let digit = self.read_hex_digit()?; | |
| acc = (acc << 4) | digit; | |
| i += 1; | |
| } | |
| Ok(acc) | |
| } | |
| #[curry::verified] | |
| pub(crate) fn read_escape_into( | |
| &mut self, | |
| out: &mut [u8], | |
| len: &mut usize, | |
| ) -> Result<(), JsonError> { | |
| let esc = self.peek().ok_or(JsonError::UnexpectedEof)?; | |
| self.pos += 1; | |
| if esc == b'u' { | |
| let code = self.read_hex4()?; | |
| return encode_bmp_utf8(code, out, len); | |
| } | |
| let decoded = simple_escape_byte(esc).ok_or(JsonError::InvalidEscape)?; | |
| let slot = out.get_mut(*len).ok_or(JsonError::BufferTooSmall)?; | |
| *slot = decoded; | |
| *len += 1; | |
| Ok(()) | |
| } | |
| #[curry::verified] | |
| fn read_escape_bounded( | |
| &mut self, | |
| out: &mut [u8], | |
| len: &mut usize, | |
| overflow: &mut bool, | |
| ) -> Result<(), JsonError> { | |
| let mut tmp = [0u8; 4]; | |
| let mut tlen: usize = 0; | |
| self.read_escape_into(&mut tmp, &mut tlen)?; | |
| if *overflow { | |
| return Ok(()); | |
| } | |
| let Some(src) = tmp.get(..tlen) else { | |
| *overflow = true; | |
| return Ok(()); | |
| }; | |
| if !copy_small_bytes(src, out, len) { | |
| *overflow = true; | |
| } | |
| Ok(()) | |
| } | |
| /// Decode a JSON string into `out`, writing its decoded UTF-8 byte length | |
| /// into `*out_len`. Returns `Err(JsonError::BufferTooSmall)` if the decoded | |
| /// string exceeds `out.len()`. | |
| #[curry::verified] | |
| pub fn read_string_into( | |
| &mut self, | |
| out: &mut [u8], | |
| out_len: &mut usize, | |
| ) -> Result<(), JsonError> { | |
| self.expect_byte(b'"')?; | |
| let mut len: usize = 0; | |
| while let Some(b) = self.peek() { | |
| self.pos += 1; | |
| if b == b'"' { | |
| return finish_string_utf8(out, len, out_len); | |
| } | |
| if b < 0x20 { | |
| return Err(JsonError::InvalidString); | |
| } | |
| if b == b'\\' { | |
| self.read_escape_into(out, &mut len)?; | |
| } else { | |
| let slot = out.get_mut(len).ok_or(JsonError::BufferTooSmall)?; | |
| *slot = b; | |
| len += 1; | |
| } | |
| } | |
| Err(JsonError::UnexpectedEof) | |
| } | |
| /// Decode a JSON string into `out`, writing its decoded UTF-8 byte length | |
| /// into `*out_len`. If the decoded string exceeds `out.len()`, drains the | |
| /// remainder of the string so the cursor stays synchronized and sets | |
| /// `*out_overflow = true`, `*out_len = 0`. | |
| #[curry::verified] | |
| pub fn read_string_bounded( | |
| &mut self, | |
| out: &mut [u8], | |
| out_len: &mut usize, | |
| out_overflow: &mut bool, | |
| ) -> Result<(), JsonError> { | |
| self.expect_byte(b'"')?; | |
| let mut len: usize = 0; | |
| let mut overflow = false; | |
| while let Some(b) = self.peek() { | |
| self.pos += 1; | |
| if b == b'"' { | |
| return finish_bounded_string(out, len, overflow, out_len, out_overflow); | |
| } | |
| if b < 0x20 { | |
| return Err(JsonError::InvalidString); | |
| } | |
| if b == b'\\' { | |
| self.read_escape_bounded(out, &mut len, &mut overflow)?; | |
| } else if !overflow { | |
| if let Some(slot) = out.get_mut(len) { | |
| *slot = b; | |
| len += 1; | |
| } else { | |
| overflow = true; | |
| } | |
| } | |
| } | |
| Err(JsonError::UnexpectedEof) | |
| } | |
| /// Validate and skip one JSON string without copying it. | |
| /// | |
| /// Accepts valid 4-hex `\uXXXX` escapes (including UTF-16 surrogate pairs | |
| /// inside skipped non-target strings) while rejecting invalid escapes and | |
| /// unescaped control characters (`< 0x20`). | |
| #[curry::verified] | |
| pub fn skip_string(&mut self) -> Result<(), JsonError> { | |
| self.expect_byte(b'"')?; | |
| while let Some(b) = self.peek() { | |
| self.pos += 1; | |
| if b == b'"' { | |
| return Ok(()); | |
| } | |
| if b < 0x20 { | |
| return Err(JsonError::InvalidString); | |
| } | |
| if b == b'\\' { | |
| let esc = self.peek().ok_or(JsonError::UnexpectedEof)?; | |
| self.pos += 1; | |
| if esc == b'u' { | |
| let _ = self.read_hex4()?; | |
| } else if simple_escape_byte(esc).is_none() { | |
| return Err(JsonError::InvalidEscape); | |
| } | |
| } | |
| } | |
| Err(JsonError::UnexpectedEof) | |
| } | |
| #[curry::verified] | |
| fn skip_scalar(&mut self, b: u8) -> Result<(), JsonError> { | |
| if b == b'"' { | |
| return self.skip_string(); | |
| } | |
| if b == b't' { | |
| return if self.consume_literal(b"true") { | |
| Ok(()) | |
| } else { | |
| Err(JsonError::UnexpectedToken) | |
| }; | |
| } | |
| if b == b'f' { | |
| return if self.consume_literal(b"false") { | |
| Ok(()) | |
| } else { | |
| Err(JsonError::UnexpectedToken) | |
| }; | |
| } | |
| if b == b'n' { | |
| return if self.consume_literal(b"null") { | |
| Ok(()) | |
| } else { | |
| Err(JsonError::UnexpectedToken) | |
| }; | |
| } | |
| if b == b'-' || is_ascii_digit(b) { | |
| let mut span = NumberSpan { start: 0, end: 0, is_float: false }; | |
| return self.scan_number_span(&mut span); | |
| } | |
| Err(JsonError::UnexpectedToken) | |
| } | |
| #[curry::verified] | |
| fn advance_skip_containers( | |
| &mut self, | |
| stack: &[bool; MAX_JSON_DEPTH], | |
| first: &mut [bool; MAX_JSON_DEPTH], | |
| depth: &mut usize, | |
| ) -> Result<bool, JsonError> { | |
| while *depth > 0 { | |
| let top = *depth - 1; | |
| let is_obj = *stack.get(top).ok_or(JsonError::DepthExceeded)?; | |
| let is_first = *first.get(top).ok_or(JsonError::DepthExceeded)?; | |
| let close = if is_obj { b'}' } else { b']' }; | |
| let mut has_more = false; | |
| self.next_container_item(close, is_first, &mut has_more)?; | |
| if has_more { | |
| if let Some(f) = first.get_mut(top) { | |
| *f = false; | |
| } | |
| if is_obj { | |
| self.skip_string()?; | |
| self.expect_byte(b':')?; | |
| } | |
| return Ok(true); | |
| } | |
| *depth -= 1; | |
| } | |
| Ok(false) | |
| } | |
| /// Iteratively skip an arbitrary JSON value with strict nesting depth bound | |
| /// [`MAX_JSON_DEPTH`] (`16`, zero recursion). | |
| #[curry::verified] | |
| pub fn skip_value(&mut self) -> Result<(), JsonError> { | |
| // `stack[i]`: true = object (`}`), false = array (`]`). | |
| let mut stack = [false; MAX_JSON_DEPTH]; | |
| let mut first = [true; MAX_JSON_DEPTH]; | |
| let mut depth: usize = 0; | |
| loop { | |
| let b = self.peek_token()?.ok_or(JsonError::UnexpectedEof)?; | |
| if b == b'{' || b == b'[' { | |
| let is_obj = b == b'{'; | |
| let (Some(st), Some(fr)) = (stack.get_mut(depth), first.get_mut(depth)) else { | |
| return Err(JsonError::DepthExceeded); | |
| }; | |
| *st = is_obj; | |
| *fr = true; | |
| depth += 1; | |
| self.pos += 1; | |
| } else { | |
| self.skip_scalar(b)?; | |
| } | |
| if !self.advance_skip_containers(&stack, &mut first, &mut depth)? { | |
| return Ok(()); | |
| } | |
| } | |
| } | |
| } |