rustensor 0.1.0

Small Rust-native checkpoint format for model metadata and tensor weights.
Documentation
//! RTEN file writer.
//!
//! This module validates, serializes and writes checkpoints into `.rten` files.

use crate::checkpoint::ModelCheckpoint;
use crate::error::{Result, RustensorError};
use crate::format::{HEADER_SIZE, MAX_PAYLOAD_SIZE, RtenHeader};
use crate::integrity::sha256_payload;
use std::path::Path;

pub fn save_checkpoint(path: impl AsRef<Path>, checkpoint: &ModelCheckpoint) -> Result<()> {
    checkpoint.validate()?;

    let payload = postcard::to_stdvec(checkpoint)
        .map_err(|error| RustensorError::EncodeError(error.to_string()))?;

    let payload_length = payload.len() as u64;

    if payload_length > MAX_PAYLOAD_SIZE {
        return Err(RustensorError::PayloadTooLarge {
            found: payload_length,
            max: MAX_PAYLOAD_SIZE,
        });
    }

    let checksum = sha256_payload(&payload);
    let header = RtenHeader::new(payload_length, checksum)?;
    let header_bytes = header.encode()?;

    let mut file_bytes = Vec::with_capacity(HEADER_SIZE + payload.len());
    file_bytes.extend_from_slice(&header_bytes);
    file_bytes.extend_from_slice(&payload);

    std::fs::write(path, file_bytes)?;

    Ok(())
}