bread-format 0.6.0

Reads and writes .bread files: tiny, lossless meshes and scenes, with room for slicer data such as editable supports.
Documentation
/*
 * SPDX-FileCopyrightText: 2026 SynrgStudio
 * SPDX-License-Identifier: Apache-2.0
 */

//! The program data chunk (`SPEC.md`, section 13): each program's own
//! documents, by program name and subject, a node or the whole file.
//!
//! The documents are carried without being read: what one holds belongs to
//! the program that wrote it. Every entry's program name is checked, every
//! subject is a node of the scene or the whole file, and no two entries have
//! the same program and subject.
//!
//! ```text
//! entries   u32 count, then per entry:
//!           u32 length, the program's name
//!           u32 the node index the entry is about, or FFFFFFFF for the file
//!           u32 the program's own version of the document
//!           u32 length, the document
//! ```

use std::collections::HashSet;
use std::fmt;

use crate::bytes::{In, Out, fits_u32};
use crate::container::ChunkTag;
use crate::scene::Scene;

/// The tag of the program data chunk.
pub const PROGRAM_TAG: ChunkTag = ChunkTag(*b"PROG");

/// The program data payload layout this build writes and reads.
pub const PROGRAM_VERSION: u16 = 1;

/// The subject that stands for the whole file in a payload.
const FILE: u32 = u32::MAX;

/// The longest program name, in bytes.
const MAX_NAME: usize = 64;

/// One program's document about the whole file or one node.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProgramEntry {
    /// The program's name, such as `nudl`: 1 to 64 lowercase letters,
    /// digits, dots, hyphens and underscores, starting with a letter.
    pub program: String,
    /// The node the entry is about, as an index into the scene's nodes, or
    /// `None` for the whole file.
    pub node: Option<usize>,
    /// The program's own version of the document.
    pub version: u32,
    /// The document, carried without being read.
    pub document: Vec<u8>,
}

/// Why a list of program data entries could not be encoded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EncodeProgramDataError {
    /// A program name is not 1 to 64 lowercase letters, digits, dots,
    /// hyphens and underscores, starting with a letter.
    BadName { program: String },
    /// An entry names a node the scene does not have.
    NoSuchNode { node: usize },
    /// Two entries have the same program and subject.
    SameEntry { program: String },
    /// There are 2^32 or more entries, or a document of 4 GiB or more.
    TooLarge,
}

impl fmt::Display for EncodeProgramDataError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BadName { program } => write!(f, "{program:?} is not a program name"),
            Self::NoSuchNode { node } => write!(
                f,
                "program data names node {node}, which the scene does not have"
            ),
            Self::SameEntry { program } => write!(
                f,
                "two program data entries of {program:?} have the same subject"
            ),
            Self::TooLarge => f.write_str("the program data is too large for its chunk"),
        }
    }
}

impl std::error::Error for EncodeProgramDataError {}

/// Why a program data payload could not be decoded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodeProgramDataError {
    /// The payload is cut short or padded, or a program name breaks the
    /// rules of section 13.1.
    Malformed,
    /// An entry names a node the scene does not have.
    NoSuchNode,
    /// Two entries have the same program and subject.
    SameEntry,
}

impl fmt::Display for DecodeProgramDataError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Malformed => f.write_str("the program data is malformed"),
            Self::NoSuchNode => f.write_str("program data names a node the scene does not have"),
            Self::SameEntry => {
                f.write_str("two program data entries have the same program and subject")
            }
        }
    }
}

impl std::error::Error for DecodeProgramDataError {}

/// Whether `name` is a program name (`SPEC.md`, section 13.1): 1 to 64
/// lowercase ASCII letters, digits, `.`, `-` and `_`, the first a letter. The
/// program data, the surface paint and the volumes name their programs this
/// way.
pub fn is_program_name(name: &str) -> bool {
    is_name(name.as_bytes())
}

/// [`is_program_name`] on the bytes of a payload.
pub(crate) fn is_name(name: &[u8]) -> bool {
    (1..=MAX_NAME).contains(&name.len())
        && name[0].is_ascii_lowercase()
        && name
            .iter()
            .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
}

/// Encodes `entries` as a program data payload, in their order, checking
/// them against `scene`.
pub fn encode_program_data(
    entries: &[ProgramEntry],
    scene: &Scene,
) -> Result<Vec<u8>, EncodeProgramDataError> {
    let mut seen = HashSet::new();
    for entry in entries {
        if !is_name(entry.program.as_bytes()) {
            return Err(EncodeProgramDataError::BadName {
                program: entry.program.clone(),
            });
        }
        if let Some(node) = entry.node
            && node >= scene.nodes.len()
        {
            return Err(EncodeProgramDataError::NoSuchNode { node });
        }
        if !seen.insert((entry.program.as_str(), entry.node)) {
            return Err(EncodeProgramDataError::SameEntry {
                program: entry.program.clone(),
            });
        }
    }
    if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.document.len())) {
        return Err(EncodeProgramDataError::TooLarge);
    }
    let mut out = Out::default();
    out.len(entries.len());
    for entry in entries {
        out.bytes(entry.program.as_bytes());
        // A node was checked against the scene, whose node count fits.
        out.u32(entry.node.map_or(FILE, |node| node as u32));
        out.u32(entry.version);
        out.bytes(&entry.document);
    }
    Ok(out.0)
}

/// Decodes a program data payload, checking it against `scene`, the scene
/// of the same file.
pub fn decode_program_data(
    payload: &[u8],
    scene: &Scene,
) -> Result<Vec<ProgramEntry>, DecodeProgramDataError> {
    let mut input = In(payload);
    let malformed = DecodeProgramDataError::Malformed;
    let count = input.count(17).ok_or(malformed.clone())?;
    let mut entries = Vec::with_capacity(count);
    for _ in 0..count {
        let name = input.bytes().ok_or(malformed.clone())?;
        if !is_name(name) {
            return Err(malformed);
        }
        let subject = input.u32().ok_or(malformed.clone())?;
        let version = input.u32().ok_or(malformed.clone())?;
        let document = input.bytes().ok_or(malformed.clone())?;
        entries.push((name, subject, version, document));
    }
    if !input.is_empty() {
        return Err(malformed);
    }
    let mut seen = HashSet::new();
    let mut out = Vec::with_capacity(entries.len());
    for (name, subject, version, document) in entries {
        let node = match subject {
            FILE => None,
            node if (node as usize) < scene.nodes.len() => Some(node as usize),
            _ => return Err(DecodeProgramDataError::NoSuchNode),
        };
        if !seen.insert((name, node)) {
            return Err(DecodeProgramDataError::SameEntry);
        }
        out.push(ProgramEntry {
            // A program name is ASCII.
            program: String::from_utf8_lossy(name).into_owned(),
            node,
            version,
            document: document.to_vec(),
        });
    }
    Ok(out)
}