Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-crumb/src/json.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-crumb / src / json.rs` 403 lines ยท 12782 bytes Raw Blame History 1 //! Strict, bounded JSON reader for Directory Crumb documents. 2 //! 3 //! Stricter than the `crumb.c` reader on purpose: nesting is capped at 4 //! [`MAX_JSON_DEPTH`], duplicate object keys are refused, raw control characters 5 //! inside strings are refused, numbers follow the RFC 8259 grammar, and lone 6 //! UTF-16 surrogates in `\u` escapes are refused instead of being replaced. 7 8 use std::collections::BTreeSet; 9 10 /// Maximum container nesting depth (objects and arrays) accepted in a `.crumb`. 11 pub const MAX_JSON_DEPTH: usize = 32; 12 13 /// A parsed JSON value. Object members keep document order. 14 #[derive(Debug, Clone, PartialEq, Eq)] 15 pub enum JsonValue { 16 Null, 17 Bool(bool), 18 /// Number kept as its validated source text. 19 Number(String), 20 String(String), 21 Array(Vec), 22 Object(Vec<(String, JsonValue)>), 23 } 24 25 impl JsonValue { 26 /// Member lookup on an object; `None` for non-objects or absent keys. 27 pub fn get(&self, key: &str) -> Option<&JsonValue> { 28 match self { 29 JsonValue::Object(members) => members.iter().find(|(k, _)| k == key).map(|(_, v)| v), 30 _ => None, 31 } 32 } 33 34 pub fn as_str(&self) -> Option<&str> { 35 match self { 36 JsonValue::String(s) => Some(s), 37 _ => None, 38 } 39 } 40 } 41 42 /// Why a document is not acceptable JSON under the strict rules. 43 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 44 pub enum JsonError { 45 /// Grammar violation at the given byte offset. 46 Syntax { offset: usize }, 47 /// Nesting deeper than [`MAX_JSON_DEPTH`]. 48 TooDeep, 49 /// The same key appears twice in one object. 50 DuplicateKey { offset: usize }, 51 } 52 53 /// Parse a complete JSON document. Leading and trailing JSON whitespace is allowed. 54 pub fn parse(text: &str) -> Result { 55 let mut p = Parser { 56 b: text.as_bytes(), 57 i: 0, 58 depth: 0, 59 }; 60 p.ws(); 61 let v = p.value()?; 62 p.ws(); 63 if p.i != p.b.len() { 64 return Err(JsonError::Syntax { offset: p.i }); 65 } 66 Ok(v) 67 } 68 69 struct Parser<'a> { 70 b: &'a [u8], 71 i: usize, 72 depth: usize, 73 } 74 75 impl Parser<'_> { 76 fn err(&self) -> JsonError { 77 JsonError::Syntax { offset: self.i } 78 } 79 80 fn peek(&self) -> Option { 81 self.b.get(self.i).copied() 82 } 83 84 fn ws(&mut self) { 85 while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) { 86 self.i += 1; 87 } 88 } 89 90 fn eat(&mut self, c: u8) -> Result<(), JsonError> { 91 if self.peek() == Some(c) { 92 self.i += 1; 93 Ok(()) 94 } else { 95 Err(self.err()) 96 } 97 } 98 99 fn literal(&mut self, word: &[u8], v: JsonValue) -> Result { 100 if self.b[self.i..].starts_with(word) { 101 self.i += word.len(); 102 Ok(v) 103 } else { 104 Err(self.err()) 105 } 106 } 107 108 fn value(&mut self) -> Result { 109 match self.peek() { 110 Some(b'{') => self.container(true), 111 Some(b'[') => self.container(false), 112 Some(b'"') => Ok(JsonValue::String(self.string()?)), 113 Some(b't') => self.literal(b"true", JsonValue::Bool(true)), 114 Some(b'f') => self.literal(b"false", JsonValue::Bool(false)), 115 Some(b'n') => self.literal(b"null", JsonValue::Null), 116 Some(b'-' | b'0'..=b'9') => self.number(), 117 _ => Err(self.err()), 118 } 119 } 120 121 fn container(&mut self, object: bool) -> Result { 122 self.depth += 1; 123 if self.depth > MAX_JSON_DEPTH { 124 return Err(JsonError::TooDeep); 125 } 126 self.i += 1; 127 self.ws(); 128 let close = if object { b'}' } else { b']' }; 129 let mut members: Vec<(String, JsonValue)> = Vec::new(); 130 // Duplicate check in O(log n) per key: a 64 KiB object holds about 8,000 keys, and a 131 // linear scan per key made such a file cost O(n^2) (review finding on PR #13). 132 let mut seen: BTreeSet = BTreeSet::new(); 133 let mut items: Vec = Vec::new(); 134 if self.peek() == Some(close) { 135 self.i += 1; 136 } else { 137 loop { 138 self.ws(); 139 if object { 140 let key_offset = self.i; 141 if self.peek() != Some(b'"') { 142 return Err(self.err()); 143 } 144 let key = self.string()?; 145 if !seen.insert(key.clone()) { 146 return Err(JsonError::DuplicateKey { offset: key_offset }); 147 } 148 self.ws(); 149 self.eat(b':')?; 150 self.ws(); 151 let v = self.value()?; 152 members.push((key, v)); 153 } else { 154 let v = self.value()?; 155 items.push(v); 156 } 157 self.ws(); 158 match self.peek() { 159 Some(b',') => self.i += 1, 160 Some(c) if c == close => { 161 self.i += 1; 162 break; 163 } 164 _ => return Err(self.err()), 165 } 166 } 167 } 168 self.depth -= 1; 169 Ok(if object { 170 JsonValue::Object(members) 171 } else { 172 JsonValue::Array(items) 173 }) 174 } 175 176 fn hex4(&mut self) -> Result { 177 let s = self.b.get(self.i..self.i + 4).ok_or_else(|| self.err())?; 178 let mut v = 0u32; 179 for &c in s { 180 let d = (c as char) 181 .to_digit(16) 182 .ok_or(JsonError::Syntax { offset: self.i })?; 183 v = v * 16 + d; 184 } 185 self.i += 4; 186 Ok(v) 187 } 188 189 fn string(&mut self) -> Result { 190 self.eat(b'"')?; 191 let mut out: Vec = Vec::new(); 192 loop { 193 let c = self.peek().ok_or_else(|| self.err())?; 194 match c { 195 b'"' => { 196 self.i += 1; 197 break; 198 } 199 b'\\' => { 200 self.i += 1; 201 let e = self.peek().ok_or_else(|| self.err())?; 202 self.i += 1; 203 let ch = match e { 204 b'"' => '"', 205 b'\\' => '\\', 206 b'/' => '/', 207 b'b' => '\u{8}', 208 b'f' => '\u{c}', 209 b'n' => '\n', 210 b'r' => '\r', 211 b't' => '\t', 212 b'u' => { 213 let hi = self.hex4()?; 214 let cp = if (0xD800..0xDC00).contains(&hi) { 215 if self.b.get(self.i..self.i + 2) != Some(b"\\u") { 216 return Err(self.err()); 217 } 218 self.i += 2; 219 let lo = self.hex4()?; 220 if !(0xDC00..0xE000).contains(&lo) { 221 return Err(self.err()); 222 } 223 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00) 224 } else if (0xDC00..0xE000).contains(&hi) { 225 return Err(self.err()); 226 } else { 227 hi 228 }; 229 char::from_u32(cp).ok_or_else(|| self.err())? 230 } 231 _ => return Err(JsonError::Syntax { offset: self.i - 1 }), 232 }; 233 let mut buf = [0u8; 4]; 234 out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); 235 } 236 0x00..=0x1F => return Err(self.err()), 237 _ => { 238 out.push(c); 239 self.i += 1; 240 } 241 } 242 } 243 // Input is a &str and escapes produce valid UTF-8, so this cannot fail. 244 String::from_utf8(out).map_err(|_| self.err()) 245 } 246 247 fn digits(&mut self) -> usize { 248 let start = self.i; 249 while matches!(self.peek(), Some(b'0'..=b'9')) { 250 self.i += 1; 251 } 252 self.i - start 253 } 254 255 fn number(&mut self) -> Result { 256 let start = self.i; 257 if self.peek() == Some(b'-') { 258 self.i += 1; 259 } 260 match self.peek() { 261 Some(b'0') => self.i += 1, 262 Some(b'1'..=b'9') => { 263 self.digits(); 264 } 265 _ => return Err(self.err()), 266 } 267 if self.peek() == Some(b'.') { 268 self.i += 1; 269 if self.digits() == 0 { 270 return Err(self.err()); 271 } 272 } 273 if matches!(self.peek(), Some(b'e' | b'E')) { 274 self.i += 1; 275 if matches!(self.peek(), Some(b'+' | b'-')) { 276 self.i += 1; 277 } 278 if self.digits() == 0 { 279 return Err(self.err()); 280 } 281 } 282 let text = std::str::from_utf8(&self.b[start..self.i]).map_err(|_| self.err())?; 283 Ok(JsonValue::Number(text.to_string())) 284 } 285 } 286 287 #[cfg(test)] 288 mod tests { 289 use super::*; 290 291 #[test] 292 fn parses_nested_document() { 293 let v = 294 parse(r#" {"a": [1, -2.5e3, true, null, "x\u00e9\ud83d\ude00"], "b": {}} "#).unwrap(); 295 assert_eq!( 296 v.get("a"), 297 Some(&JsonValue::Array(vec![ 298 JsonValue::Number("1".into()), 299 JsonValue::Number("-2.5e3".into()), 300 JsonValue::Bool(true), 301 JsonValue::Null, 302 JsonValue::String("x\u{e9}\u{1F600}".into()), 303 ])) 304 ); 305 assert_eq!(v.get("b"), Some(&JsonValue::Object(vec![]))); 306 } 307 308 #[test] 309 fn refuses_duplicate_keys() { 310 assert_eq!( 311 parse(r#"{"a": 1, "a": 2}"#), 312 Err(JsonError::DuplicateKey { offset: 9 }) 313 ); 314 } 315 316 #[test] 317 fn refuses_depth_over_cap_and_accepts_cap() { 318 let ok = format!( 319 "{}{}", 320 "[".repeat(MAX_JSON_DEPTH), 321 "]".repeat(MAX_JSON_DEPTH) 322 ); 323 assert!(parse(&ok).is_ok()); 324 let deep = format!( 325 "{}{}", 326 "[".repeat(MAX_JSON_DEPTH + 1), 327 "]".repeat(MAX_JSON_DEPTH + 1) 328 ); 329 assert_eq!(parse(&deep), Err(JsonError::TooDeep)); 330 } 331 332 #[test] 333 fn refuses_loose_grammar() { 334 for bad in [ 335 "{\"a\": 01}", 336 "{\"a\": 1.}", 337 "{\"a\": +1}", 338 "{\"a\": \"\u{1}\"}", 339 "{\"a\": \"\\ud800\"}", 340 "{\"a\": \"\\x\"}", 341 "{\"a\": 1,}", 342 "{\"a\": 1} x", 343 "{'a': 1}", 344 "", 345 ] { 346 assert!( 347 matches!(parse(bad), Err(JsonError::Syntax { .. })), 348 "{bad:?}" 349 ); 350 } 351 } 352 } 353 354 #[cfg(test)] 355 mod cost_tests { 356 use super::*; 357 use std::time::{Duration, Instant}; 358 359 /// Largest-key-count object that fits in `MAX_CRUMB_BYTES` (64 KiB): short distinct keys. 360 fn widest_object() -> String { 361 let mut s = String::from("{"); 362 let mut i = 0usize; 363 loop { 364 let member = format!("\"{i:x}\":0,"); 365 if s.len() + member.len() + 1 > 64 * 1024 { 366 break; 367 } 368 s.push_str(&member); 369 i += 1; 370 } 371 s.pop(); 372 s.push('}'); 373 s 374 } 375 376 /// Regression for the O(n^2) duplicate-key scan (PR #13 review): before the fix this 377 /// document took about 170 ms in a debug build and 42 ms in release; after, about 9 ms and 378 /// 1.6 ms. The bound is the fastest of five runs, so a briefly loaded machine does not 379 /// fail it, and it sits several times away from both the old and the new cost. 380 #[test] 381 fn widest_object_parses_in_linear_time() { 382 let doc = widest_object(); 383 assert!(doc.len() <= 64 * 1024); 384 match parse(&doc).unwrap() { 385 JsonValue::Object(m) => assert!(m.len() > 7_000, "{}", m.len()), 386 other => panic!("{other:?}"), 387 } 388 let fastest = (0..5) 389 .map(|_| { 390 let start = Instant::now(); 391 parse(&doc).unwrap(); 392 start.elapsed() 393 }) 394 .min() 395 .unwrap(); 396 let bound = if cfg!(debug_assertions) { 397 Duration::from_millis(60) 398 } else { 399 Duration::from_millis(10) 400 }; 401 assert!(fastest < bound, "{fastest:?} >= {bound:?}"); 402 } 403 }