OXYGENHUB

Coverage / crates/oxy-core/src/flat.rs 98.0%

100 of 102 lines run, 51 of 54 functions · run #273 on bare-hashes · run missed

1
//! A flat binary layout for local indexes (oxygen#41): fixed-width
2
//! little-endian numbers and length-prefixed bytes, read in one pass
3
//! without building a generic value tree. Only for caches this repository
4
//! derives and can derive again: never exchanged, never trusted beyond the
5
//! key they are stored under, and a reader that finds anything amiss fails
6
//! so the caller rebuilds.
7
8
use crate::hash::ObjectRef;
9
use crate::objects::ObjectError;
10
11
#[derive(Default)]
12
pub struct Writer(pub Vec<u8>);
13
14
impl Writer {
15345612×
    pub fn u8(&mut self, v: u8) {
16345612×
        self.0.push(v);
17345612×
    }
18371784×
    pub fn u32(&mut self, v: u32) {
19371784×
        self.0.extend_from_slice(&v.to_le_bytes());
20371784×
    }
2166148×
    pub fn u64(&mut self, v: u64) {
2266148×
        self.0.extend_from_slice(&v.to_le_bytes());
2366148×
    }
24
    /// A count, which must fit in 32 bits.
25173464×
    pub fn count(&mut self, n: usize) {
26173464×
        self.u32(u32::try_from(n).expect("an index count fits in 32 bits"));
27173464×
    }
28686116×
    pub fn fixed(&mut self, b: &[u8]) {
29686116×
        self.0.extend_from_slice(b);
30686116×
    }
31108033×
    pub fn bytes(&mut self, b: &[u8]) {
32108033×
        self.count(b.len());
33108033×
        self.0.extend_from_slice(b);
34108033×
    }
35234142×
    pub fn object(&mut self, r: &ObjectRef) {
36234142×
        self.fixed(&r.0);
37234142×
    }
3830942×
    pub fn opt_object(&mut self, r: &Option<ObjectRef>) {
3930942×
        match r {
4030703×
            None => self.u8(0),
41239×
            Some(r) => {
42239×
                self.u8(1);
43239×
                self.object(r);
44239×
            }
45
        }
4630942×
    }
47
}
48
49
pub struct Reader<'a> {
50
    buf: &'a [u8],
51
    pos: usize,
52
}
53
542×
fn short() -> ObjectError {
552×
    ObjectError::Schema("index: truncated".into())
562×
}
57
58
impl<'a> Reader<'a> {
5922111×
    pub fn new(buf: &'a [u8]) -> Reader<'a> {
6022111×
        Reader { buf, pos: 0 }
6122111×
    }
6244096×
    pub fn at_end(&self) -> bool {
6344096×
        self.pos == self.buf.len()
6444096×
    }
651112627×
    fn take(&mut self, n: usize) -> Result<&'a [u8], ObjectError> {
661112627×
        let end = self.pos.checked_add(n).ok_or_else(short)?;
671112627×
        let s = self.buf.get(self.pos..end).ok_or_else(short)?;
681112625×
        self.pos = end;
691112625×
        Ok(s)
701112627×
    }
71229261×
    pub fn u8(&mut self) -> Result<u8, ObjectError> {
72229261×
        Ok(self.take(1)?[0])
73229261×
    }
74268920×
    pub fn u32(&mut self) -> Result<u32, ObjectError> {
75268920×
        Ok(u32::from_le_bytes(self.fixed::<4>()?))
76268920×
    }
7744524×
    pub fn u64(&mut self) -> Result<u64, ObjectError> {
7844524×
        Ok(u64::from_le_bytes(self.fixed::<8>()?))
7944524×
    }
80
    /// A count; checked against what is left, so a corrupt one cannot ask
81
    /// for more room than the index could hold.
8246789×
    pub fn count(&mut self) -> Result<usize, ObjectError> {
8346789×
        let n = self.u32()? as usize;
8446789×
        if n > self.buf.len() - self.pos {
850×
            return Err(short());
8646789×
        }
8746789×
        Ok(n)
8846789×
    }
89790199×
    pub fn fixed<const N: usize>(&mut self) -> Result<[u8; N], ObjectError> {
90790199×
        Ok(self.take(N)?.try_into().expect("N bytes"))
91790199×
    }
9293167×
    pub fn bytes(&mut self) -> Result<&'a [u8], ObjectError> {
9393167×
        let n = self.u32()? as usize;
9493167×
        self.take(n)
9593167×
    }
9651497×
    pub fn text(&mut self) -> Result<String, ObjectError> {
9751497×
        String::from_utf8(self.bytes()?.to_vec())
9851497×
            .map_err(|_| ObjectError::Schema("index: text is not UTF-8".into()))
9951497×
    }
100148167×
    pub fn object(&mut self) -> Result<ObjectRef, ObjectError> {
101148167×
        Ok(ObjectRef(self.fixed::<32>()?))
102148167×
    }
10325981×
    pub fn opt_object(&mut self) -> Result<Option<ObjectRef>, ObjectError> {
10425981×
        Ok(match self.u8()? {
10525788×
            0 => None,
106193×
            _ => Some(self.object()?),
107
        })
10825981×
    }
109
}
110
111
#[cfg(test)]
112
mod tests {
113
    use super::*;
114
115
    #[test]
1161×
    fn numbers_and_bytes_round_trip_and_truncation_fails() {
1171×
        let mut w = Writer::default();
1181×
        w.u8(7);
1191×
        w.u32(70_000);
1201×
        w.u64(1 << 40);
1211×
        w.bytes(b"path/name");
1221×
        w.opt_object(&Some(ObjectRef([3; 32])));
1231×
        w.opt_object(&None);
1241×
        let mut r = Reader::new(&w.0);
1251×
        assert_eq!(r.u8().unwrap(), 7);
1261×
        assert_eq!(r.u32().unwrap(), 70_000);
1271×
        assert_eq!(r.u64().unwrap(), 1 << 40);
1281×
        assert_eq!(r.text().unwrap(), "path/name");
1291×
        assert_eq!(r.opt_object().unwrap(), Some(ObjectRef([3; 32])));
1301×
        assert_eq!(r.opt_object().unwrap(), None);
1311×
        assert!(r.at_end());
1321×
        let mut r = Reader::new(&w.0[..w.0.len() - 3]);
1331×
        r.fixed::<13>().unwrap();
1341×
        assert!(r.text().is_ok());
1351×
        assert!(r.opt_object().is_err());
1361×
    }
137
}