clm-kernel 0.0.24

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 0: Stateless Kenotic Codecs & Canonical Serialization
//! Canonical Path: kernel/clm_rust_core/src/layer0/codec.rs

use serde::Serialize;
use serde_json::Value;

/// Encode bytes to lowercase hexadecimal string.
pub fn to_hex(bytes: &[u8]) -> String {
    hex::encode(bytes)
}

/// Decode hexadecimal string into bytes.
pub fn from_hex(s: &str) -> Result<Vec<u8>, String> {
    hex::decode(s.trim()).map_err(|e| e.to_string())
}

/// Encode bytes to Base58 string (Bitcoin alphabet) via `bs58`.
pub fn to_base58(bytes: &[u8]) -> String {
    bs58::encode(bytes).into_string()
}

/// Decode Base58 string into bytes via `bs58`.
pub fn from_base58(s: &str) -> Result<Vec<u8>, String> {
    bs58::decode(s).into_vec().map_err(|e| e.to_string())
}

/// Canonical JSON serialization with recursively sorted object keys.
pub fn canonical_json<T: Serialize>(value: &T) -> Result<String, String> {
    let raw = serde_json::to_value(value).map_err(|e| e.to_string())?;
    let sorted = sort_json_value(&raw);
    serde_json::to_string(&sorted).map_err(|e| e.to_string())
}

/// Recursively sort JSON object keys in deterministic UTF-8 order.
pub fn sort_json_value(v: &Value) -> Value {
    match v {
        Value::Object(map) => {
            let mut keys: Vec<String> = map.keys().cloned().collect();
            keys.sort();
            let mut sorted_map = serde_json::Map::new();
            for k in keys {
                if let Some(val) = map.get(&k) {
                    sorted_map.insert(k, sort_json_value(val));
                }
            }
            Value::Object(sorted_map)
        }
        Value::Array(arr) => Value::Array(arr.iter().map(sort_json_value).collect()),
        other => other.clone(),
    }
}

/// Canonical YAML serialization.
pub fn canonical_yaml<T: Serialize>(value: &T) -> Result<String, String> {
    serde_yaml::to_string(value).map_err(|e| e.to_string())
}

/// Sprint 529 parity corpus, shared by the canonicalizer delegation tests.
#[cfg(test)]
pub fn canonical_parity_corpus() -> Vec<serde_json::Value> {
    use serde_json::json;
    vec![json!(null), json!(true), json!(0), json!(-17), json!(1.5), json!(1e10), json!("plain"),
         json!("quote \" and backslash \\"), json!("unicode: héllo 世界"), json!([]), json!({}),
         json!({"b": 1, "a": 2}), json!({"z": [1, {"y": 2, "x": 3}], "a": "s"}),
         json!({"n": null, "arr": [null, 1]}), json!({"nested": {"deep": {"deeper": [true, false]}}}),
         json!([[[[]]]]), json!({"empty_obj": {}, "empty_arr": []})]
}