interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / rust / crates / interplane-conformance / src / ojson.rs
| 1 | //! JSON that keeps object key order, and a writer with the byte form of Python's `json.dumps`. |
| 2 | //! |
| 3 | //! The corpus tools (fixture validator, subset rule, adapter runner) were first written in Python. |
| 4 | //! Two of their outputs depend on details `serde_json::Value` does not keep: the order of keys in an |
| 5 | //! object (the fixture validator checks it; the subset rule writes tool-call arguments in the |
| 6 | //! order of the translation table) and the exact text `json.dumps` produces (ASCII escapes, |
| 7 | //! `", "` and `": "` separators, Python float spelling). [`OJson`] keeps the order as read, and |
| 8 | //! [`dumps`] reproduces that text, so the frozen files those tools wrote stay byte-identical. |
| 9 | //! |
| 10 | //! Parsing is `serde_json` with `float_roundtrip`, so decimals parse to the nearest double as |
| 11 | //! Python's do. One known limit: an integer outside the 64-bit range parses as a float, where |
| 12 | //! Python kept it exact. No corpus file holds one. `serde_json`'s `arbitrary_precision` would lift |
| 13 | //! the limit but changes `serde_json::Number` for every crate in the workspace, so it is not used. |
| 14 | use std::fmt; |
| 15 | |
| 16 | use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor}; |
| 17 | use serde_json::{Map, Number, Value}; |
| 18 | |
| 19 | /// A JSON value whose objects keep their keys in the order they were read or inserted. |
| 20 | #[derive(Debug, Clone, PartialEq)] |
| 21 | pub enum OJson { |
| 22 | Null, |
| 23 | Bool(bool), |
| 24 | Int(i128), |
| 25 | Float(f64), |
| 26 | Str(String), |
| 27 | Arr(Vec<OJson>), |
| 28 | Obj(Vec<(String, OJson)>), |
| 29 | } |
| 30 | |
| 31 | static NULL: OJson = OJson::Null; |
| 32 | |
| 33 | impl OJson { |
| 34 | pub fn parse(text: &str) -> Result<OJson, String> { |
| 35 | serde_json::from_str(text).map_err(|e| e.to_string()) |
| 36 | } |
| 37 | |
| 38 | pub fn read(path: &std::path::Path) -> Result<OJson, String> { |
| 39 | let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; |
| 40 | Self::parse(&text).map_err(|e| format!("{}: {e}", path.display())) |
| 41 | } |
| 42 | |
| 43 | /// The value at `key`, or JSON null when this is not an object or has no such key. |
| 44 | pub fn get(&self, key: &str) -> &OJson { |
| 45 | self.get_opt(key).unwrap_or(&NULL) |
| 46 | } |
| 47 | |
| 48 | pub fn get_opt(&self, key: &str) -> Option<&OJson> { |
| 49 | match self { |
| 50 | OJson::Obj(m) => m.iter().find(|(k, _)| k == key).map(|(_, v)| v), |
| 51 | _ => None, |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | pub fn get_mut(&mut self, key: &str) -> Option<&mut OJson> { |
| 56 | match self { |
| 57 | OJson::Obj(m) => m.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v), |
| 58 | _ => None, |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub fn has(&self, key: &str) -> bool { |
| 63 | self.get_opt(key).is_some() |
| 64 | } |
| 65 | |
| 66 | /// Python `d[key] = value`: replace in place when present, else append. |
| 67 | pub fn set(&mut self, key: &str, value: OJson) { |
| 68 | if let OJson::Obj(m) = self { |
| 69 | match m.iter_mut().find(|(k, _)| k == key) { |
| 70 | Some(slot) => slot.1 = value, |
| 71 | None => m.push((key.to_string(), value)), |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | pub fn as_str(&self) -> Option<&str> { |
| 77 | match self { |
| 78 | OJson::Str(s) => Some(s), |
| 79 | _ => None, |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | pub fn as_arr(&self) -> &[OJson] { |
| 84 | match self { |
| 85 | OJson::Arr(a) => a, |
| 86 | _ => &[], |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | pub fn entries(&self) -> &[(String, OJson)] { |
| 91 | match self { |
| 92 | OJson::Obj(m) => m, |
| 93 | _ => &[], |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub fn keys(&self) -> Vec<&str> { |
| 98 | self.entries().iter().map(|(k, _)| k.as_str()).collect() |
| 99 | } |
| 100 | |
| 101 | pub fn is_obj(&self) -> bool { |
| 102 | matches!(self, OJson::Obj(_)) |
| 103 | } |
| 104 | |
| 105 | pub fn is_null(&self) -> bool { |
| 106 | matches!(self, OJson::Null) |
| 107 | } |
| 108 | |
| 109 | /// Python truthiness: null, false, 0, "", [] and {} are false. |
| 110 | pub fn truthy(&self) -> bool { |
| 111 | match self { |
| 112 | OJson::Null => false, |
| 113 | OJson::Bool(b) => *b, |
| 114 | OJson::Int(i) => *i != 0, |
| 115 | OJson::Float(f) => *f != 0.0, |
| 116 | OJson::Str(s) => !s.is_empty(), |
| 117 | OJson::Arr(a) => !a.is_empty(), |
| 118 | OJson::Obj(m) => !m.is_empty(), |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /// The same value as a `serde_json::Value` (object key order is then sorted). |
| 123 | pub fn to_value(&self) -> Value { |
| 124 | match self { |
| 125 | OJson::Null => Value::Null, |
| 126 | OJson::Bool(b) => Value::Bool(*b), |
| 127 | OJson::Int(i) => { |
| 128 | if let Ok(u) = u64::try_from(*i) { |
| 129 | Value::Number(u.into()) |
| 130 | } else if let Ok(s) = i64::try_from(*i) { |
| 131 | Value::Number(s.into()) |
| 132 | } else { |
| 133 | Number::from_f64(*i as f64).map_or(Value::Null, Value::Number) |
| 134 | } |
| 135 | } |
| 136 | OJson::Float(f) => Number::from_f64(*f).map_or(Value::Null, Value::Number), |
| 137 | OJson::Str(s) => Value::String(s.clone()), |
| 138 | OJson::Arr(a) => Value::Array(a.iter().map(OJson::to_value).collect()), |
| 139 | OJson::Obj(m) => Value::Object( |
| 140 | m.iter() |
| 141 | .map(|(k, v)| (k.clone(), v.to_value())) |
| 142 | .collect::<Map<_, _>>(), |
| 143 | ), |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | /// From a `serde_json::Value` (object keys in that value's iteration order). |
| 148 | pub fn from_value(v: &Value) -> OJson { |
| 149 | match v { |
| 150 | Value::Null => OJson::Null, |
| 151 | Value::Bool(b) => OJson::Bool(*b), |
| 152 | Value::Number(n) => match (n.as_i64(), n.as_u64()) { |
| 153 | (Some(i), _) => OJson::Int(i as i128), |
| 154 | (None, Some(u)) => OJson::Int(u as i128), |
| 155 | _ => OJson::Float(n.as_f64().unwrap_or(0.0)), |
| 156 | }, |
| 157 | Value::String(s) => OJson::Str(s.clone()), |
| 158 | Value::Array(a) => OJson::Arr(a.iter().map(OJson::from_value).collect()), |
| 159 | Value::Object(m) => OJson::Obj( |
| 160 | m.iter() |
| 161 | .map(|(k, v)| (k.clone(), OJson::from_value(v))) |
| 162 | .collect(), |
| 163 | ), |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | impl From<&str> for OJson { |
| 169 | fn from(s: &str) -> Self { |
| 170 | OJson::Str(s.to_string()) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | impl From<String> for OJson { |
| 175 | fn from(s: String) -> Self { |
| 176 | OJson::Str(s) |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | /// Build an [`OJson`] object from `(key, value)` pairs, in order. |
| 181 | pub fn obj<const N: usize>(pairs: [(&str, OJson); N]) -> OJson { |
| 182 | OJson::Obj(pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()) |
| 183 | } |
| 184 | |
| 185 | impl<'de> Deserialize<'de> for OJson { |
| 186 | fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { |
| 187 | struct V; |
| 188 | impl<'de> Visitor<'de> for V { |
| 189 | type Value = OJson; |
| 190 | fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 191 | f.write_str("any JSON value") |
| 192 | } |
| 193 | fn visit_unit<E>(self) -> Result<OJson, E> { |
| 194 | Ok(OJson::Null) |
| 195 | } |
| 196 | fn visit_none<E>(self) -> Result<OJson, E> { |
| 197 | Ok(OJson::Null) |
| 198 | } |
| 199 | fn visit_bool<E>(self, b: bool) -> Result<OJson, E> { |
| 200 | Ok(OJson::Bool(b)) |
| 201 | } |
| 202 | fn visit_i64<E>(self, i: i64) -> Result<OJson, E> { |
| 203 | Ok(OJson::Int(i as i128)) |
| 204 | } |
| 205 | fn visit_u64<E>(self, u: u64) -> Result<OJson, E> { |
| 206 | Ok(OJson::Int(u as i128)) |
| 207 | } |
| 208 | fn visit_f64<E>(self, f: f64) -> Result<OJson, E> { |
| 209 | Ok(OJson::Float(f)) |
| 210 | } |
| 211 | fn visit_str<E: de::Error>(self, s: &str) -> Result<OJson, E> { |
| 212 | Ok(OJson::Str(s.to_string())) |
| 213 | } |
| 214 | fn visit_string<E>(self, s: String) -> Result<OJson, E> { |
| 215 | Ok(OJson::Str(s)) |
| 216 | } |
| 217 | fn visit_seq<A: SeqAccess<'de>>(self, mut a: A) -> Result<OJson, A::Error> { |
| 218 | let mut out = vec![]; |
| 219 | while let Some(v) = a.next_element()? { |
| 220 | out.push(v); |
| 221 | } |
| 222 | Ok(OJson::Arr(out)) |
| 223 | } |
| 224 | fn visit_map<A: MapAccess<'de>>(self, mut a: A) -> Result<OJson, A::Error> { |
| 225 | // Python's json.load: a repeated key keeps its first position and its last value. |
| 226 | let mut out = OJson::Obj(vec![]); |
| 227 | while let Some((k, v)) = a.next_entry::<String, OJson>()? { |
| 228 | out.set(&k, v); |
| 229 | } |
| 230 | Ok(out) |
| 231 | } |
| 232 | } |
| 233 | d.deserialize_any(V) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | /// How [`dumps`] lays the text out; each preset is one `json.dumps` call shape. |
| 238 | #[derive(Debug, Clone, Copy)] |
| 239 | pub struct Style { |
| 240 | pub sort_keys: bool, |
| 241 | /// `separators=(",", ":")`. |
| 242 | pub compact: bool, |
| 243 | pub indent: Option<usize>, |
| 244 | } |
| 245 | |
| 246 | impl Style { |
| 247 | /// `json.dumps(x)` |
| 248 | pub const PLAIN: Style = Style { |
| 249 | sort_keys: false, |
| 250 | compact: false, |
| 251 | indent: None, |
| 252 | }; |
| 253 | /// `json.dumps(x, sort_keys=True)` |
| 254 | pub const SORTED: Style = Style { |
| 255 | sort_keys: true, |
| 256 | compact: false, |
| 257 | indent: None, |
| 258 | }; |
| 259 | /// `json.dumps(x, sort_keys=True, separators=(",", ":"))` |
| 260 | pub const SORTED_COMPACT: Style = Style { |
| 261 | sort_keys: true, |
| 262 | compact: true, |
| 263 | indent: None, |
| 264 | }; |
| 265 | /// `json.dumps(x, indent=2, sort_keys=True)` |
| 266 | pub const SORTED_INDENT2: Style = Style { |
| 267 | sort_keys: true, |
| 268 | compact: false, |
| 269 | indent: Some(2), |
| 270 | }; |
| 271 | } |
| 272 | |
| 273 | /// The text Python's `json.dumps` (default `ensure_ascii=True`) writes for `v` in `style`. |
| 274 | pub fn dumps(v: &OJson, style: Style) -> String { |
| 275 | let mut out = String::new(); |
| 276 | write(v, style, 0, &mut out); |
| 277 | out |
| 278 | } |
| 279 | |
| 280 | fn write(v: &OJson, st: Style, level: usize, out: &mut String) { |
| 281 | let (item_sep, key_sep) = match (st.compact, st.indent) { |
| 282 | (true, _) => (",", ":"), |
| 283 | (false, Some(_)) => (",", ": "), |
| 284 | (false, None) => (", ", ": "), |
| 285 | }; |
| 286 | let newline = |out: &mut String, lvl: usize| { |
| 287 | if let Some(n) = st.indent { |
| 288 | out.push('\n'); |
| 289 | out.push_str(&" ".repeat(n * lvl)); |
| 290 | } |
| 291 | }; |
| 292 | match v { |
| 293 | OJson::Null => out.push_str("null"), |
| 294 | OJson::Bool(true) => out.push_str("true"), |
| 295 | OJson::Bool(false) => out.push_str("false"), |
| 296 | OJson::Int(i) => out.push_str(&i.to_string()), |
| 297 | OJson::Float(f) => out.push_str(&py_float_repr(*f)), |
| 298 | OJson::Str(s) => write_str(s, out), |
| 299 | OJson::Arr(a) => { |
| 300 | if a.is_empty() { |
| 301 | out.push_str("[]"); |
| 302 | return; |
| 303 | } |
| 304 | out.push('['); |
| 305 | for (i, x) in a.iter().enumerate() { |
| 306 | if i > 0 { |
| 307 | out.push_str(item_sep); |
| 308 | } |
| 309 | newline(out, level + 1); |
| 310 | write(x, st, level + 1, out); |
| 311 | } |
| 312 | newline(out, level); |
| 313 | out.push(']'); |
| 314 | } |
| 315 | OJson::Obj(m) => { |
| 316 | if m.is_empty() { |
| 317 | out.push_str("{}"); |
| 318 | return; |
| 319 | } |
| 320 | let mut items: Vec<&(String, OJson)> = m.iter().collect(); |
| 321 | if st.sort_keys { |
| 322 | items.sort_by(|a, b| a.0.cmp(&b.0)); |
| 323 | } |
| 324 | out.push('{'); |
| 325 | for (i, (k, x)) in items.into_iter().enumerate() { |
| 326 | if i > 0 { |
| 327 | out.push_str(item_sep); |
| 328 | } |
| 329 | newline(out, level + 1); |
| 330 | write_str(k, out); |
| 331 | out.push_str(key_sep); |
| 332 | write(x, st, level + 1, out); |
| 333 | } |
| 334 | newline(out, level); |
| 335 | out.push('}'); |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | fn write_str(s: &str, out: &mut String) { |
| 341 | out.push('"'); |
| 342 | for c in s.chars() { |
| 343 | match c { |
| 344 | '"' => out.push_str("\\\""), |
| 345 | '\\' => out.push_str("\\\\"), |
| 346 | '\n' => out.push_str("\\n"), |
| 347 | '\r' => out.push_str("\\r"), |
| 348 | '\t' => out.push_str("\\t"), |
| 349 | '\u{8}' => out.push_str("\\b"), |
| 350 | '\u{c}' => out.push_str("\\f"), |
| 351 | c if (c as u32) < 0x20 || (c as u32) > 0x7e => { |
| 352 | let mut buf = [0u16; 2]; |
| 353 | for unit in c.encode_utf16(&mut buf) { |
| 354 | out.push_str(&format!("\\u{unit:04x}")); |
| 355 | } |
| 356 | } |
| 357 | c => out.push(c), |
| 358 | } |
| 359 | } |
| 360 | out.push('"'); |
| 361 | } |
| 362 | |
| 363 | /// Python's `repr(float)`: the shortest round-trip digits, fixed notation for exponents -4 to 15, |
| 364 | /// scientific (`1e-05`, `1e+16`) outside it, and always a `.0` on whole numbers. |
| 365 | pub fn py_float_repr(f: f64) -> String { |
| 366 | if f.is_nan() { |
| 367 | return "NaN".into(); |
| 368 | } |
| 369 | if f.is_infinite() { |
| 370 | return if f > 0.0 { "Infinity" } else { "-Infinity" }.into(); |
| 371 | } |
| 372 | // Rust's `{:e}` prints the shortest round-trip digits, e.g. `-1.25e3`, `1e-7`. |
| 373 | let sci = format!("{f:e}"); |
| 374 | let (mant, exp) = sci.split_once('e').expect("{:e} has an exponent"); |
| 375 | let exp: i32 = exp.parse().expect("exponent"); |
| 376 | let neg = mant.starts_with('-'); |
| 377 | let digits: String = mant.chars().filter(char::is_ascii_digit).collect(); |
| 378 | let mut s = String::new(); |
| 379 | if neg { |
| 380 | s.push('-'); |
| 381 | } |
| 382 | if (-4..16).contains(&exp) { |
| 383 | if exp >= 0 { |
| 384 | let int_len = exp as usize + 1; |
| 385 | let mut d = digits.clone(); |
| 386 | while d.len() < int_len { |
| 387 | d.push('0'); |
| 388 | } |
| 389 | s.push_str(&d[..int_len]); |
| 390 | s.push('.'); |
| 391 | let frac = &d[int_len..]; |
| 392 | s.push_str(if frac.is_empty() { "0" } else { frac }); |
| 393 | } else { |
| 394 | s.push_str("0."); |
| 395 | s.push_str(&"0".repeat((-exp - 1) as usize)); |
| 396 | s.push_str(&digits); |
| 397 | } |
| 398 | } else { |
| 399 | s.push_str(&digits[..1]); |
| 400 | if digits.len() > 1 { |
| 401 | s.push('.'); |
| 402 | s.push_str(&digits[1..]); |
| 403 | } |
| 404 | s.push('e'); |
| 405 | s.push(if exp < 0 { '-' } else { '+' }); |
| 406 | s.push_str(&format!("{:02}", exp.abs())); |
| 407 | } |
| 408 | s |
| 409 | } |
| 410 | |
| 411 | #[cfg(test)] |
| 412 | mod tests { |
| 413 | use super::*; |
| 414 | |
| 415 | #[test] |
| 416 | fn keeps_key_order_and_python_text() { |
| 417 | let v = OJson::parse(r#"{"b": 1, "a": [1.5, "é😀", null], "b": 2}"#).unwrap(); |
| 418 | assert_eq!(v.keys(), ["b", "a"]); |
| 419 | assert_eq!( |
| 420 | dumps(&v, Style::PLAIN), |
| 421 | r#"{"b": 2, "a": [1.5, "\u00e9\ud83d\ude00", null]}"# |
| 422 | ); |
| 423 | assert_eq!( |
| 424 | dumps(&v, Style::SORTED_COMPACT), |
| 425 | r#"{"a":[1.5,"\u00e9\ud83d\ude00",null],"b":2}"# |
| 426 | ); |
| 427 | assert_eq!( |
| 428 | dumps(&v, Style::SORTED_INDENT2), |
| 429 | "{\n \"a\": [\n 1.5,\n \"\\u00e9\\ud83d\\ude00\",\n null\n ],\n \"b\": 2\n}" |
| 430 | ); |
| 431 | assert_eq!( |
| 432 | dumps(&OJson::parse("[{}, []]").unwrap(), Style::SORTED_INDENT2), |
| 433 | "[\n {},\n []\n]" |
| 434 | ); |
| 435 | } |
| 436 | |
| 437 | #[test] |
| 438 | fn float_spelling_matches_python_repr() { |
| 439 | for (f, want) in [ |
| 440 | (1.0, "1.0"), |
| 441 | (0.1, "0.1"), |
| 442 | (-2.5, "-2.5"), |
| 443 | (1e16, "1e+16"), |
| 444 | (1.5e16, "1.5e+16"), |
| 445 | (123456789012345.6, "123456789012345.6"), |
| 446 | (1e-5, "1e-05"), |
| 447 | (0.0001, "0.0001"), |
| 448 | (0.0, "0.0"), |
| 449 | (1e22, "1e+22"), |
| 450 | ] { |
| 451 | assert_eq!(py_float_repr(f), want, "{f}"); |
| 452 | } |
| 453 | } |
| 454 | } |