icedwright-trace 0.0.1

The icedwright trace format: a deterministic .iwtrace archive of every step a test took, with its writer, reader and comparison
Documentation
//! The zip container: member names and the fixed settings that make its bytes reproducible.

use std::io::{Cursor, Write};

use zip::write::SimpleFileOptions;
use zip::{CompressionMethod, DateTime, ZipWriter};

use crate::error::TraceError;

pub(crate) const META: &str = "meta.json";
pub(crate) const STEPS: &str = "steps.jsonl";
pub(crate) const REAL: &str = "real.json";
pub(crate) const SOURCE_PREFIX: &str = "source/";

/// The deflate level every text member is written at.
const LEVEL: i64 = 6;

/// How a member is stored. PNGs are already compressed, so they are stored as they are,
/// which also makes their share of the archive size exact.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Packing {
    Deflate,
    Store,
}

/// One member, in the order it is written.
#[derive(Debug)]
pub(crate) struct Member<'a> {
    pub(crate) name: String,
    pub(crate) bytes: &'a [u8],
    pub(crate) packing: Packing,
}

/// The archive holding `members` in the order given, every one with the same timestamp and
/// permissions.
pub(crate) fn pack(members: &[Member<'_>]) -> Result<Vec<u8>, TraceError> {
    let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
    for member in members {
        let options = SimpleFileOptions::default()
            .last_modified_time(DateTime::DEFAULT)
            .unix_permissions(0o644);
        let options = match member.packing {
            Packing::Deflate => options
                .compression_method(CompressionMethod::Deflated)
                .compression_level(Some(LEVEL)),
            Packing::Store => options.compression_method(CompressionMethod::Stored),
        };
        writer
            .start_file(member.name.as_str(), options)
            .map_err(zip_error)?;
        writer.write_all(member.bytes)?;
    }
    let cursor = writer.finish().map_err(zip_error)?;
    Ok(cursor.into_inner())
}

pub(crate) fn zip_error(error: zip::result::ZipError) -> TraceError {
    match error {
        zip::result::ZipError::Io(io) => TraceError::Io(io),
        other => TraceError::Corrupt(other.to_string()),
    }
}