Skip to main content

bread_format/
container.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The chunked container.
7//!
8//! Layout, all integers little-endian:
9//!
10//! ```text
11//! header  "BREAD\0\r\n" (8 bytes), container version u16
12//! chunk   tag [u8; 4], chunk version u16, raw length u64,
13//!         stored length u64, CRC-32 of the stored bytes u32,
14//!         stored bytes (zstd)
15//! ...     chunks until the end of the file
16//! ```
17//!
18//! The `\r\n` in the magic catches a file mangled by a text-mode transfer,
19//! as PNG's does.
20
21use std::fmt;
22use std::io::{self, Read, Write};
23
24/// The first bytes of every `.bread` file.
25pub const MAGIC: [u8; 8] = *b"BREAD\0\r\n";
26
27/// The container layout this build writes and reads.
28pub const CONTAINER_VERSION: u16 = 1;
29
30/// The zstd level chunks are written at: fast, and most of the ratio.
31const ZSTD_LEVEL: i32 = 3;
32
33/// A chunk's kind, four ASCII bytes.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub struct ChunkTag(pub [u8; 4]);
36
37impl fmt::Display for ChunkTag {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.write_str(&String::from_utf8_lossy(&self.0))
40    }
41}
42
43/// One chunk read back: its tag, version and decompressed payload.
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct Chunk {
46    pub tag: ChunkTag,
47    pub version: u16,
48    pub payload: Vec<u8>,
49}
50
51/// Why a `.bread` file could not be read.
52#[derive(Debug)]
53pub enum ReadBreadError {
54    Io(io::Error),
55    /// The file does not start with the `.bread` magic.
56    NotBread,
57    /// The file was written by a newer container layout, or has container
58    /// version 0, which no version is.
59    UnsupportedVersion(u16),
60    /// The file ends inside a chunk.
61    Truncated,
62    /// A chunk's bytes do not match their checksum.
63    Corrupt(ChunkTag),
64    /// A chunk's payload does not decompress to its recorded length.
65    BadPayload(ChunkTag),
66}
67
68impl fmt::Display for ReadBreadError {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match self {
71            Self::Io(err) => write!(f, "{err}"),
72            Self::NotBread => f.write_str("not a .bread file"),
73            Self::UnsupportedVersion(0) => f.write_str("container version 0, which does not exist"),
74            Self::UnsupportedVersion(v) => {
75                write!(f, "written in a newer container version ({v})")
76            }
77            Self::Truncated => f.write_str("the file is cut short"),
78            Self::Corrupt(tag) => write!(f, "the {tag} chunk is damaged"),
79            Self::BadPayload(tag) => write!(f, "the {tag} chunk does not decode"),
80        }
81    }
82}
83
84impl std::error::Error for ReadBreadError {}
85
86impl From<io::Error> for ReadBreadError {
87    fn from(err: io::Error) -> Self {
88        if err.kind() == io::ErrorKind::UnexpectedEof {
89            Self::Truncated
90        } else {
91            Self::Io(err)
92        }
93    }
94}
95
96/// Writes a `.bread` file chunk by chunk.
97#[derive(Debug)]
98pub struct BreadWriter<W: Write> {
99    out: W,
100}
101
102impl<W: Write> BreadWriter<W> {
103    /// Starts a file: writes the header.
104    pub fn new(mut out: W) -> io::Result<Self> {
105        out.write_all(&MAGIC)?;
106        out.write_all(&CONTAINER_VERSION.to_le_bytes())?;
107        Ok(Self { out })
108    }
109
110    /// Compresses `payload` and writes it as one chunk.
111    pub fn chunk(&mut self, tag: ChunkTag, version: u16, payload: &[u8]) -> io::Result<()> {
112        let stored = zstd::bulk::compress(payload, ZSTD_LEVEL)?;
113        self.out.write_all(&tag.0)?;
114        self.out.write_all(&version.to_le_bytes())?;
115        self.out.write_all(&(payload.len() as u64).to_le_bytes())?;
116        self.out.write_all(&(stored.len() as u64).to_le_bytes())?;
117        self.out
118            .write_all(&crc32fast::hash(&stored).to_le_bytes())?;
119        self.out.write_all(&stored)
120    }
121
122    /// Ends the file, handing back the writer.
123    pub fn finish(mut self) -> io::Result<W> {
124        self.out.flush()?;
125        Ok(self.out)
126    }
127}
128
129/// Reads a `.bread` file chunk by chunk.
130#[derive(Debug)]
131pub struct BreadReader<R: Read> {
132    input: R,
133}
134
135impl<R: Read> BreadReader<R> {
136    /// Opens a file: checks the header.
137    pub fn new(mut input: R) -> Result<Self, ReadBreadError> {
138        let mut magic = [0; 8];
139        input
140            .read_exact(&mut magic)
141            .map_err(|err| match err.kind() {
142                io::ErrorKind::UnexpectedEof => ReadBreadError::NotBread,
143                _ => ReadBreadError::Io(err),
144            })?;
145        if magic != MAGIC {
146            return Err(ReadBreadError::NotBread);
147        }
148        let version = read_u16(&mut input)?;
149        if version == 0 || version > CONTAINER_VERSION {
150            return Err(ReadBreadError::UnsupportedVersion(version));
151        }
152        Ok(Self { input })
153    }
154
155    /// The next chunk, decompressed and checked, or `None` at the end of the
156    /// file.
157    pub fn next_chunk(&mut self) -> Result<Option<Chunk>, ReadBreadError> {
158        let mut tag = [0; 4];
159        match read_fully(&mut self.input, &mut tag)? {
160            0 => return Ok(None),
161            4 => {}
162            _ => return Err(ReadBreadError::Truncated),
163        }
164        let tag = ChunkTag(tag);
165        let version = read_u16(&mut self.input)?;
166        let raw_len = read_u64(&mut self.input)?;
167        let stored_len = read_u64(&mut self.input)?;
168        let crc = read_u32(&mut self.input)?;
169        let mut stored = Vec::new();
170        (&mut self.input)
171            .take(stored_len)
172            .read_to_end(&mut stored)?;
173        if stored.len() as u64 != stored_len {
174            return Err(ReadBreadError::Truncated);
175        }
176        if crc32fast::hash(&stored) != crc {
177            return Err(ReadBreadError::Corrupt(tag));
178        }
179        if !is_one_frame(&stored) {
180            return Err(ReadBreadError::BadPayload(tag));
181        }
182        // Streamed, not preallocated from the recorded length: a damaged
183        // length cannot ask for more memory than the payload really holds.
184        let mut payload = Vec::new();
185        zstd::stream::read::Decoder::new(stored.as_slice())
186            .and_then(|decoder| {
187                decoder
188                    .take(raw_len.saturating_add(1))
189                    .read_to_end(&mut payload)
190            })
191            .map_err(|_| ReadBreadError::BadPayload(tag))?;
192        if payload.len() as u64 != raw_len {
193            return Err(ReadBreadError::BadPayload(tag));
194        }
195        Ok(Some(Chunk {
196            tag,
197            version,
198            payload,
199        }))
200    }
201}
202
203/// Whether `stored` is exactly one Zstandard frame, not a skippable one, with
204/// nothing after it (`SPEC.md`, section 4.3). The stream decoder alone would
205/// also read several frames in a row, and skip skippable ones.
206fn is_one_frame(stored: &[u8]) -> bool {
207    stored.starts_with(&ZSTD_MAGIC)
208        && zstd::zstd_safe::find_frame_compressed_size(stored) == Ok(stored.len())
209}
210
211/// The first four bytes of a Zstandard frame that holds data.
212const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd];
213
214/// Reads until `buf` is full or the input ends; returns the bytes read.
215fn read_fully(input: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
216    let mut filled = 0;
217    while filled < buf.len() {
218        match input.read(&mut buf[filled..]) {
219            Ok(0) => break,
220            Ok(n) => filled += n,
221            Err(err) if err.kind() == io::ErrorKind::Interrupted => {}
222            Err(err) => return Err(err),
223        }
224    }
225    Ok(filled)
226}
227
228fn read_u16(input: &mut impl Read) -> io::Result<u16> {
229    let mut bytes = [0; 2];
230    input.read_exact(&mut bytes)?;
231    Ok(u16::from_le_bytes(bytes))
232}
233
234fn read_u32(input: &mut impl Read) -> io::Result<u32> {
235    let mut bytes = [0; 4];
236    input.read_exact(&mut bytes)?;
237    Ok(u32::from_le_bytes(bytes))
238}
239
240fn read_u64(input: &mut impl Read) -> io::Result<u64> {
241    let mut bytes = [0; 8];
242    input.read_exact(&mut bytes)?;
243    Ok(u64::from_le_bytes(bytes))
244}