rustensor 0.1.0

Small Rust-native checkpoint format for model metadata and tensor weights.
Documentation
//! Integrity helpers for RTEN payloads.
//!
//! This module computes and verifies SHA-256 checksums over serialized payloads.
//! The checksum detects accidental corruption or unintended modification.
//! It is not a digital signature and does not prove file authenticity.

use crate::error::{Result, RustensorError};
use sha2::{Digest, Sha256};
use std::fmt::Write;

pub const SHA256_SIZE: usize = 32;

pub fn sha256_payload(payload: &[u8]) -> [u8; SHA256_SIZE] {
    let digest = Sha256::digest(payload);
    digest.into()
}

pub fn sha256_hex(payload: &[u8]) -> String {
    let digest = sha256_payload(payload);
    let mut output = String::with_capacity(digest.len() * 2);

    for byte in digest {
        write!(&mut output, "{byte:02x}").expect("writing to String should not fail");
    }

    output
}

pub fn verify_checksum(payload: &[u8], expected: &[u8; SHA256_SIZE]) -> Result<()> {
    let actual = sha256_payload(payload);

    // Constant-time style comparison without adding an external dependency.
    // This avoids early-exit comparison behavior. The checksum is still only
    // an integrity check, not an authenticity mechanism.
    let diff = actual
        .iter()
        .zip(expected.iter())
        .fold(0u8, |acc, (left, right)| acc | (left ^ right));

    if diff != 0 {
        return Err(RustensorError::ChecksumMismatch);
    }

    Ok(())
}