gitiverse-git 0.3.0

Git object store abstraction, packfile construction, strict quarantine ingest, canonical serialisation, and merge/diff helpers for gitiverse
Documentation
use serde::Serialize;
use serde_json::Value;
use sha2::{Digest, Sha256};
use thiserror::Error;
use wire_mesh_wire::minicbor::{Decode, Encode};
use wire_mesh_wire::{DecodeError, decode_exact, to_vec};

/// Failure returned by canonical serialisation helpers.
#[derive(Debug, Error)]
pub enum CanonicalError {
    #[error("JSON serialisation failed: {0}")]
    Json(#[from] serde_json::Error),
    #[error("CBOR decode failed: {0}")]
    Cbor(#[from] DecodeError),
}

fn canonicalise_json_value(value: Value) -> Value {
    match value {
        Value::Array(items) => {
            Value::Array(items.into_iter().map(canonicalise_json_value).collect())
        }
        Value::Object(map) => {
            let mut entries: Vec<(String, Value)> = map
                .into_iter()
                .map(|(k, v)| (k, canonicalise_json_value(v)))
                .collect();
            entries.sort_by(|(a, _), (b, _)| a.cmp(b));
            let mut sorted = serde_json::Map::new();
            for (k, v) in entries {
                sorted.insert(k, v);
            }
            Value::Object(sorted)
        }
        other => other,
    }
}

/// Serialises any `Serialize` value to deterministic compact JSON with lexicographically sorted object keys at every nesting depth.
pub fn canonical_json_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>, CanonicalError> {
    let json_val = serde_json::to_value(value)?;
    let canonical = canonicalise_json_value(json_val);
    Ok(serde_json::to_vec(&canonical)?)
}

/// Serialises any `minicbor::Encode<()>` value into canonical CBOR bytes.
#[must_use]
pub fn to_canonical_cbor<T: Encode<()>>(value: &T) -> Vec<u8> {
    to_vec(value)
}

/// Strictly decodes a `minicbor::Decode<()>` value from complete canonical CBOR bytes without trailing bytes.
pub fn from_canonical_cbor<'b, T: Decode<'b, ()>>(bytes: &'b [u8]) -> Result<T, CanonicalError> {
    Ok(decode_exact(bytes)?)
}

/// Computes the raw 32-byte SHA-256 digest of `bytes`.
#[must_use]
pub fn sha256_digest(bytes: &[u8]) -> [u8; 32] {
    Sha256::digest(bytes).into()
}

/// Computes the 64-character lowercase hex SHA-256 digest of `bytes`.
#[must_use]
pub fn sha256_hex(bytes: &[u8]) -> String {
    hex::encode(sha256_digest(bytes))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn canonical_json_produces_identical_bytes_regardless_of_map_insertion_order() {
        let mut m1 = HashMap::new();
        m1.insert("z", 1);
        m1.insert("a", 2);
        m1.insert("m", 3);

        let mut m2 = HashMap::new();
        m2.insert("m", 3);
        m2.insert("a", 2);
        m2.insert("z", 1);

        let b1 = canonical_json_bytes(&m1).unwrap();
        let b2 = canonical_json_bytes(&m2).unwrap();
        assert_eq!(b1, b2);
        assert_eq!(String::from_utf8(b1).unwrap(), r#"{"a":2,"m":3,"z":1}"#);
    }

    #[test]
    fn sha256_helpers_match_expected_digest() {
        let digest = sha256_digest(b"gitiverse");
        assert_eq!(hex::encode(digest), sha256_hex(b"gitiverse"));
        assert_eq!(sha256_hex(b"gitiverse").len(), 64);
    }
}