OXYGENHUB

Coverage / crates/spectra-core/src/cbor.rs 90.7%

175 of 193 lines run, 44 of 52 functions · run #36 on main · run missed

1
//! Deterministic CBOR (RFC 8949 §4.2), as much of it as Spectra encodes:
2
//! unsigned integers, byte and text strings, arrays, maps with integer
3
//! keys, null and booleans. Shortest forms, definite lengths, map keys in
4
//! ascending order; the decoder refuses anything else, so one value has
5
//! exactly one encoding and hashing it is meaningful (spec §9.5).
6
7
use std::collections::BTreeMap;
8
9
#[derive(Clone, Debug, PartialEq, Eq)]
10
pub enum Value {
11
    Uint(u64),
12
    Bytes(Vec<u8>),
13
    Text(String),
14
    Array(Vec<Value>),
15
    Map(BTreeMap<u64, Value>),
16
    Bool(bool),
17
    Null,
18
}
19
20
impl Value {
2168295×
    pub fn map<const N: usize>(entries: [(u64, Value); N]) -> Value {
2268295×
        Value::Map(entries.into_iter().collect())
2368295×
    }
245121×
    pub fn as_uint(&self) -> Option<u64> {
255121×
        match self {
265121×
            Value::Uint(u) => Some(*u),
270×
            _ => None,
28
        }
295121×
    }
3013606×
    pub fn as_bytes(&self) -> Option<&[u8]> {
3113606×
        match self {
3213606×
            Value::Bytes(b) => Some(b),
330×
            _ => None,
34
        }
3513606×
    }
364654×
    pub fn as_text(&self) -> Option<&str> {
374654×
        match self {
384654×
            Value::Text(t) => Some(t),
390×
            _ => None,
40
        }
414654×
    }
421762×
    pub fn as_array(&self) -> Option<&[Value]> {
431762×
        match self {
441762×
            Value::Array(a) => Some(a),
450×
            _ => None,
46
        }
471762×
    }
486129×
    pub fn as_map(&self) -> Option<&BTreeMap<u64, Value>> {
496129×
        match self {
506129×
            Value::Map(m) => Some(m),
510×
            _ => None,
52
        }
536129×
    }
540×
    pub fn is_null(&self) -> bool {
550×
        matches!(self, Value::Null)
560×
    }
57
}
58
59984630×
fn head(out: &mut Vec<u8>, major: u8, n: u64) {
60984630×
    let m = major << 5;
61984630×
    match n {
62984630×
        0..=23 => out.push(m | n as u8),
63189552×
        24..=0xff => out.extend_from_slice(&[m | 24, n as u8]),
6489256×
        0x100..=0xffff => {
6531498×
            out.push(m | 25);
6631498×
            out.extend_from_slice(&(n as u16).to_be_bytes());
6731498×
        }
6857758×
        0x1_0000..=0xffff_ffff => {
690×
            out.push(m | 26);
700×
            out.extend_from_slice(&(n as u32).to_be_bytes());
710×
        }
7257758×
        _ => {
7357758×
            out.push(m | 27);
7457758×
            out.extend_from_slice(&n.to_be_bytes());
7557758×
        }
76
    }
77984630×
}
78
79607166×
fn put(out: &mut Vec<u8>, v: &Value) {
80607166×
    match v {
81186017×
        Value::Uint(n) => head(out, 0, *n),
8287034×
        Value::Bytes(b) => {
8387034×
            head(out, 2, b.len() as u64);
8487034×
            out.extend_from_slice(b);
8587034×
        }
8694048×
        Value::Text(t) => {
8794048×
            head(out, 3, t.len() as u64);
8894048×
            out.extend_from_slice(t.as_bytes());
8994048×
        }
9033569×
        Value::Array(a) => {
9133569×
            head(out, 4, a.len() as u64);
9256991×
            for x in a {
9356991×
                put(out, x);
9456991×
            }
95
        }
96
        // BTreeMap iterates keys ascending, which for unsigned integers is
97
        // the order of their shortest encodings.
9868295×
        Value::Map(m) => {
9968295×
            head(out, 5, m.len() as u64);
100515667×
            for (k, x) in m {
101515667×
                head(out, 0, *k);
102515667×
                put(out, x);
103515667×
            }
104
        }
1050×
        Value::Bool(false) => out.push(0xf4),
1061×
        Value::Bool(true) => out.push(0xf5),
107138202×
        Value::Null => out.push(0xf6),
108
    }
109607166×
}
110
11134508×
pub fn encode(v: &Value) -> Vec<u8> {
11234508×
    let mut out = Vec::new();
11334508×
    put(&mut out, v);
11434508×
    out
11534508×
}
116
117
/// Why bytes are not a value Spectra encodes.
118
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
119
#[error("malformed CBOR: {0}")]
120
pub struct Error(pub String);
121
122
struct Reader<'a> {
123
    b: &'a [u8],
124
    at: usize,
125
    depth: usize,
126
}
127
128
const MAX_DEPTH: usize = 32;
129
130
impl<'a> Reader<'a> {
13199373×
    fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
13299373×
        let end = self.at.checked_add(n).filter(|e| *e <= self.b.len()).ok_or_else(|| Error("truncated".into()))?;
13399373×
        let s = &self.b[self.at..end];
13499373×
        self.at = end;
13599373×
        Ok(s)
13699373×
    }
137
13865712×
    fn head(&mut self) -> Result<(u8, u64), Error> {
13965712×
        let first = self.take(1)?[0];
14065712×
        let (major, info) = (first >> 5, first & 0x1f);
14165711×
        let n = match info {
14265712×
            0..=23 => info as u64,
1439305×
            24 => self.take(1)?[0] as u64,
1443176×
            25 => u16::from_be_bytes(self.take(2)?.try_into().unwrap()) as u64,
1451×
            26 => u32::from_be_bytes(self.take(4)?.try_into().unwrap()) as u64,
1462917×
            27 => u64::from_be_bytes(self.take(8)?.try_into().unwrap()),
1471×
            _ if major == 7 => return Ok((7, info as u64)),
1481×
            _ => return Err(Error("an indefinite length or a reserved form".into())),
149
        };
15065711×
        let minimal = match info {
1519305×
            24 => n >= 24,
1523176×
            25 => n > 0xff,
1531×
            26 => n > 0xffff,
1542917×
            27 => n > 0xffff_ffff,
15550312×
            _ => true,
156
        };
15765711×
        if !minimal && major != 7 {
1581×
            return Err(Error("a length or number not in its shortest form".into()));
15965710×
        }
16065710×
        Ok((major, n))
16165712×
    }
162
16326189×
    fn len(&mut self, n: u64) -> Result<usize, Error> {
16426189×
        let n = usize::try_from(n).map_err(|_| Error("too long".into()))?;
16526189×
        if n > self.b.len() - self.at {
1661×
            return Err(Error("truncated".into()));
16726188×
        }
16826188×
        Ok(n)
16926189×
    }
170
17135377×
    fn value(&mut self) -> Result<Value, Error> {
17235377×
        self.depth += 1;
17335377×
        if self.depth > MAX_DEPTH {
1741×
            return Err(Error("nested too deeply".into()));
17535376×
        }
17635376×
        let (major, n) = self.head()?;
17735374×
        let v = match major {
1785151×
            0 => Value::Uint(n),
179
            2 => {
18013608×
                let l = self.len(n)?;
18113607×
                Value::Bytes(self.take(l)?.to_vec())
182
            }
183
            3 => {
1844655×
                let l = self.len(n)?;
1854655×
                Value::Text(String::from_utf8(self.take(l)?.to_vec()).map_err(|_| Error("text that is not UTF-8".into()))?)
186
            }
187
            4 => {
1881795×
                let l = self.len(n)?;
1891795×
                let mut a = Vec::with_capacity(l);
1901795×
                for _ in 0..l {
1911392×
                    a.push(self.value()?);
192
                }
1931763×
                Value::Array(a)
194
            }
195
            5 => {
1966131×
                let l = self.len(n)?;
1976131×
                let mut m = BTreeMap::new();
1986131×
                let mut last: Option<u64> = None;
1996131×
                for _ in 0..l {
20030336×
                    let (km, k) = self.head()?;
20130336×
                    if km != 0 {
2020×
                        return Err(Error("a map key that is not an unsigned integer".into()));
20330336×
                    }
20430336×
                    if last.is_some_and(|p| k <= p) {
2051×
                        return Err(Error("map keys out of order or repeated".into()));
20630335×
                    }
20730335×
                    last = Some(k);
20830335×
                    m.insert(k, self.value()?);
209
                }
2106130×
                Value::Map(m)
211
            }
2124033×
            7 => match n {
2130×
                20 => Value::Bool(false),
2141×
                21 => Value::Bool(true),
2154032×
                22 => Value::Null,
2160×
                _ => return Err(Error("an unsupported simple value or float".into())),
217
            },
2181×
            _ => return Err(Error("a negative integer or a tag".into())),
219
        };
22035339×
        self.depth -= 1;
22135339×
        Ok(v)
22235377×
    }
223
}
224
225
/// Decode exactly one value, refusing any non-canonical encoding.
2263650×
pub fn decode(b: &[u8]) -> Result<Value, Error> {
2273650×
    let mut r = Reader { b, at: 0, depth: 0 };
2283650×
    let v = r.value()?;
2293644×
    if r.at != b.len() {
2301×
        return Err(Error("bytes after the value".into()));
2313643×
    }
2323643×
    Ok(v)
2333650×
}
234
235
#[cfg(test)]
236
mod tests {
237
    use super::*;
238
239
    #[test]
2401×
    fn round_trips_and_known_encodings() {
2411×
        let v = Value::map([
2421×
            (0, Value::Uint(1)),
2431×
            (1, Value::Text("é".into())),
2441×
            (2, Value::Bytes(vec![1, 2])),
2451×
            (3, Value::Array(vec![Value::Null, Value::Bool(true), Value::Uint(500)])),
2461×
            (24, Value::Uint(u64::MAX)),
2471×
        ]);
2481×
        let b = encode(&v);
2491×
        assert_eq!(decode(&b).unwrap(), v);
2501×
        assert_eq!(encode(&Value::Uint(23)), [0x17]);
2511×
        assert_eq!(encode(&Value::Uint(24)), [0x18, 24]);
2521×
        assert_eq!(encode(&Value::Uint(1000)), [0x19, 0x03, 0xe8]);
2531×
        assert_eq!(encode(&Value::Text("a".into())), [0x61, b'a']);
2541×
    }
255
256
    #[test]
2571×
    fn refuses_what_is_not_canonical() {
2581×
        assert!(decode(&[0x18, 5]).is_err(), "5 in two bytes");
2591×
        assert!(decode(&[0xa2, 0x01, 0x00, 0x00, 0x00]).is_err(), "keys out of order");
2601×
        assert!(decode(&[0x5f]).is_err(), "indefinite length");
2611×
        assert!(decode(&[0x01, 0x02]).is_err(), "trailing bytes");
2621×
        assert!(decode(&[0x5a, 0xff, 0xff, 0xff, 0xff]).is_err(), "truncated");
2631×
        assert!(decode(&[0x20]).is_err(), "negative");
2641×
        let deep = [0x81u8; 64];
2651×
        assert!(decode(&deep).is_err(), "too deep");
2661×
    }
267
}