Skip to main content

bread_format/
program.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The program data chunk (`SPEC.md`, section 13): each program's own
7//! documents, by program name and subject, a node or the whole file.
8//!
9//! The documents are carried without being read: what one holds belongs to
10//! the program that wrote it. Every entry's program name is checked, every
11//! subject is a node of the scene or the whole file, and no two entries have
12//! the same program and subject.
13//!
14//! ```text
15//! entries   u32 count, then per entry:
16//!           u32 length, the program's name
17//!           u32 the node index the entry is about, or FFFFFFFF for the file
18//!           u32 the program's own version of the document
19//!           u32 length, the document
20//! ```
21
22use std::collections::HashSet;
23use std::fmt;
24
25use crate::bytes::{In, Out, fits_u32};
26use crate::container::ChunkTag;
27use crate::scene::Scene;
28
29/// The tag of the program data chunk.
30pub const PROGRAM_TAG: ChunkTag = ChunkTag(*b"PROG");
31
32/// The program data payload layout this build writes and reads.
33pub const PROGRAM_VERSION: u16 = 1;
34
35/// The subject that stands for the whole file in a payload.
36const FILE: u32 = u32::MAX;
37
38/// The longest program name, in bytes.
39const MAX_NAME: usize = 64;
40
41/// One program's document about the whole file or one node.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct ProgramEntry {
44    /// The program's name, such as `nudl`: 1 to 64 lowercase letters,
45    /// digits, dots, hyphens and underscores, starting with a letter.
46    pub program: String,
47    /// The node the entry is about, as an index into the scene's nodes, or
48    /// `None` for the whole file.
49    pub node: Option<usize>,
50    /// The program's own version of the document.
51    pub version: u32,
52    /// The document, carried without being read.
53    pub document: Vec<u8>,
54}
55
56/// Why a list of program data entries could not be encoded.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum EncodeProgramDataError {
59    /// A program name is not 1 to 64 lowercase letters, digits, dots,
60    /// hyphens and underscores, starting with a letter.
61    BadName { program: String },
62    /// An entry names a node the scene does not have.
63    NoSuchNode { node: usize },
64    /// Two entries have the same program and subject.
65    SameEntry { program: String },
66    /// There are 2^32 or more entries, or a document of 4 GiB or more.
67    TooLarge,
68}
69
70impl fmt::Display for EncodeProgramDataError {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            Self::BadName { program } => write!(f, "{program:?} is not a program name"),
74            Self::NoSuchNode { node } => write!(
75                f,
76                "program data names node {node}, which the scene does not have"
77            ),
78            Self::SameEntry { program } => write!(
79                f,
80                "two program data entries of {program:?} have the same subject"
81            ),
82            Self::TooLarge => f.write_str("the program data is too large for its chunk"),
83        }
84    }
85}
86
87impl std::error::Error for EncodeProgramDataError {}
88
89/// Why a program data payload could not be decoded.
90#[derive(Clone, Debug, PartialEq, Eq)]
91pub enum DecodeProgramDataError {
92    /// The payload is cut short or padded, or a program name breaks the
93    /// rules of section 13.1.
94    Malformed,
95    /// An entry names a node the scene does not have.
96    NoSuchNode,
97    /// Two entries have the same program and subject.
98    SameEntry,
99}
100
101impl fmt::Display for DecodeProgramDataError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Self::Malformed => f.write_str("the program data is malformed"),
105            Self::NoSuchNode => f.write_str("program data names a node the scene does not have"),
106            Self::SameEntry => {
107                f.write_str("two program data entries have the same program and subject")
108            }
109        }
110    }
111}
112
113impl std::error::Error for DecodeProgramDataError {}
114
115/// Whether `name` is a program name (`SPEC.md`, section 13.1): 1 to 64
116/// lowercase ASCII letters, digits, `.`, `-` and `_`, the first a letter. The
117/// program data, the surface paint and the volumes name their programs this
118/// way.
119pub fn is_program_name(name: &str) -> bool {
120    is_name(name.as_bytes())
121}
122
123/// [`is_program_name`] on the bytes of a payload.
124pub(crate) fn is_name(name: &[u8]) -> bool {
125    (1..=MAX_NAME).contains(&name.len())
126        && name[0].is_ascii_lowercase()
127        && name
128            .iter()
129            .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b))
130}
131
132/// Encodes `entries` as a program data payload, in their order, checking
133/// them against `scene`.
134pub fn encode_program_data(
135    entries: &[ProgramEntry],
136    scene: &Scene,
137) -> Result<Vec<u8>, EncodeProgramDataError> {
138    let mut seen = HashSet::new();
139    for entry in entries {
140        if !is_name(entry.program.as_bytes()) {
141            return Err(EncodeProgramDataError::BadName {
142                program: entry.program.clone(),
143            });
144        }
145        if let Some(node) = entry.node
146            && node >= scene.nodes.len()
147        {
148            return Err(EncodeProgramDataError::NoSuchNode { node });
149        }
150        if !seen.insert((entry.program.as_str(), entry.node)) {
151            return Err(EncodeProgramDataError::SameEntry {
152                program: entry.program.clone(),
153            });
154        }
155    }
156    if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.document.len())) {
157        return Err(EncodeProgramDataError::TooLarge);
158    }
159    let mut out = Out::default();
160    out.len(entries.len());
161    for entry in entries {
162        out.bytes(entry.program.as_bytes());
163        // A node was checked against the scene, whose node count fits.
164        out.u32(entry.node.map_or(FILE, |node| node as u32));
165        out.u32(entry.version);
166        out.bytes(&entry.document);
167    }
168    Ok(out.0)
169}
170
171/// Decodes a program data payload, checking it against `scene`, the scene
172/// of the same file.
173pub fn decode_program_data(
174    payload: &[u8],
175    scene: &Scene,
176) -> Result<Vec<ProgramEntry>, DecodeProgramDataError> {
177    let mut input = In(payload);
178    let malformed = DecodeProgramDataError::Malformed;
179    let count = input.count(17).ok_or(malformed.clone())?;
180    let mut entries = Vec::with_capacity(count);
181    for _ in 0..count {
182        let name = input.bytes().ok_or(malformed.clone())?;
183        if !is_name(name) {
184            return Err(malformed);
185        }
186        let subject = input.u32().ok_or(malformed.clone())?;
187        let version = input.u32().ok_or(malformed.clone())?;
188        let document = input.bytes().ok_or(malformed.clone())?;
189        entries.push((name, subject, version, document));
190    }
191    if !input.is_empty() {
192        return Err(malformed);
193    }
194    let mut seen = HashSet::new();
195    let mut out = Vec::with_capacity(entries.len());
196    for (name, subject, version, document) in entries {
197        let node = match subject {
198            FILE => None,
199            node if (node as usize) < scene.nodes.len() => Some(node as usize),
200            _ => return Err(DecodeProgramDataError::NoSuchNode),
201        };
202        if !seen.insert((name, node)) {
203            return Err(DecodeProgramDataError::SameEntry);
204        }
205        out.push(ProgramEntry {
206            // A program name is ASCII.
207            program: String::from_utf8_lossy(name).into_owned(),
208            node,
209            version,
210            document: document.to_vec(),
211        });
212    }
213    Ok(out)
214}