bread_format/
container.rs1use std::fmt;
22use std::io::{self, Read, Write};
23
24pub const MAGIC: [u8; 8] = *b"BREAD\0\r\n";
26
27pub const CONTAINER_VERSION: u16 = 1;
29
30const ZSTD_LEVEL: i32 = 3;
32
33#[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#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct Chunk {
46 pub tag: ChunkTag,
47 pub version: u16,
48 pub payload: Vec<u8>,
49}
50
51#[derive(Debug)]
53pub enum ReadBreadError {
54 Io(io::Error),
55 NotBread,
57 UnsupportedVersion(u16),
60 Truncated,
62 Corrupt(ChunkTag),
64 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#[derive(Debug)]
98pub struct BreadWriter<W: Write> {
99 out: W,
100}
101
102impl<W: Write> BreadWriter<W> {
103 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 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 pub fn finish(mut self) -> io::Result<W> {
124 self.out.flush()?;
125 Ok(self.out)
126 }
127}
128
129#[derive(Debug)]
131pub struct BreadReader<R: Read> {
132 input: R,
133}
134
135impl<R: Read> BreadReader<R> {
136 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 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 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
203fn 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
211const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd];
213
214fn 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}