icedwright-trace 0.0.2

The icedwright trace format: a deterministic .iwtrace archive of every step a test took, with its writer, reader and comparison
Documentation
//! Content-addressed blobs: semantic trees as YAML text and frames as PNG.

use core::fmt;
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::str::FromStr;

use icedwright_types::Frame;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::TraceError;

/// The blake3 hash of a blob's bytes, printed as 64 lowercase hex digits.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BlobHash([u8; 32]);

impl BlobHash {
    /// The hash of `bytes`.
    #[must_use]
    pub fn of(bytes: &[u8]) -> Self {
        Self(*blake3::hash(bytes).as_bytes())
    }
}

impl fmt::Display for BlobHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
    }
}

impl fmt::Debug for BlobHash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "BlobHash({self})")
    }
}

/// Why a string is not a [`BlobHash`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0:?} is not 64 lowercase hex digits")]
pub struct BadBlobHash(String);

impl FromStr for BlobHash {
    type Err = BadBlobHash;

    fn from_str(text: &str) -> Result<Self, BadBlobHash> {
        let bad = || BadBlobHash(text.to_owned());
        if text.len() != 64 {
            return Err(bad());
        }
        let mut bytes = [0u8; 32];
        let (pairs, _) = text.as_bytes().as_chunks::<2>();
        for (byte, pair) in bytes.iter_mut().zip(pairs) {
            let digits = core::str::from_utf8(pair).map_err(|_| bad())?;
            if digits.bytes().any(|d| d.is_ascii_uppercase()) {
                return Err(bad());
            }
            *byte = u8::from_str_radix(digits, 16).map_err(|_| bad())?;
        }
        Ok(Self(bytes))
    }
}

impl Serialize for BlobHash {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for BlobHash {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        text.parse().map_err(serde::de::Error::custom)
    }
}

mod sealed {
    pub trait Sealed {}
}

/// A kind of blob a trace stores. Sealed: the format has exactly these.
pub trait Media: sealed::Sealed {
    /// The file extension of its members under `blobs/`.
    const EXTENSION: &'static str;
}

/// Marks a blob holding a semantic tree as YAML text.
#[derive(Debug)]
pub enum Yaml {}

impl sealed::Sealed for Yaml {}
impl Media for Yaml {
    const EXTENSION: &'static str = "yaml";
}

impl sealed::Sealed for Png {}
impl Media for Png {
    const EXTENSION: &'static str = "png";
}

/// A content-addressed blob whose media type is part of its type, so a tree ref cannot be read
/// as a frame. Only the writer makes them, and reading a trace back.
pub struct BlobRef<M: Media> {
    /// The hash of the blob's bytes, which is also its name.
    pub hash: BlobHash,
    media: PhantomData<fn() -> M>,
}

impl<M: Media> BlobRef<M> {
    pub(crate) fn new(hash: BlobHash) -> Self {
        Self {
            hash,
            media: PhantomData,
        }
    }

    /// The member that holds the blob, such as `blobs/<hash>.png`.
    #[must_use]
    pub fn member(&self) -> String {
        member_name::<M>(self.hash)
    }
}

pub(crate) fn member_name<M: Media>(hash: BlobHash) -> String {
    format!("blobs/{hash}.{}", M::EXTENSION)
}

impl<M: Media> Clone for BlobRef<M> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<M: Media> Copy for BlobRef<M> {}

impl<M: Media> PartialEq for BlobRef<M> {
    fn eq(&self, other: &Self) -> bool {
        self.hash == other.hash
    }
}

impl<M: Media> Eq for BlobRef<M> {}

impl<M: Media> PartialOrd for BlobRef<M> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<M: Media> Ord for BlobRef<M> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.hash.cmp(&other.hash)
    }
}

impl<M: Media> Hash for BlobRef<M> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.hash.hash(state);
    }
}

impl<M: Media> fmt::Debug for BlobRef<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "BlobRef({})", self.member())
    }
}

impl<M: Media> Serialize for BlobRef<M> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.hash.serialize(serializer)
    }
}

impl<'de, M: Media> Deserialize<'de> for BlobRef<M> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        BlobHash::deserialize(deserializer).map(Self::new)
    }
}

/// An encoded PNG image, and the media marker for frame blobs.
#[derive(Clone, PartialEq, Eq)]
pub struct Png(Vec<u8>);

const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";

impl Png {
    /// Encodes `frame` as an 8-bit RGBA PNG with fixed compression and filter settings, so the
    /// same pixels always give the same bytes.
    pub fn encode(frame: &Frame) -> Result<Png, TraceError> {
        let size = frame.size().get();
        let mut bytes = Vec::new();
        let mut encoder = png::Encoder::new(&mut bytes, size.width, size.height);
        encoder.set_color(png::ColorType::Rgba);
        encoder.set_depth(png::BitDepth::Eight);
        encoder.set_compression(png::Compression::Balanced);
        encoder.set_filter(png::Filter::Adaptive);
        let mut writer = encoder
            .write_header()
            .map_err(|e| TraceError::Png(e.to_string()))?;
        writer
            .write_image_data(frame.rgba())
            .map_err(|e| TraceError::Png(e.to_string()))?;
        writer
            .finish()
            .map_err(|e| TraceError::Png(e.to_string()))?;
        Ok(Png(bytes))
    }

    /// Wraps bytes that are already a PNG. Only the signature is checked.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Png, TraceError> {
        if !bytes.starts_with(PNG_SIGNATURE) {
            return Err(TraceError::Png("the PNG signature is missing".to_owned()));
        }
        Ok(Png(bytes))
    }

    /// The encoded bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// The encoded bytes, taking ownership.
    #[must_use]
    pub fn into_bytes(self) -> Vec<u8> {
        self.0
    }

    /// The encoded size in bytes.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Always false for a valid PNG; present because `len` is.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Prints the length rather than every byte.
impl fmt::Debug for Png {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Png({} bytes)", self.0.len())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use icedwright_types::{ScaleFactor, Size, units::Physical};

    #[test]
    fn hashes_print_and_parse_as_hex() -> Result<(), BadBlobHash> {
        let hash = BlobHash::of(b"tree");
        let text = hash.to_string();
        assert_eq!(text.len(), 64);
        assert_eq!(text.parse::<BlobHash>()?, hash);
        assert!("abc".parse::<BlobHash>().is_err());
        assert!(text.to_uppercase().parse::<BlobHash>().is_err());
        assert!("zz".repeat(32).parse::<BlobHash>().is_err());
        Ok(())
    }

    #[test]
    fn refs_serialise_as_their_hash() -> Result<(), serde_json::Error> {
        let tree = BlobRef::<Yaml>::new(BlobHash::of(b"a"));
        let json = serde_json::to_string(&tree)?;
        assert_eq!(json, format!("\"{}\"", tree.hash));
        assert_eq!(serde_json::from_str::<BlobRef<Yaml>>(&json)?, tree);
        assert_eq!(tree.member(), format!("blobs/{}.yaml", tree.hash));
        let frame = BlobRef::<Png>::new(tree.hash);
        assert_eq!(frame.member(), format!("blobs/{}.png", tree.hash));
        Ok(())
    }

    #[test]
    fn encoding_is_stable() -> Result<(), Box<dyn std::error::Error>> {
        let rgba = (0..64u8).flat_map(|i| [i, 255 - i, i / 2, 255]).collect();
        let frame = Frame::new(rgba, Physical::new(Size::new(8, 8)), ScaleFactor::ONE)?;
        let first = Png::encode(&frame)?;
        let second = Png::encode(&frame)?;
        assert_eq!(first, second);
        assert!(first.as_bytes().starts_with(PNG_SIGNATURE));
        assert_eq!(Png::from_bytes(first.clone().into_bytes())?, first);
        assert!(!first.is_empty());
        Ok(())
    }

    #[test]
    fn non_png_bytes_are_refused() {
        let error = Png::from_bytes(b"GIF89a".to_vec())
            .err()
            .map(|e| e.to_string());
        assert_eq!(
            error.as_deref(),
            Some("not a PNG: the PNG signature is missing")
        );
    }
}