Skip to main content

olean_export/
accepted.rs

1//! Accepted stores: the declaration keys each checker has accepted, one section per checker,
2//! so several checkers share one file.
3//!
4//! Layout: `MAGIC`, a little-endian `u32` section count, then per section a `u32` name length,
5//! the checker name, a 32-byte tag the checker defines, a `u64` key count, and the sorted keys.
6
7use crate::{
8    error::{corrupt, Result},
9    key::Key,
10};
11use std::{
12    fs::{self, File},
13    io::{self, Write},
14    path::Path,
15};
16
17pub const MAGIC: &[u8; 8] = b"ACCEPT\0\x01";
18
19/// One checker's section. A checker trusts its keys only while `tag` matches its own.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Section<'a> {
22    pub checker: &'a str,
23    pub tag: Key,
24    pub keys: &'a [Key],
25}
26
27impl Section<'_> {
28    #[must_use]
29    pub fn contains(&self, k: &Key) -> bool {
30        self.keys.binary_search(k).is_ok()
31    }
32}
33
34fn take<'a>(b: &mut &'a [u8], n: usize) -> Result<&'a [u8]> {
35    if b.len() < n {
36        return Err(corrupt("accepted store: truncated"));
37    }
38    let (h, t) = b.split_at(n);
39    *b = t;
40    Ok(h)
41}
42
43fn word<const N: usize>(b: &mut &[u8]) -> Result<[u8; N]> {
44    Ok(take(b, N)?.try_into().expect("length checked"))
45}
46
47/// The sections of a store, borrowing from `bytes`.
48pub fn parse(bytes: &[u8]) -> Result<Vec<Section<'_>>> {
49    let mut b = bytes;
50    if take(&mut b, MAGIC.len())? != MAGIC {
51        return Err(corrupt("not an accepted store"));
52    }
53    let n = u32::from_le_bytes(word(&mut b)?);
54    let mut out = Vec::new();
55    for _ in 0..n {
56        let len = u32::from_le_bytes(word(&mut b)?) as usize;
57        let checker = std::str::from_utf8(take(&mut b, len)?)
58            .map_err(|_| corrupt("accepted store: checker name is not UTF-8"))?;
59        let tag = word(&mut b)?;
60        let count = usize::try_from(u64::from_le_bytes(word(&mut b)?))
61            .map_err(|_| corrupt("accepted store: key count"))?;
62        let bytes = count
63            .checked_mul(32)
64            .ok_or_else(|| corrupt("accepted store: key count"))?;
65        let keys = take(&mut b, bytes)?.as_chunks().0;
66        out.push(Section { checker, tag, keys });
67    }
68    if !b.is_empty() {
69        return Err(corrupt("accepted store: trailing bytes"));
70    }
71    Ok(out)
72}
73
74/// Write `sections` in order. Each section's keys must be sorted.
75pub fn write(mut w: impl Write, sections: &[Section<'_>]) -> io::Result<()> {
76    let n = |x: usize| u32::try_from(x).map_err(|_| io::Error::other("too many sections"));
77    w.write_all(MAGIC)?;
78    w.write_all(&n(sections.len())?.to_le_bytes())?;
79    for s in sections {
80        w.write_all(&n(s.checker.len())?.to_le_bytes())?;
81        w.write_all(s.checker.as_bytes())?;
82        w.write_all(&s.tag)?;
83        w.write_all(&(s.keys.len() as u64).to_le_bytes())?;
84        s.keys.iter().try_for_each(|k| w.write_all(k))?;
85    }
86    Ok(())
87}
88
89/// Replace the store at `path` with `sections`, atomically: readers that map the old file
90/// keep seeing it whole.
91pub fn save(path: &Path, sections: &[Section<'_>]) -> io::Result<()> {
92    if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
93        fs::create_dir_all(dir)?;
94    }
95    let tmp = path.with_extension(format!("tmp.{}", std::process::id()));
96    let mut f = io::BufWriter::new(File::create(&tmp)?);
97    write(&mut f, sections)?;
98    f.into_inner()
99        .map_err(io::IntoInnerError::into_error)?
100        .sync_all()?;
101    fs::rename(&tmp, path)
102}