1use 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#[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
47pub 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
74pub 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
89pub 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}