Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 26.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Indexes of sealed segments (format spec, section 7).
5//!
6//! An index lists, in id order, where the records of one or more sealed
7//! segments are. It is written once, to a temporary file that is flushed and
8//! renamed into place, and never changes afterwards.
9//!
10//! **Version 2**, which this version writes (storage version 3): the index of
11//! one segment, `seg/<name>.idx`, or a merged index of several,
12//! `seg/<name>.midx`.
13//!
14//! ```text
15//! [8] "braididx" | u32 version = 2 | u32 0 | u64 count | u32 segments
16//! u32 crc32c of the 28 bytes before it
17//! segments × ([16] segment name | u64 segment length)
18//! 256 × u32 fan-out: entry b counts the ids whose first byte is at most b
19//! u32 crc32c of the segment table and the fan-out
20//! count × 64-byte entries, ids strictly ascending:
21//! [32] id | u64 offset | u32 stored_len | u8 kind | u8 codec | u16 segment
22//! u64 raw_len | u32 record crc | u32 crc32c of the 60 bytes before it
23//! ```
24//!
25//! An entry is a journal entry whose reserved field holds the number of its
26//! segment in the table, 0 in the index of one segment. A segment name is
27//! the 32 hex digits of its file name as 16 bytes, and its length the size
28//! of the segment when it was sealed. Every part has a checksum of its own,
29//! so a reader takes in what a lookup needs and checks only that: the head
30//! (everything up to the second checksum) when it first uses the index, and
31//! the entries of one fan-out bucket, the ids that share their first byte,
32//! when a lookup first needs that bucket. The cost of a lookup follows the
33//! size of a bucket, not the size of the index.
34//!
35//! **Version 1** (storage versions 1 and 2), the index of one segment, read
36//! and checked whole:
37//!
38//! ```text
39//! [8] magic "braididx" | u32 version = 1 | u32 0 | u64 count | u64 segment length
40//! 256 × u32 fan-out: entry i is the number of ids whose first byte is at most i
41//! count × [32] ids, strictly ascending
42//! count × 32-byte locations, in the same order as the ids:
43//! u64 offset | u32 stored_len | u8 kind | u8 codec | u16 0
44//! u64 raw_len | u32 record crc | u32 0
45//! [32] BLAKE3 hash of everything before it
46//! ```
47//!
48//! An index whose checksums hold but whose version, reserved fields or
49//! entries this version does not know was written by a newer version of
50//! braid, and is refused rather than taken for damage. The first 32 bytes
51//! of every version after 1 carry their own checksum, so that a reader can
52//! tell a later version from damage without knowing its layout.
53
54use std::ops::Range;
55
56use crate::journal::{ENTRY_LEN, Entry, Unusable};
57use crate::record::array;
58
59/// Why an index cannot be used.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub(crate) enum IndexError {
62 /// It fails its checksums or its structure checks. Lookups work around
63 /// it by scanning the segments it covers.
64 Damaged(&'static str),
65 /// It is whole, but a newer version of braid wrote it.
66 Newer(&'static str),
67}
68
69const MAGIC: &[u8; 8] = b"braididx";
70const VERSION_1: u32 = 1;
71const VERSION_2: u32 = 2;
72/// Bytes of the fixed header every version starts with.
73pub(crate) const HEADER_LEN: usize = 32;
74/// Bytes of one segment in the table of a version 2 index.
75const COVERED_LEN: usize = 24;
76const FANOUT_LEN: usize = 256 * 4;
77const CRC_LEN: usize = 4;
78/// Bytes of a version 1 location.
79const V1_LOCATION_LEN: usize = 32;
80/// Bytes of the hash that ends a version 1 index.
81const V1_FOOTER_LEN: usize = 32;
82
83/// The most segments one index covers: entries number theirs with a u16.
84pub(crate) const MAX_COVERED: usize = 1 << 16;
85
86/// An entry, with the number of its segment in the index that holds it.
87pub(crate) type Numbered = (Entry, u16);
88
89/// A sealed segment an index covers.
90#[derive(Clone, Debug, PartialEq, Eq)]
91pub(crate) struct Covered {
92 /// Its name: 32 lowercase hex digits.
93 pub name: String,
94 /// Its length when it was sealed. No entry points past it.
95 pub len: u64,
96}
97
98/// What the fixed header of an index says.
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
100pub(crate) enum Header {
101 /// A version 1 index: it is read and checked whole.
102 V1,
103 /// A version 2 index of `count` entries for `segments` segments.
104 V2 { count: u64, segments: usize },
105}
106
107impl Header {
108 /// Bytes of a version 2 index's head, from the start of the file to its
109 /// first entry.
110 pub fn head_len(segments: usize) -> usize {
111 HEADER_LEN + COVERED_LEN * segments + FANOUT_LEN + CRC_LEN
112 }
113}
114
115/// Reads the fixed header, the first [`HEADER_LEN`] bytes of an index.
116pub(crate) fn header(bytes: &[u8]) -> Result<Header, IndexError> {
117 use IndexError::{Damaged, Newer};
118 if bytes.len() < HEADER_LEN {
119 return Err(Damaged("index file cut short"));
120 }
121 if &bytes[0..8] != MAGIC {
122 return Err(Damaged("not an index file"));
123 }
124 let version = u32::from_le_bytes(array(&bytes[8..12]));
125 if version == VERSION_1 {
126 // Its hash, at the end of the file, says whether it is whole.
127 return Ok(Header::V1);
128 }
129 if crc32c::crc32c(&bytes[..28]) != u32::from_le_bytes(array(&bytes[28..32])) {
130 return Err(Damaged("index header checksum mismatch"));
131 }
132 // Whole from here on: what this version does not know is news.
133 match version {
134 VERSION_2 => {}
135 0 => return Err(Damaged("index version 0")),
136 _ => return Err(Newer("an index version this version does not know")),
137 }
138 if u32::from_le_bytes(array(&bytes[12..16])) != 0 {
139 return Err(Newer("a reserved index field is set"));
140 }
141 let count = u64::from_le_bytes(array(&bytes[16..24]));
142 let segments = u32::from_le_bytes(array(&bytes[24..28])) as usize;
143 if segments == 0 || segments > MAX_COVERED {
144 return Err(Damaged("index covers no segment, or too many"));
145 }
146 Ok(Header::V2 { count, segments })
147}
148
149/// The head of a version 2 index: what it covers, and where its entries are.
150#[derive(Clone, Debug)]
151pub(crate) struct Head {
152 /// The segments it covers, by their number in it.
153 pub covered: Vec<Covered>,
154 /// How many entries it holds.
155 pub count: u64,
156 /// Entry `b` is the number of entries whose id's first byte is at most `b`.
157 fanout: Vec<u32>,
158}
159
160impl Head {
161 /// Bytes from the start of the file to the first entry.
162 pub fn len(&self) -> u64 {
163 Header::head_len(self.covered.len()) as u64
164 }
165
166 /// Bytes of the whole index.
167 pub fn file_len(&self) -> u64 {
168 self.len() + self.count * ENTRY_LEN
169 }
170
171 /// The numbers of the entries whose ids start with `byte`.
172 pub fn bucket(&self, byte: u8) -> Range<u64> {
173 let end = u64::from(self.fanout[usize::from(byte)]);
174 let start = match byte {
175 0 => 0,
176 _ => u64::from(self.fanout[usize::from(byte) - 1]),
177 };
178 start..end
179 }
180
181 /// Where entry `n` starts in the file.
182 pub fn entry_offset(&self, n: u64) -> u64 {
183 self.len() + n * ENTRY_LEN
184 }
185}
186
187/// Reads the head of a version 2 index: its first
188/// [`Header::head_len`] bytes.
189pub(crate) fn head(bytes: &[u8]) -> Result<Head, IndexError> {
190 use IndexError::Damaged;
191 let Header::V2 { count, segments } = header(bytes)? else {
192 return Err(Damaged("a version 1 index has no head of its own"));
193 };
194 let len = Header::head_len(segments);
195 if bytes.len() < len {
196 return Err(Damaged("index file cut short"));
197 }
198 let checked = &bytes[HEADER_LEN..len - CRC_LEN];
199 if crc32c::crc32c(checked) != u32::from_le_bytes(array(&bytes[len - CRC_LEN..len])) {
200 return Err(Damaged("index head checksum mismatch"));
201 }
202 let (table, fanout) = checked.split_at(COVERED_LEN * segments);
203 let mut covered = Vec::with_capacity(segments);
204 for slot in table.as_chunks::<COVERED_LEN>().0 {
205 let name = hex(&slot[..16]);
206 if covered.iter().any(|seen: &Covered| seen.name == name) {
207 return Err(Damaged("index names a segment twice"));
208 }
209 covered.push(Covered {
210 name,
211 len: u64::from_le_bytes(array(&slot[16..24])),
212 });
213 }
214 let fanout: Vec<u32> = fanout
215 .as_chunks::<4>()
216 .0
217 .iter()
218 .map(|value| u32::from_le_bytes(*value))
219 .collect();
220 if fanout.windows(2).any(|pair| pair[0] > pair[1]) || u64::from(fanout[255]) != count {
221 return Err(Damaged(
222 "index fan-out table does not match its entry count",
223 ));
224 }
225 Ok(Head {
226 covered,
227 count,
228 fanout,
229 })
230}
231
232/// Checks and decodes the entries of the bucket of ids that start with
233/// `byte`, read from the file as [`Head::bucket`] says.
234pub(crate) fn bucket(head: &Head, byte: u8, bytes: &[u8]) -> Result<Vec<(Entry, u16)>, IndexError> {
235 let expected = head.bucket(byte);
236 if bytes.len() as u64 != (expected.end - expected.start) * ENTRY_LEN {
237 return Err(IndexError::Damaged("index bucket cut short"));
238 }
239 let mut entries: Vec<(Entry, u16)> = Vec::with_capacity(bytes.len() / ENTRY_LEN as usize);
240 for slot in bytes.as_chunks::<{ ENTRY_LEN as usize }>().0 {
241 let (entry, segment) = Entry::decode_in(slot).map_err(|unusable| match unusable {
242 Unusable::Invalid => IndexError::Damaged("index entry fails its checksum"),
243 Unusable::Newer => {
244 IndexError::Newer("an object kind or codec this version does not know")
245 }
246 })?;
247 if entry.id.as_bytes()[0] != byte
248 || entries
249 .last()
250 .is_some_and(|(previous, _)| previous.id >= entry.id)
251 {
252 return Err(IndexError::Damaged("index ids are not strictly ascending"));
253 }
254 let Some(covered) = head.covered.get(usize::from(segment)) else {
255 return Err(IndexError::Damaged(
256 "index entry names a segment it does not cover",
257 ));
258 };
259 if entry.end() > covered.len {
260 return Err(IndexError::Damaged(
261 "index entry points past the end of the segment",
262 ));
263 }
264 entries.push((entry, segment));
265 }
266 Ok(entries)
267}
268
269/// Encodes a version 2 index of `covered`. `entries` must be sorted by id,
270/// without duplicates, each with the number of its segment in `covered`.
271pub(crate) fn encode(covered: &[Covered], entries: &[(Entry, u16)]) -> Vec<u8> {
272 debug_assert!(!covered.is_empty() && covered.len() <= MAX_COVERED);
273 debug_assert!(entries.windows(2).all(|pair| pair[0].0.id < pair[1].0.id));
274 let head_len = Header::head_len(covered.len());
275 let mut out = Vec::with_capacity(head_len + entries.len() * ENTRY_LEN as usize);
276 out.extend_from_slice(MAGIC);
277 out.extend_from_slice(&VERSION_2.to_le_bytes());
278 out.extend_from_slice(&0u32.to_le_bytes());
279 out.extend_from_slice(&(entries.len() as u64).to_le_bytes());
280 out.extend_from_slice(&(covered.len() as u32).to_le_bytes());
281 let crc = crc32c::crc32c(&out);
282 out.extend_from_slice(&crc.to_le_bytes());
283 for segment in covered {
284 out.extend_from_slice(&unhex(&segment.name));
285 out.extend_from_slice(&segment.len.to_le_bytes());
286 }
287 let mut fanout = [0u32; 256];
288 for (entry, _) in entries {
289 fanout[usize::from(entry.id.as_bytes()[0])] += 1;
290 }
291 let mut total = 0u32;
292 for slot in &mut fanout {
293 total += *slot;
294 *slot = total;
295 out.extend_from_slice(&slot.to_le_bytes());
296 }
297 let crc = crc32c::crc32c(&out[HEADER_LEN..]);
298 out.extend_from_slice(&crc.to_le_bytes());
299 for (entry, segment) in entries {
300 out.extend_from_slice(&entry.encode_in(*segment));
301 }
302 out
303}
304
305/// A whole index, decoded and checked.
306#[derive(Debug)]
307pub(crate) struct Decoded {
308 /// The segments it covers. A version 1 index covers the segment its file
309 /// is named after.
310 pub covered: Vec<Covered>,
311 /// Its entries, sorted by id, each with the number of its segment.
312 pub entries: Vec<(Entry, u16)>,
313}
314
315/// Decodes and checks a whole index of either version. `own` is the name of
316/// the segment whose own index this is, or `None` for a merged index.
317pub(crate) fn decode(bytes: &[u8], own: Option<&str>) -> Result<Decoded, IndexError> {
318 use IndexError::Damaged;
319 let decoded = match header(bytes)? {
320 Header::V1 => {
321 let Some(name) = own else {
322 return Err(Damaged("a merged index of version 1"));
323 };
324 let (entries, len) = decode_v1(bytes)?;
325 Decoded {
326 covered: vec![Covered {
327 name: name.to_owned(),
328 len,
329 }],
330 entries: entries.into_iter().map(|entry| (entry, 0)).collect(),
331 }
332 }
333 Header::V2 { .. } => {
334 let head = head(bytes)?;
335 if bytes.len() as u64 != head.file_len() {
336 return Err(Damaged("index length does not match its entry count"));
337 }
338 let mut entries = Vec::with_capacity(head.count as usize);
339 for byte in 0..=255u8 {
340 let range = head.bucket(byte);
341 let start = head.entry_offset(range.start) as usize;
342 let end = head.entry_offset(range.end) as usize;
343 entries.extend(bucket(&head, byte, &bytes[start..end])?);
344 }
345 Decoded {
346 covered: head.covered,
347 entries,
348 }
349 }
350 };
351 if let Some(name) = own
352 && (decoded.covered.len() != 1 || decoded.covered[0].name != name)
353 {
354 return Err(Damaged("the index of another segment"));
355 }
356 Ok(decoded)
357}
358
359/// Decodes and checks a version 1 index: its entries and the segment's
360/// length when it was sealed.
361fn decode_v1(bytes: &[u8]) -> Result<(Vec<Entry>, u64), IndexError> {
362 use IndexError::{Damaged, Newer};
363 if bytes.len() < HEADER_LEN + FANOUT_LEN + V1_FOOTER_LEN {
364 return Err(Damaged("index file cut short"));
365 }
366 let (body, footer) = bytes.split_at(bytes.len() - V1_FOOTER_LEN);
367 if blake3::hash(body).as_bytes() != footer {
368 return Err(Damaged("index checksum mismatch"));
369 }
370 // Whole from here on: what this version does not know is news, not
371 // damage.
372 if u32::from_le_bytes(array(&body[12..16])) != 0 {
373 return Err(Newer("a reserved index field is set"));
374 }
375 let count = u64::from_le_bytes(array(&body[16..24]));
376 let segment_len = u64::from_le_bytes(array(&body[24..32]));
377 let count = usize::try_from(count).map_err(|_| Damaged("index entry count too large"))?;
378 let expected = count
379 .checked_mul(32 + V1_LOCATION_LEN)
380 .and_then(|n| n.checked_add(HEADER_LEN + FANOUT_LEN))
381 .ok_or(Damaged("index entry count too large"))?;
382 if body.len() != expected {
383 return Err(Damaged("index length does not match its entry count"));
384 }
385
386 let fanout = &body[HEADER_LEN..HEADER_LEN + FANOUT_LEN];
387 let ids = &body[HEADER_LEN + FANOUT_LEN..HEADER_LEN + FANOUT_LEN + count * 32];
388 let locations = &body[HEADER_LEN + FANOUT_LEN + count * 32..];
389
390 let mut entries = Vec::with_capacity(count);
391 for i in 0..count {
392 let id = &ids[i * 32..i * 32 + 32];
393 let location = &locations[i * V1_LOCATION_LEN..(i + 1) * V1_LOCATION_LEN];
394 if u32::from_le_bytes(array(&location[28..32])) != 0 {
395 return Err(Newer("a reserved location field is set"));
396 }
397 let entry = Entry::from_fields(id, &location[..28]).map_err(|unusable| match unusable {
398 Unusable::Invalid => Damaged("invalid index location"),
399 Unusable::Newer => Newer("an object kind or codec this version does not know"),
400 })?;
401 if entry.end() > segment_len {
402 return Err(Damaged("index entry points past the end of the segment"));
403 }
404 if entries
405 .last()
406 .is_some_and(|previous: &Entry| previous.id >= entry.id)
407 {
408 return Err(Damaged("index ids are not strictly ascending"));
409 }
410 entries.push(entry);
411 }
412
413 let mut below = 0usize;
414 for (byte, value) in fanout.as_chunks::<4>().0.iter().enumerate() {
415 below += entries[below..]
416 .iter()
417 .take_while(|entry| usize::from(entry.id.as_bytes()[0]) == byte)
418 .count();
419 if u32::from_le_bytes(array(value)) as usize != below {
420 return Err(Damaged("index fan-out table does not match its ids"));
421 }
422 }
423 Ok((entries, segment_len))
424}
425
426/// The 32 hex digits of a 16-byte segment name.
427fn hex(bytes: &[u8]) -> String {
428 const DIGITS: &[u8; 16] = b"0123456789abcdef";
429 let mut out = String::with_capacity(bytes.len() * 2);
430 for byte in bytes {
431 out.push(char::from(DIGITS[usize::from(byte >> 4)]));
432 out.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
433 }
434 out
435}
436
437/// The 16 bytes of a segment name, 32 lowercase hex digits.
438fn unhex(name: &str) -> [u8; 16] {
439 debug_assert!(crate::fsutil::is_random_name(name));
440 let digit = |b: u8| match b {
441 b'0'..=b'9' => b - b'0',
442 _ => b - b'a' + 10,
443 };
444 let mut out = [0u8; 16];
445 for (slot, pair) in out.iter_mut().zip(name.as_bytes().as_chunks::<2>().0) {
446 *slot = digit(pair[0]) << 4 | digit(pair[1]);
447 }
448 out
449}
450
451/// Encodes a version 1 index, as storage versions 1 and 2 wrote them, for
452/// tests of stores that older versions left.
453#[cfg(test)]
454pub(crate) fn encode_v1(entries: &[Entry], segment_len: u64) -> Vec<u8> {
455 let count = entries.len();
456 let mut out = Vec::with_capacity(
457 HEADER_LEN + FANOUT_LEN + count * (32 + V1_LOCATION_LEN) + V1_FOOTER_LEN,
458 );
459 out.extend_from_slice(MAGIC);
460 out.extend_from_slice(&VERSION_1.to_le_bytes());
461 out.extend_from_slice(&0u32.to_le_bytes());
462 out.extend_from_slice(&(count as u64).to_le_bytes());
463 out.extend_from_slice(&segment_len.to_le_bytes());
464 let mut fanout = [0u32; 256];
465 for entry in entries {
466 fanout[usize::from(entry.id.as_bytes()[0])] += 1;
467 }
468 let mut total = 0u32;
469 for slot in &mut fanout {
470 total += *slot;
471 *slot = total;
472 out.extend_from_slice(&slot.to_le_bytes());
473 }
474 for entry in entries {
475 out.extend_from_slice(entry.id.as_bytes());
476 }
477 for entry in entries {
478 out.extend_from_slice(&entry.encode()[32..60]);
479 out.extend_from_slice(&0u32.to_le_bytes());
480 }
481 let hash = blake3::hash(&out);
482 out.extend_from_slice(hash.as_bytes());
483 out
484}
485
486#[cfg(test)]
487mod tests {
488 use braid_format::{Kind, ObjectId};
489
490 use super::*;
491 use crate::record;
492
493 fn entries(n: usize) -> Vec<Entry> {
494 entries_of(0..n)
495 }
496
497 fn entries_of(objects: std::ops::Range<usize>) -> Vec<Entry> {
498 let mut offset = 0;
499 let mut entries: Vec<Entry> = objects
500 .map(|i| {
501 let payload = format!("object number {i}").repeat(i % 7 + 1);
502 let id = ObjectId::hash(Kind::Blob, payload.as_bytes());
503 let encoded = record::encode(Kind::Blob, id, payload.as_bytes()).unwrap();
504 let entry = Entry::new(offset, &encoded.header, encoded.crc);
505 offset += encoded.bytes.len() as u64;
506 entry
507 })
508 .collect();
509 entries.sort_by_key(|entry| entry.id);
510 entries
511 }
512
513 fn segment_len(entries: &[Entry]) -> u64 {
514 entries.iter().map(Entry::end).max().unwrap_or(0)
515 }
516
517 const NAME: &str = "0123456789abcdef0123456789abcdef";
518 const OTHER: &str = "fedcba9876543210fedcba9876543210";
519
520 fn own(entries: &[Entry]) -> Vec<u8> {
521 let covered = [Covered {
522 name: NAME.to_owned(),
523 len: segment_len(entries),
524 }];
525 let entries: Vec<(Entry, u16)> = entries.iter().map(|entry| (*entry, 0)).collect();
526 encode(&covered, &entries)
527 }
528
529 #[test]
530 fn round_trip() {
531 for n in [0, 1, 2, 300] {
532 let entries = entries(n);
533 let len = segment_len(&entries);
534 let decoded = decode(&own(&entries), Some(NAME)).unwrap();
535 assert_eq!(
536 decoded.entries,
537 entries.iter().map(|e| (*e, 0)).collect::<Vec<_>>()
538 );
539 assert_eq!(
540 decoded.covered,
541 [Covered {
542 name: NAME.to_owned(),
543 len
544 }]
545 );
546 // Version 1, as older versions wrote it.
547 let decoded = decode(&encode_v1(&entries, len), Some(NAME)).unwrap();
548 assert_eq!(decoded.entries.len(), n);
549 assert_eq!(decoded.covered[0].len, len);
550 }
551 }
552
553 #[test]
554 fn a_merged_index_names_each_entry_segment() {
555 let first = entries_of(0..40);
556 let second = entries_of(40..80);
557 let covered = vec![
558 Covered {
559 name: NAME.to_owned(),
560 len: segment_len(&first),
561 },
562 Covered {
563 name: OTHER.to_owned(),
564 len: segment_len(&second),
565 },
566 ];
567 let mut merged: Vec<(Entry, u16)> = first
568 .iter()
569 .map(|e| (*e, 0))
570 .chain(second.iter().map(|e| (*e, 1)))
571 .collect();
572 merged.sort_by_key(|(entry, _)| entry.id);
573 let bytes = encode(&covered, &merged);
574 let decoded = decode(&bytes, None).unwrap();
575 assert_eq!(decoded.covered, covered);
576 assert_eq!(decoded.entries, merged);
577 // Read a bucket at a time, as lookups do.
578 let head = head(&bytes[..Header::head_len(2)]).unwrap();
579 assert_eq!(head.file_len(), bytes.len() as u64);
580 let mut seen = Vec::new();
581 for byte in 0..=255u8 {
582 let range = head.bucket(byte);
583 let at = |n| head.entry_offset(n) as usize;
584 seen.extend(bucket(&head, byte, &bytes[at(range.start)..at(range.end)]).unwrap());
585 }
586 assert_eq!(seen, merged);
587 // An index of one segment is not another segment's.
588 assert!(decode(&bytes, Some(NAME)).is_err());
589 assert!(decode(&own(&first), Some(OTHER)).is_err());
590 }
591
592 #[test]
593 fn every_flipped_byte_is_caught() {
594 let entries = entries(5);
595 let bytes = own(&entries);
596 for i in 0..bytes.len() {
597 let mut damaged = bytes.clone();
598 damaged[i] ^= 0x10;
599 assert!(decode(&damaged, Some(NAME)).is_err(), "byte {i}");
600 }
601 for len in 0..bytes.len() {
602 assert!(decode(&bytes[..len], Some(NAME)).is_err(), "cut at {len}");
603 }
604 let v1 = encode_v1(&entries, segment_len(&entries));
605 for i in 0..v1.len() {
606 let mut damaged = v1.clone();
607 damaged[i] ^= 0x10;
608 assert!(decode(&damaged, Some(NAME)).is_err(), "version 1, byte {i}");
609 }
610 }
611
612 #[test]
613 fn structure_is_checked_under_valid_checksums() {
614 let entries = entries(3);
615 let len = segment_len(&entries);
616 let covered = [Covered {
617 name: NAME.to_owned(),
618 len,
619 }];
620 let with = |list: &[(Entry, u16)], covered: &[Covered]| {
621 let mut bytes = encode(covered, &[]);
622 // Entries written as given, with the fan-out fixed to match.
623 let mut fanout = [0u32; 256];
624 for (entry, _) in list {
625 fanout[usize::from(entry.id.as_bytes()[0])] += 1;
626 }
627 let mut total = 0;
628 let start = HEADER_LEN + COVERED_LEN * covered.len();
629 for (byte, slot) in fanout.iter().enumerate() {
630 total += slot;
631 bytes[start + byte * 4..start + byte * 4 + 4].copy_from_slice(&total.to_le_bytes());
632 }
633 bytes[16..24].copy_from_slice(&(list.len() as u64).to_le_bytes());
634 let crc = crc32c::crc32c(&bytes[..28]);
635 bytes[28..32].copy_from_slice(&crc.to_le_bytes());
636 let head_end = Header::head_len(covered.len());
637 let crc = crc32c::crc32c(&bytes[HEADER_LEN..head_end - CRC_LEN]);
638 bytes[head_end - CRC_LEN..head_end].copy_from_slice(&crc.to_le_bytes());
639 for (entry, segment) in list {
640 bytes.extend_from_slice(&entry.encode_in(*segment));
641 }
642 bytes
643 };
644 let good: Vec<(Entry, u16)> = entries.iter().map(|e| (*e, 0)).collect();
645 assert!(decode(&with(&good, &covered), Some(NAME)).is_ok());
646
647 // Ids out of order.
648 let mut swapped = good.clone();
649 swapped.swap(0, 2);
650 assert!(matches!(
651 decode(&with(&swapped, &covered), Some(NAME)),
652 Err(IndexError::Damaged(_))
653 ));
654 // An entry past the end of its segment.
655 let short = [Covered {
656 name: NAME.to_owned(),
657 len: len - 8,
658 }];
659 assert_eq!(
660 decode(&with(&good, &short), Some(NAME)).unwrap_err(),
661 IndexError::Damaged("index entry points past the end of the segment")
662 );
663 // An entry naming a segment the index does not cover.
664 let mut stray = good.clone();
665 stray[1].1 = 1;
666 assert_eq!(
667 decode(&with(&stray, &covered), Some(NAME)).unwrap_err(),
668 IndexError::Damaged("index entry names a segment it does not cover")
669 );
670 }
671
672 #[test]
673 fn what_a_newer_version_wrote_is_not_damage() {
674 let entries = entries(3);
675 // A later version or a reserved field in a header that checks out.
676 for (at, value) in [(8, 3u8), (12, 1)] {
677 let mut bytes = own(&entries);
678 bytes[at] = value;
679 let crc = crc32c::crc32c(&bytes[..28]);
680 bytes[28..32].copy_from_slice(&crc.to_le_bytes());
681 assert!(
682 matches!(decode(&bytes, Some(NAME)), Err(IndexError::Newer(_))),
683 "byte {at}"
684 );
685 }
686 // An entry with a codec this version does not know.
687 let mut bytes = own(&entries);
688 let at = Header::head_len(1);
689 bytes[at + 45] = 9;
690 let crc = crc32c::crc32c(&bytes[at..at + 60]);
691 bytes[at + 60..at + 64].copy_from_slice(&crc.to_le_bytes());
692 assert!(matches!(
693 decode(&bytes, Some(NAME)),
694 Err(IndexError::Newer(_))
695 ));
696
697 // Version 1: a later version, a reserved field, an unknown codec, an
698 // unknown kind, a reserved location field, under a valid hash.
699 let len = segment_len(&entries);
700 let reseal = |mut body: Vec<u8>| {
701 body.truncate(body.len() - V1_FOOTER_LEN);
702 let hash = blake3::hash(&body);
703 body.extend_from_slice(hash.as_bytes());
704 body
705 };
706 let locations = HEADER_LEN + FANOUT_LEN + entries.len() * 32;
707 for at in [12, locations + 13, locations + 12, locations + 28] {
708 let mut bytes = encode_v1(&entries, len);
709 bytes[at] = 7;
710 assert!(
711 matches!(
712 decode(&reseal(bytes), Some(NAME)),
713 Err(IndexError::Newer(_))
714 ),
715 "byte {at}"
716 );
717 }
718 }
719
720 #[test]
721 fn names_round_trip() {
722 assert_eq!(hex(&unhex(NAME)), NAME);
723 assert_eq!(hex(&unhex(OTHER)), OTHER);
724 }
725}