Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / gtfs_ingest / src / json.rs
json.rs374 lines · 13.0 KiBRaw
| 1 | //! A minimal JSON reader, for the transit registries. |
| 2 | //! |
| 3 | //! `gtfs_ingest` has **zero** dependencies, which is what lets it build and resolve |
| 4 | //! offline on any box. The Transitous and transitland-atlas registries are JSON, so |
| 5 | //! reading them needs a parser; pulling in serde for two file formats would trade |
| 6 | //! that property away. |
| 7 | //! |
| 8 | //! Deliberately small, and enough for exactly this job: |
| 9 | //! |
| 10 | //! * Objects, arrays, strings, numbers, `true`/`false`/`null`. |
| 11 | //! * String escapes including `\uXXXX`, with surrogate pairs joined -- agency names |
| 12 | //! in these registries are full Unicode. |
| 13 | //! * Numbers are kept as `f64`; nothing here reads one, but discarding them would |
| 14 | //! make the parser reject documents it should accept. |
| 15 | //! |
| 16 | //! What it does not do: streaming, duplicate-key policy, or any error recovery. A |
| 17 | //! malformed registry is an error with a byte offset, not a partial parse. |
| 18 | |
| 19 | use std::collections::BTreeMap; |
| 20 | |
| 21 | #[derive(Debug, Clone, PartialEq)] |
| 22 | pub enum Json { |
| 23 | Null, |
| 24 | Bool(bool), |
| 25 | Number(f64), |
| 26 | String(String), |
| 27 | Array(Vec<Json>), |
| 28 | Object(BTreeMap<String, Json>), |
| 29 | } |
| 30 | |
| 31 | impl Json { |
| 32 | /// A member of an object, or `None` when this is not an object or the key is |
| 33 | /// absent. Chains, so `v.get("urls").and_then(|u| u.get("static_current"))` |
| 34 | /// reads the way the document does. |
| 35 | pub fn get(&self, key: &str) -> Option<&Json> { |
| 36 | match self { |
| 37 | Json::Object(m) => m.get(key), |
| 38 | _ => None, |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | pub fn as_str(&self) -> Option<&str> { |
| 43 | match self { |
| 44 | Json::String(s) => Some(s.as_str()), |
| 45 | _ => None, |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// The elements of an array, or an empty slice. A registry field that is |
| 50 | /// sometimes a single value and sometimes a list is common enough that callers |
| 51 | /// should not have to branch. |
| 52 | pub fn as_array(&self) -> &[Json] { |
| 53 | match self { |
| 54 | Json::Array(v) => v.as_slice(), |
| 55 | _ => &[], |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /// Truthiness in the sense the registries use: present, and not `null`, `false`, |
| 60 | /// an empty string, or an empty container. |
| 61 | pub fn is_truthy(&self) -> bool { |
| 62 | match self { |
| 63 | Json::Null => false, |
| 64 | Json::Bool(b) => *b, |
| 65 | Json::Number(n) => *n != 0.0, |
| 66 | Json::String(s) => !s.is_empty(), |
| 67 | Json::Array(v) => !v.is_empty(), |
| 68 | Json::Object(m) => !m.is_empty(), |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | pub fn parse(text: &str) -> Result<Json, String> { |
| 74 | let b = text.as_bytes(); |
| 75 | let mut i = 0usize; |
| 76 | let v = value(b, &mut i)?; |
| 77 | skip_ws(b, &mut i); |
| 78 | if i != b.len() { |
| 79 | return Err(format!("trailing bytes at offset {i}")); |
| 80 | } |
| 81 | Ok(v) |
| 82 | } |
| 83 | |
| 84 | fn skip_ws(b: &[u8], i: &mut usize) { |
| 85 | while *i < b.len() && matches!(b[*i], b' ' | b'\t' | b'\n' | b'\r') { |
| 86 | *i += 1; |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | fn expect(b: &[u8], i: &mut usize, c: u8) -> Result<(), String> { |
| 91 | skip_ws(b, i); |
| 92 | if b.get(*i) != Some(&c) { |
| 93 | return Err(format!( |
| 94 | "expected '{}' at offset {i}, found {:?}", |
| 95 | c as char, |
| 96 | b.get(*i).map(|x| *x as char) |
| 97 | )); |
| 98 | } |
| 99 | *i += 1; |
| 100 | Ok(()) |
| 101 | } |
| 102 | |
| 103 | fn value(b: &[u8], i: &mut usize) -> Result<Json, String> { |
| 104 | skip_ws(b, i); |
| 105 | match b.get(*i) { |
| 106 | None => Err(format!("unexpected end of input at offset {i}")), |
| 107 | Some(b'{') => { |
| 108 | *i += 1; |
| 109 | let mut map = BTreeMap::new(); |
| 110 | skip_ws(b, i); |
| 111 | if b.get(*i) == Some(&b'}') { |
| 112 | *i += 1; |
| 113 | return Ok(Json::Object(map)); |
| 114 | } |
| 115 | loop { |
| 116 | skip_ws(b, i); |
| 117 | let key = string(b, i)?; |
| 118 | expect(b, i, b':')?; |
| 119 | map.insert(key, value(b, i)?); |
| 120 | skip_ws(b, i); |
| 121 | match b.get(*i) { |
| 122 | Some(b',') => *i += 1, |
| 123 | Some(b'}') => { |
| 124 | *i += 1; |
| 125 | return Ok(Json::Object(map)); |
| 126 | } |
| 127 | other => { |
| 128 | return Err(format!( |
| 129 | "expected ',' or '}}' at offset {i}, found {:?}", |
| 130 | other.map(|x| *x as char) |
| 131 | )) |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | Some(b'[') => { |
| 137 | *i += 1; |
| 138 | let mut items = Vec::new(); |
| 139 | skip_ws(b, i); |
| 140 | if b.get(*i) == Some(&b']') { |
| 141 | *i += 1; |
| 142 | return Ok(Json::Array(items)); |
| 143 | } |
| 144 | loop { |
| 145 | items.push(value(b, i)?); |
| 146 | skip_ws(b, i); |
| 147 | match b.get(*i) { |
| 148 | Some(b',') => *i += 1, |
| 149 | Some(b']') => { |
| 150 | *i += 1; |
| 151 | return Ok(Json::Array(items)); |
| 152 | } |
| 153 | other => { |
| 154 | return Err(format!( |
| 155 | "expected ',' or ']' at offset {i}, found {:?}", |
| 156 | other.map(|x| *x as char) |
| 157 | )) |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | Some(b'"') => Ok(Json::String(string(b, i)?)), |
| 163 | Some(b't') => literal(b, i, "true").map(|_| Json::Bool(true)), |
| 164 | Some(b'f') => literal(b, i, "false").map(|_| Json::Bool(false)), |
| 165 | Some(b'n') => literal(b, i, "null").map(|_| Json::Null), |
| 166 | Some(_) => number(b, i), |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | fn literal(b: &[u8], i: &mut usize, want: &str) -> Result<(), String> { |
| 171 | if b[*i..].starts_with(want.as_bytes()) { |
| 172 | *i += want.len(); |
| 173 | Ok(()) |
| 174 | } else { |
| 175 | Err(format!("expected '{want}' at offset {i}")) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | fn number(b: &[u8], i: &mut usize) -> Result<Json, String> { |
| 180 | let start = *i; |
| 181 | while *i < b.len() && matches!(b[*i], b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E') { |
| 182 | *i += 1; |
| 183 | } |
| 184 | if *i == start { |
| 185 | return Err(format!("not a value at offset {start}")); |
| 186 | } |
| 187 | std::str::from_utf8(&b[start..*i]) |
| 188 | .ok() |
| 189 | .and_then(|s| s.parse().ok()) |
| 190 | .map(Json::Number) |
| 191 | .ok_or_else(|| format!("bad number at offset {start}")) |
| 192 | } |
| 193 | |
| 194 | fn string(b: &[u8], i: &mut usize) -> Result<String, String> { |
| 195 | expect(b, i, b'"')?; |
| 196 | let mut out = String::new(); |
| 197 | loop { |
| 198 | match b.get(*i) { |
| 199 | None => return Err(format!("unterminated string at offset {i}")), |
| 200 | Some(b'"') => { |
| 201 | *i += 1; |
| 202 | return Ok(out); |
| 203 | } |
| 204 | Some(b'\\') => { |
| 205 | *i += 1; |
| 206 | match b.get(*i) { |
| 207 | Some(b'"') => out.push('"'), |
| 208 | Some(b'\\') => out.push('\\'), |
| 209 | Some(b'/') => out.push('/'), |
| 210 | Some(b'b') => out.push('\u{8}'), |
| 211 | Some(b'f') => out.push('\u{c}'), |
| 212 | Some(b'n') => out.push('\n'), |
| 213 | Some(b'r') => out.push('\r'), |
| 214 | Some(b't') => out.push('\t'), |
| 215 | Some(b'u') => { |
| 216 | let hi = hex4(b, i)?; |
| 217 | // A high surrogate must be followed by its low half, or the |
| 218 | // agency name comes out as two replacement characters. |
| 219 | if (0xD800..0xDC00).contains(&hi) { |
| 220 | if b.get(*i + 1) == Some(&b'\\') && b.get(*i + 2) == Some(&b'u') { |
| 221 | *i += 2; |
| 222 | let lo = hex4(b, i)?; |
| 223 | if (0xDC00..0xE000).contains(&lo) { |
| 224 | let c = 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00); |
| 225 | out.push(char::from_u32(c).unwrap_or('\u{fffd}')); |
| 226 | } else { |
| 227 | out.push('\u{fffd}'); |
| 228 | out.push(char::from_u32(lo).unwrap_or('\u{fffd}')); |
| 229 | } |
| 230 | } else { |
| 231 | out.push('\u{fffd}'); |
| 232 | } |
| 233 | } else { |
| 234 | out.push(char::from_u32(hi).unwrap_or('\u{fffd}')); |
| 235 | } |
| 236 | } |
| 237 | other => { |
| 238 | return Err(format!( |
| 239 | "bad escape at offset {i}: {:?}", |
| 240 | other.map(|x| *x as char) |
| 241 | )) |
| 242 | } |
| 243 | } |
| 244 | *i += 1; |
| 245 | } |
| 246 | Some(_) => { |
| 247 | // Copy the whole UTF-8 run up to the next escape or quote in one go. |
| 248 | let start = *i; |
| 249 | while *i < b.len() && b[*i] != b'"' && b[*i] != b'\\' { |
| 250 | *i += 1; |
| 251 | } |
| 252 | out.push_str( |
| 253 | std::str::from_utf8(&b[start..*i]) |
| 254 | .map_err(|_| format!("invalid UTF-8 at offset {start}"))?, |
| 255 | ); |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | /// Read the four hex digits after a `\u`, leaving `i` on the last of them. |
| 262 | fn hex4(b: &[u8], i: &mut usize) -> Result<u32, String> { |
| 263 | let start = *i + 1; |
| 264 | let end = start + 4; |
| 265 | if end > b.len() { |
| 266 | return Err(format!("truncated \\u escape at offset {start}")); |
| 267 | } |
| 268 | let s = std::str::from_utf8(&b[start..end]).map_err(|_| format!("bad \\u at {start}"))?; |
| 269 | let v = u32::from_str_radix(s, 16).map_err(|_| format!("bad \\u escape at offset {start}"))?; |
| 270 | *i = end - 1; |
| 271 | Ok(v) |
| 272 | } |
| 273 | |
| 274 | #[cfg(test)] |
| 275 | mod tests { |
| 276 | use super::*; |
| 277 | |
| 278 | #[test] |
| 279 | fn reads_the_shapes_a_registry_uses() { |
| 280 | let v = parse( |
| 281 | r#"{"sources":[{"name":"SF-bayarea","transitland-atlas-id":"f-9q9-bayarea", |
| 282 | "url":"https://example.com/gtfs.zip","skip":false,"spec":"gtfs"}]}"#, |
| 283 | ) |
| 284 | .unwrap(); |
| 285 | let s = &v.get("sources").unwrap().as_array()[0]; |
| 286 | assert_eq!(s.get("name").unwrap().as_str(), Some("SF-bayarea")); |
| 287 | assert_eq!(s.get("transitland-atlas-id").unwrap().as_str(), Some("f-9q9-bayarea")); |
| 288 | assert!(!s.get("skip").unwrap().is_truthy()); |
| 289 | assert_eq!(v.get("nope"), None); |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn reads_a_nested_atlas_entry() { |
| 294 | let v = parse( |
| 295 | r#"{"feeds":[{"id":"f-9q9-bayarea","spec":"gtfs", |
| 296 | "urls":{"static_current":"https://a/x.zip", |
| 297 | "static_historic":["https://a/old.zip","https://a/older.zip"]}, |
| 298 | "authorization":{"type":"query_param"}}]}"#, |
| 299 | ) |
| 300 | .unwrap(); |
| 301 | let f = &v.get("feeds").unwrap().as_array()[0]; |
| 302 | let urls = f.get("urls").unwrap(); |
| 303 | assert_eq!(urls.get("static_current").unwrap().as_str(), Some("https://a/x.zip")); |
| 304 | assert_eq!(urls.get("static_historic").unwrap().as_array().len(), 2); |
| 305 | assert!(f.get("authorization").unwrap().is_truthy()); |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn handles_escapes_and_unicode() { |
| 310 | let v = parse(r#"{"a":"quote\" back\\ slash\/ nl\n tab\t","b":"\u00e9\u4e2d"}"#).unwrap(); |
| 311 | assert_eq!(v.get("a").unwrap().as_str(), Some("quote\" back\\ slash/ nl\n tab\t")); |
| 312 | assert_eq!(v.get("b").unwrap().as_str(), Some("é中")); |
| 313 | } |
| 314 | |
| 315 | #[test] |
| 316 | fn joins_surrogate_pairs() { |
| 317 | // An emoji in an agency name, which is not hypothetical. |
| 318 | let v = parse(r#"{"a":"\ud83d\ude80"}"#).unwrap(); |
| 319 | assert_eq!(v.get("a").unwrap().as_str(), Some("🚀")); |
| 320 | // A lone high surrogate becomes a replacement character rather than an error. |
| 321 | let v = parse(r#"{"a":"\ud83dx"}"#).unwrap(); |
| 322 | assert_eq!(v.get("a").unwrap().as_str(), Some("\u{fffd}x")); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn numbers_booleans_and_null_round_trip_enough_to_not_reject_a_document() { |
| 327 | let v = parse(r#"{"a":1,"b":-2.5,"c":1e3,"d":true,"e":false,"f":null}"#).unwrap(); |
| 328 | assert_eq!(v.get("a"), Some(&Json::Number(1.0))); |
| 329 | assert_eq!(v.get("b"), Some(&Json::Number(-2.5))); |
| 330 | assert_eq!(v.get("c"), Some(&Json::Number(1000.0))); |
| 331 | assert!(v.get("d").unwrap().is_truthy()); |
| 332 | assert!(!v.get("e").unwrap().is_truthy()); |
| 333 | assert!(!v.get("f").unwrap().is_truthy()); |
| 334 | } |
| 335 | |
| 336 | #[test] |
| 337 | fn whitespace_and_empty_containers_are_fine() { |
| 338 | assert_eq!(parse(" { } ").unwrap(), Json::Object(BTreeMap::new())); |
| 339 | assert_eq!(parse("[ ]").unwrap(), Json::Array(vec![])); |
| 340 | assert_eq!( |
| 341 | parse("{\n\t\"a\" : [ 1 , 2 ]\n}").unwrap().get("a").unwrap().as_array().len(), |
| 342 | 2 |
| 343 | ); |
| 344 | } |
| 345 | |
| 346 | #[test] |
| 347 | fn malformed_input_is_an_error_with_an_offset_not_a_partial_parse() { |
| 348 | for bad in [ |
| 349 | "", |
| 350 | "{", |
| 351 | "{\"a\"}", |
| 352 | "{\"a\":}", |
| 353 | "{\"a\":1,}", |
| 354 | "[1,]", |
| 355 | "\"unterminated", |
| 356 | "{\"a\":1} trailing", |
| 357 | "tru", |
| 358 | "{\"a\":\"\\q\"}", |
| 359 | "{\"a\":\"\\u00\"}", |
| 360 | ] { |
| 361 | let err = parse(bad).unwrap_err(); |
| 362 | assert!(!err.is_empty(), "{bad:?} must report something"); |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | #[test] |
| 367 | fn accessors_do_not_panic_on_the_wrong_shape() { |
| 368 | let v = Json::String("x".into()); |
| 369 | assert_eq!(v.get("a"), None); |
| 370 | assert!(v.as_array().is_empty()); |
| 371 | assert_eq!(Json::Null.as_str(), None); |
| 372 | assert!(Json::Number(1.0).as_array().is_empty()); |
| 373 | } |
| 374 | } |