Skip to main content

vlo_kernel/
canonical.rs

1//! Canonical JSON: parse, then re-serialize compact with object keys sorted.
2//!
3//! `serde_json::Map` is a `BTreeMap` here (the `preserve_order` feature is off), so a
4//! parsed value re-serializes with sorted keys and no whitespace. `NaN` / `Infinity`
5//! are rejected by the parser and cannot exist inside a `Value`, so a canonical form is
6//! always valid JSON.
7//!
8//! Numbers round-trip exactly within `i64` / `u64`; larger integers become `f64` and
9//! canonicalize to their shortest round-trip form. Canonicalization is idempotent:
10//! `canonicalize(canonicalize(x)) == canonicalize(x)`.
11
12use serde::Serialize;
13use serde_json::Value;
14
15use crate::error::{code, err, KResult};
16
17/// Parse JSON text into a `Value`; `malformed_json` when it is not valid JSON.
18pub fn parse(raw: &str) -> KResult<Value> {
19    serde_json::from_str(raw).map_err(|e| err(code::MALFORMED_JSON, format!("invalid JSON: {e}")))
20}
21
22/// Serialize a `Value` compact with object keys sorted.
23pub fn to_string(value: &Value) -> KResult<String> {
24    serde_json::to_string(value)
25        .map_err(|e| err(code::MALFORMED_JSON, format!("value is not JSON: {e}")))
26}
27
28/// Parse `raw` and return its canonical form.
29pub fn canonicalize(raw: &str) -> KResult<String> {
30    to_string(&parse(raw)?)
31}
32
33/// Canonical form of any serializable value. Goes through `Value` on purpose: struct
34/// serialization emits fields in declaration order, `Value` emits them sorted.
35pub fn canonical_of<T: Serialize>(value: &T) -> KResult<String> {
36    let value = serde_json::to_value(value)
37        .map_err(|e| err(code::MALFORMED_JSON, format!("value is not JSON: {e}")))?;
38    to_string(&value)
39}