Skip to main content

bread_format/
metadata.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The metadata chunk (`SPEC.md`, section 12): who made a file, how it may be
7//! used, and lasting ids for its parts, as entries of a subject, a key and a
8//! value.
9//!
10//! Metadata never makes a file unreadable. Decoding drops what breaks a rule,
11//! entry by entry, or the whole payload when it is malformed; encoding refuses
12//! what a writer must not write.
13//!
14//! ```text
15//! entries   u32 count, then per entry:
16//!           u32 the node index the entry is about, or FFFFFFFF for the file
17//!           u32 length, key
18//!           u32 length, value
19//! ```
20
21use std::collections::HashSet;
22use std::fmt;
23
24use crate::bytes::{In, Out, fits_u32};
25use crate::container::ChunkTag;
26use crate::scene::Scene;
27
28/// The tag of the metadata chunk.
29pub const METADATA_TAG: ChunkTag = ChunkTag(*b"META");
30
31/// The metadata payload layout this build writes and reads.
32pub const METADATA_VERSION: u16 = 1;
33
34/// The registered keys whose value is UTF-8 text (`SPEC.md`, 12.1).
35pub const TEXT_KEYS: [&str; 8] = [
36    "title",
37    "description",
38    "designer",
39    "copyright",
40    "license",
41    "source",
42    "created",
43    "generator",
44];
45
46/// The registered key whose value is the 16 bytes of a UUID.
47pub const UUID_KEY: &str = "uuid";
48
49/// The subject that stands for the whole file in a payload.
50const FILE: u32 = u32::MAX;
51
52/// The longest key, in bytes.
53const MAX_KEY: usize = 64;
54
55/// One entry of metadata.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct MetadataEntry {
58    /// The node the entry is about, as an index into the scene's nodes, or
59    /// `None` for the whole file.
60    pub node: Option<usize>,
61    /// What the value is: a registered key, such as `title`, or a program's
62    /// own, with a dot, such as `breadslicer.printer`.
63    pub key: String,
64    /// The value: UTF-8 text for the registered text keys, 16 bytes for
65    /// `uuid`, and whatever a program makes of it for its own keys.
66    pub value: Vec<u8>,
67}
68
69impl MetadataEntry {
70    /// An entry with a text value, such as a title.
71    pub fn text(node: Option<usize>, key: &str, text: &str) -> Self {
72        Self {
73            node,
74            key: key.into(),
75            value: text.as_bytes().to_vec(),
76        }
77    }
78
79    /// An entry with a UUID, given as its 16 bytes in the order of RFC 9562.
80    pub fn uuid(node: Option<usize>, uuid: [u8; 16]) -> Self {
81        Self {
82            node,
83            key: UUID_KEY.into(),
84            value: uuid.to_vec(),
85        }
86    }
87
88    /// The value as text, when the key is a registered text key.
89    pub fn as_text(&self) -> Option<&str> {
90        match key_kind(self.key.as_bytes()) {
91            KeyKind::Text => std::str::from_utf8(&self.value).ok(),
92            _ => None,
93        }
94    }
95
96    /// The value as a UUID, when the key is `uuid`.
97    pub fn as_uuid(&self) -> Option<[u8; 16]> {
98        match key_kind(self.key.as_bytes()) {
99            KeyKind::Uuid => self.value.as_slice().try_into().ok(),
100            _ => None,
101        }
102    }
103}
104
105/// Why a list of metadata entries could not be encoded.
106#[derive(Clone, Debug, PartialEq, Eq)]
107pub enum EncodeMetadataError {
108    /// An entry names a node the scene does not have.
109    NoSuchNode { node: usize },
110    /// A key is not 1 to 64 lowercase letters, digits, dots, hyphens and
111    /// underscores, starting with a letter.
112    BadKey { key: String },
113    /// A key without a dot that the format does not register.
114    ReservedKey { key: String },
115    /// A registered key's value is not what the key takes: UTF-8 text, or
116    /// 16 bytes for `uuid`.
117    BadValue { key: String },
118    /// Two entries have the same subject and key.
119    SameEntry { key: String },
120    /// There are 2^32 or more entries, or a value of 4 GiB or more.
121    TooLarge,
122}
123
124impl fmt::Display for EncodeMetadataError {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        match self {
127            Self::NoSuchNode { node } => write!(
128                f,
129                "metadata names node {node}, which the scene does not have"
130            ),
131            Self::BadKey { key } => write!(f, "{key:?} is not a metadata key"),
132            Self::ReservedKey { key } => write!(f, "the metadata key {key:?} is reserved"),
133            Self::BadValue { key } => write!(
134                f,
135                "the value of the metadata key {key:?} is not what it takes"
136            ),
137            Self::SameEntry { key } => write!(
138                f,
139                "two metadata entries have the same subject and the key {key:?}"
140            ),
141            Self::TooLarge => f.write_str("the metadata is too large for its chunk"),
142        }
143    }
144}
145
146impl std::error::Error for EncodeMetadataError {}
147
148/// What a key is.
149#[derive(Clone, Copy, PartialEq, Eq)]
150enum KeyKind {
151    /// A registered key with a text value.
152    Text,
153    /// `uuid`.
154    Uuid,
155    /// A program's own key: it has a dot.
156    Program,
157    /// A key without a dot that is not registered.
158    Reserved,
159    /// Not a key at all.
160    Invalid,
161}
162
163fn key_kind(key: &[u8]) -> KeyKind {
164    let well_formed = (1..=MAX_KEY).contains(&key.len())
165        && key[0].is_ascii_lowercase()
166        && key
167            .iter()
168            .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b));
169    if !well_formed {
170        return KeyKind::Invalid;
171    }
172    if key.contains(&b'.') {
173        return KeyKind::Program;
174    }
175    if key == UUID_KEY.as_bytes() {
176        return KeyKind::Uuid;
177    }
178    if TEXT_KEYS.iter().any(|text| text.as_bytes() == key) {
179        return KeyKind::Text;
180    }
181    KeyKind::Reserved
182}
183
184/// Whether `value` is what a key of `kind` takes.
185fn fits(kind: KeyKind, value: &[u8]) -> bool {
186    match kind {
187        KeyKind::Text => std::str::from_utf8(value).is_ok(),
188        KeyKind::Uuid => value.len() == 16,
189        KeyKind::Program => true,
190        KeyKind::Reserved | KeyKind::Invalid => false,
191    }
192}
193
194/// Encodes `entries` as a metadata payload, in their order, checking them
195/// against `scene`.
196pub fn encode_metadata(
197    entries: &[MetadataEntry],
198    scene: &Scene,
199) -> Result<Vec<u8>, EncodeMetadataError> {
200    let mut seen = HashSet::new();
201    for entry in entries {
202        if let Some(node) = entry.node
203            && node >= scene.nodes.len()
204        {
205            return Err(EncodeMetadataError::NoSuchNode { node });
206        }
207        let key = entry.key.clone();
208        match key_kind(entry.key.as_bytes()) {
209            KeyKind::Invalid => return Err(EncodeMetadataError::BadKey { key }),
210            KeyKind::Reserved => return Err(EncodeMetadataError::ReservedKey { key }),
211            kind if !fits(kind, &entry.value) => {
212                return Err(EncodeMetadataError::BadValue { key });
213            }
214            _ => {}
215        }
216        if !seen.insert((entry.node, entry.key.as_str())) {
217            return Err(EncodeMetadataError::SameEntry { key });
218        }
219    }
220    if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.value.len())) {
221        return Err(EncodeMetadataError::TooLarge);
222    }
223    let mut out = Out::default();
224    out.len(entries.len());
225    for entry in entries {
226        // A node was checked against the scene, whose node count fits.
227        out.u32(entry.node.map_or(FILE, |node| node as u32));
228        out.bytes(entry.key.as_bytes());
229        out.bytes(&entry.value);
230    }
231    Ok(out.0)
232}
233
234/// Decodes a metadata payload against `scene`, the scene of the same file.
235/// It never fails: a malformed payload is no metadata at all, and an entry
236/// that breaks a rule of section 12 is left out (`SPEC.md`, 12.2).
237pub fn decode_metadata(payload: &[u8], scene: &Scene) -> Vec<MetadataEntry> {
238    let Some(raw) = split(payload) else {
239        return Vec::new();
240    };
241    let mut seen = HashSet::new();
242    let mut entries = Vec::new();
243    for (subject, key, value) in raw {
244        // The second of two entries with the same subject and key is left
245        // out, whatever the first holds.
246        if !seen.insert((subject, key)) {
247            continue;
248        }
249        let node = match subject {
250            FILE => None,
251            node if (node as usize) < scene.nodes.len() => Some(node as usize),
252            _ => continue,
253        };
254        let kind = key_kind(key);
255        if !fits(kind, value) {
256            continue;
257        }
258        entries.push(MetadataEntry {
259            node,
260            // A key of any kind but `Invalid` is ASCII.
261            key: String::from_utf8_lossy(key).into_owned(),
262            value: value.to_vec(),
263        });
264    }
265    entries
266}
267
268/// An entry as stored: its subject, key and value.
269type RawEntry<'a> = (u32, &'a [u8], &'a [u8]);
270
271/// The entries of a payload as stored, or `None` when it is malformed.
272fn split(payload: &[u8]) -> Option<Vec<RawEntry<'_>>> {
273    let mut input = In(payload);
274    let count = input.count(12)?;
275    let mut raw = Vec::with_capacity(count);
276    for _ in 0..count {
277        let subject = input.u32()?;
278        let key = input.bytes()?;
279        let value = input.bytes()?;
280        raw.push((subject, key, value));
281    }
282    input.is_empty().then_some(raw)
283}