ifc_template_catalog/
snapshot.rs1use thiserror::Error;
21
22use crate::catalog::{Catalog, CatalogError, CatalogProfile};
23use crate::definition::CatalogEdition;
24use crate::pack::{self, PackError};
25
26pub const FORMAT_VERSION: u16 = 3;
28
29pub const CONTAINER_SHA256: &str =
32 "bcfa9a7efa4d01af50cd4a3a12b99e2da2b4097630d2fcc100877c104b18510e";
33
34pub const EDITIONS: [CatalogEdition; 3] = [
36 CatalogEdition::Ifc2x3Tc1,
37 CatalogEdition::Ifc4Add2Tc1,
38 CatalogEdition::Ifc4x3Add2,
39];
40
41pub fn file_name(edition: CatalogEdition) -> &'static str {
44 match edition {
45 CatalogEdition::Ifc2x3Tc1 => "ifc2x3-tc1.bin",
46 CatalogEdition::Ifc4Add2Tc1 => "ifc4-add2-tc1.bin",
47 CatalogEdition::Ifc4x3Add2 => "ifc4x3-add2.bin",
48 }
49}
50
51pub fn pinned_sha256(edition: CatalogEdition) -> &'static str {
54 match edition {
55 CatalogEdition::Ifc2x3Tc1 => {
56 "484c8d50d1f374aa2fec0793be5508d8a02faa0455f7de4f142e6001469e5504"
57 }
58 CatalogEdition::Ifc4Add2Tc1 => {
59 "1ea624205c45cb31489f265c53fcef1334ba8556046cf296f73ee4e7550c6539"
60 }
61 CatalogEdition::Ifc4x3Add2 => {
62 "3cb41a5a7bb7bd81990872b1abd47b029691241447d478aa9ce0e82eb6bbf89b"
63 }
64 }
65}
66
67pub fn editions(bytes: &[u8]) -> Result<Vec<CatalogEdition>, ArchiveError> {
70 check_header(bytes)?;
71 pack::editions(bytes).map_err(ArchiveError::from)
72}
73
74pub fn decode_edition(bytes: &[u8], edition: CatalogEdition) -> Result<Catalog, ArchiveError> {
79 check_header(bytes)?;
80 pack::decode_one(bytes, edition)?.ok_or(ArchiveError::MissingEdition(edition))
81}
82
83pub fn decode_all(bytes: &[u8]) -> Result<Vec<Catalog>, ArchiveError> {
86 check_header(bytes)?;
87 pack::decode_all(bytes).map_err(ArchiveError::from)
88}
89
90pub fn encode(catalogs: &[&Catalog]) -> Result<Vec<u8>, EncodeError> {
94 let mut sorted: Vec<&Catalog> = catalogs.to_vec();
95 sorted.sort_by_key(|catalog| catalog.manifest().edition);
96 for pair in sorted.windows(2) {
97 if pair[0].manifest().edition == pair[1].manifest().edition {
98 return Err(EncodeError::DuplicateEdition(pair[0].manifest().edition));
99 }
100 }
101 if let Some(catalog) = sorted
102 .iter()
103 .find(|catalog| catalog.profile() != CatalogProfile::Official)
104 {
105 return Err(EncodeError::NotOfficial(catalog.profile()));
106 }
107 let templates: Vec<Vec<_>> = sorted
108 .iter()
109 .map(|catalog| catalog.iter().cloned().collect())
110 .collect();
111 let editions: Vec<_> = sorted
112 .iter()
113 .zip(&templates)
114 .map(|(catalog, templates)| (catalog.manifest(), templates.as_slice()))
115 .collect();
116 Ok(pack::encode(&editions))
117}
118
119fn check_header(bytes: &[u8]) -> Result<(), ArchiveError> {
120 if bytes.len() > pack::MAX_BYTES {
121 return Err(ArchiveError::TooLarge {
122 actual: bytes.len(),
123 limit: pack::MAX_BYTES,
124 });
125 }
126 if !bytes.starts_with(&pack::MAGIC) {
127 return Err(ArchiveError::BadMagic);
128 }
129 if bytes.len() < MIN_HEADER_BYTES {
130 return Err(ArchiveError::TruncatedHeader {
131 actual: bytes.len(),
132 required: MIN_HEADER_BYTES,
133 });
134 }
135 Ok(())
136}
137
138const MIN_HEADER_BYTES: usize = pack::MAGIC.len() + 1;
139
140#[derive(Debug, Clone, PartialEq, Eq, Error)]
142#[non_exhaustive]
143pub enum EncodeError {
144 #[error("only official catalogs are encoded, not {0:?}")]
147 NotOfficial(CatalogProfile),
148 #[error("edition {0:?} is given twice")]
150 DuplicateEdition(CatalogEdition),
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Error)]
155#[non_exhaustive]
156pub enum ArchiveError {
157 #[error("cannot decode catalog artifact: {0}")]
159 Decode(String),
160 #[error("catalog artifact is {actual} bytes; limit is {limit} bytes")]
162 TooLarge {
163 actual: usize,
165 limit: usize,
167 },
168 #[error("catalog artifact header is {actual} bytes; at least {required} bytes are required")]
170 TruncatedHeader {
171 actual: usize,
173 required: usize,
175 },
176 #[error("catalog artifact magic is invalid")]
178 BadMagic,
179 #[error("unsupported catalog artifact format version {0}")]
181 UnsupportedVersion(u16),
182 #[error("catalog artifact has {0} trailing bytes")]
184 TrailingBytes(usize),
185 #[error(transparent)]
187 Catalog(#[from] CatalogError),
188 #[error("the catalog artifact holds no {0:?} edition")]
190 MissingEdition(CatalogEdition),
191}
192
193impl From<PackError> for ArchiveError {
194 fn from(error: PackError) -> Self {
195 match error {
196 PackError::TooLarge(actual) => Self::TooLarge {
197 actual,
198 limit: pack::MAX_BYTES,
199 },
200 PackError::BadMagic => Self::BadMagic,
201 PackError::UnsupportedVersion(version) => match u16::try_from(version) {
202 Ok(version) => Self::UnsupportedVersion(version),
203 Err(_) => Self::Decode(format!("format version {version} is out of range")),
204 },
205 PackError::Malformed(what) => Self::Decode(what.to_owned()),
206 PackError::TrailingBytes(count) => Self::TrailingBytes(count),
207 PackError::Catalog(error) => Self::Catalog(error),
208 }
209 }
210}
211
212#[cfg(test)]
213mod tests {
214 use super::{decode_all, decode_edition, ArchiveError};
215 use crate::definition::CatalogEdition;
216 use crate::pack::{MAGIC, MAX_BYTES};
217
218 fn container() -> &'static [u8] {
219 include_bytes!("../data/catalog.bin")
220 }
221
222 #[test]
223 fn reports_format_version_before_decoding_its_payload() {
224 let mut bytes = MAGIC.to_vec();
225 bytes.push(2); bytes.push(1); assert_eq!(
228 decode_all(&bytes).unwrap_err(),
229 ArchiveError::UnsupportedVersion(2)
230 );
231 }
232
233 #[test]
234 fn rejects_truncated_header() {
235 assert!(matches!(
236 decode_all(&MAGIC),
237 Err(ArchiveError::TruncatedHeader { .. })
238 ));
239 }
240
241 #[test]
242 fn rejects_trailing_bytes() {
243 let mut bytes = container().to_vec();
244 bytes.push(0);
245 assert!(matches!(
246 decode_edition(&bytes, CatalogEdition::Ifc4Add2Tc1),
247 Err(ArchiveError::TrailingBytes(1))
248 ));
249 }
250
251 #[test]
252 fn rejects_every_truncation_of_a_small_snapshot() {
253 let catalog = decode_edition(container(), CatalogEdition::Ifc2x3Tc1).unwrap();
254 let bytes = super::encode(&[&catalog]).unwrap();
255 for len in (0..bytes.len()).step_by(997) {
257 assert!(decode_all(&bytes[..len]).is_err(), "cut at {len}");
258 }
259 }
260
261 #[test]
262 fn rejects_a_flipped_record_byte_without_panicking() {
263 let catalog = decode_edition(container(), CatalogEdition::Ifc2x3Tc1).unwrap();
264 let bytes = super::encode(&[&catalog]).unwrap();
265 for at in (MAGIC.len()..bytes.len()).step_by(4099) {
266 let mut corrupt = bytes.clone();
267 corrupt[at] ^= 0xff;
268 let _ = decode_all(&corrupt);
270 }
271 }
272
273 #[test]
274 fn decode_rejects_input_above_resource_budget() {
275 let bytes = vec![0; MAX_BYTES + 1];
276 assert!(matches!(
277 decode_all(&bytes),
278 Err(ArchiveError::TooLarge { .. })
279 ));
280 }
281
282 #[test]
283 fn a_missing_edition_is_named() {
284 let catalog = decode_edition(container(), CatalogEdition::Ifc2x3Tc1).unwrap();
285 let bytes = super::encode(&[&catalog]).unwrap();
286 assert_eq!(
287 decode_edition(&bytes, CatalogEdition::Ifc4x3Add2).unwrap_err(),
288 ArchiveError::MissingEdition(CatalogEdition::Ifc4x3Add2)
289 );
290 }
291}