OXYGENHUB

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

175 of 193 lines run, 44 of 52 functions · run #25 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 {
2161676×
    pub fn map<const N: usize>(entries: [(u64, Value); N]) -> Value {
2261676×
        Value::Map(entries.into_iter().collect())
2361676×
    }
243809×
    pub fn as_uint(&self) -> Option<u64> {
253809×
        match self {
263809×
            Value::Uint(u) => Some(*u),
270×
            _ => None,
28
        }
293809×
    }
309902×
    pub fn as_bytes(&self) -> Option<&[u8]> {
319902×
        match self {
329902×
            Value::Bytes(b) => Some(b),
330×
            _ => None,
34
        }
359902×
    }
363450×
    pub fn as_text(&self) -> Option<&str> {
373450×
        match self {
383450×
            Value::Text(t) => Some(t),
390×
            _ => None,
40
        }
413450×
    }
421321×
    pub fn as_array(&self) -> Option<&[Value]> {
431321×
        match self {
441321×
            Value::Array(a) => Some(a),
450×
            _ => None,
46
        }
471321×
    }
484404×
    pub fn as_map(&self) -> Option<&BTreeMap<u64, Value>> {
494404×
        match self {
504404×
            Value::Map(m) => Some(m),
510×
            _ => None,
52
        }
534404×
    }
540×
    pub fn is_null(&self) -> bool {
550×
        matches!(self, Value::Null)
560×
    }
57
}
58
59919187×
fn head(out: &mut Vec<u8>, major: u8, n: u64) {
60919187×
    let m = major << 5;
61919187×
    match n {
62919187×
        0..=23 => out.push(m | n as u8),
63175057×
        24..=0xff => out.extend_from_slice(&[m | 24, n as u8]),
6483743×
        0x100..=0xffff => {
6528856×
            out.push(m | 25);
6628856×
            out.extend_from_slice(&(n as u16).to_be_bytes());
6728856×
        }
6854887×
        0x1_0000..=0xffff_ffff => {
690×
            out.push(m | 26);
700×
            out.extend_from_slice(&(n as u32).to_be_bytes());
710×
        }
7254887×
        _ => {
7354887×
            out.push(m | 27);
7454887×
            out.extend_from_slice(&n.to_be_bytes());
7554887×
        }
76
    }
77919187×
}
78
79567437×
fn put(out: &mut Vec<u8>, v: &Value) {
80567437×
    match v {
81179847×
        Value::Uint(n) => head(out, 0, *n),
8275641×
        Value::Bytes(b) => {
8375641×
            head(out, 2, b.len() as u64);
8475641×
            out.extend_from_slice(b);
8575641×
        }
8688442×
        Value::Text(t) => {
8788442×
            head(out, 3, t.len() as u64);
8888442×
            out.extend_from_slice(t.as_bytes());
8988442×
        }
9030950×
        Value::Array(a) => {
9130950×
            head(out, 4, a.len() as u64);
9253109×
            for x in a {
9353109×
                put(out, x);
9453109×
            }
95
        }
96
        // BTreeMap iterates keys ascending, which for unsigned integers is
97
        // the order of their shortest encodings.
9861676×
        Value::Map(m) => {
9961676×
            head(out, 5, m.len() as u64);
100482631×
            for (k, x) in m {
101482631×
                head(out, 0, *k);
102482631×
                put(out, x);
103482631×
            }
104
        }
1050×
        Value::Bool(false) => out.push(0xf4),
1061×
        Value::Bool(true) => out.push(0xf5),
107130880×
        Value::Null => out.push(0xf6),
108
    }
109567437×
}
110
11131697×
pub fn encode(v: &Value) -> Vec<u8> {
11231697×
    let mut out = Vec::new();
11331697×
    put(&mut out, v);
11431697×
    out
11531697×
}
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> {
13172723×
    fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
13272723×
        let end = self.at.checked_add(n).filter(|e| *e <= self.b.len()).ok_or_else(|| Error("truncated".into()))?;
13372723×
        let s = &self.b[self.at..end];
13472723×
        self.at = end;
13572723×
        Ok(s)
13672723×
    }
137
13848115×
    fn head(&mut self) -> Result<(u8, u64), Error> {
13948115×
        let first = self.take(1)?[0];
14048115×
        let (major, info) = (first >> 5, first & 0x1f);
14148114×
        let n = match info {
14248115×
            0..=23 => info as u64,
1436742×
            24 => self.take(1)?[0] as u64,
1442357×
            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,
1462154×
            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
        };
15048114×
        let minimal = match info {
1516742×
            24 => n >= 24,
1522357×
            25 => n > 0xff,
1531×
            26 => n > 0xffff,
1542154×
            27 => n > 0xffff_ffff,
15536860×
            _ => true,
156
        };
15748114×
        if !minimal && major != 7 {
1581×
            return Err(Error("a length or number not in its shortest form".into()));
15948113×
        }
16048113×
        Ok((major, n))
16148115×
    }
162
16319115×
    fn len(&mut self, n: u64) -> Result<usize, Error> {
16419115×
        let n = usize::try_from(n).map_err(|_| Error("too long".into()))?;
16519115×
        if n > self.b.len() - self.at {
1661×
            return Err(Error("truncated".into()));
16719114×
        }
16819114×
        Ok(n)
16919115×
    }
170
17125877×
    fn value(&mut self) -> Result<Value, Error> {
17225877×
        self.depth += 1;
17325877×
        if self.depth > MAX_DEPTH {
1741×
            return Err(Error("nested too deeply".into()));
17525876×
        }
17625876×
        let (major, n) = self.head()?;
17725874×
        let v = match major {
1783839×
            0 => Value::Uint(n),
179
            2 => {
1809904×
                let l = self.len(n)?;
1819903×
                Value::Bytes(self.take(l)?.to_vec())
182
            }
183
            3 => {
1843451×
                let l = self.len(n)?;
1853451×
                Value::Text(String::from_utf8(self.take(l)?.to_vec()).map_err(|_| Error("text that is not UTF-8".into()))?)
186
            }
187
            4 => {
1881354×
                let l = self.len(n)?;
1891354×
                let mut a = Vec::with_capacity(l);
1901354×
                for _ in 0..l {
191916×
                    a.push(self.value()?);
192
                }
1931322×
                Value::Array(a)
194
            }
195
            5 => {
1964406×
                let l = self.len(n)?;
1974406×
                let mut m = BTreeMap::new();
1984406×
                let mut last: Option<u64> = None;
1994406×
                for _ in 0..l {
20022239×
                    let (km, k) = self.head()?;
20122239×
                    if km != 0 {
2020×
                        return Err(Error("a map key that is not an unsigned integer".into()));
20322239×
                    }
20422239×
                    if last.is_some_and(|p| k <= p) {
2051×
                        return Err(Error("map keys out of order or repeated".into()));
20622238×
                    }
20722238×
                    last = Some(k);
20822238×
                    m.insert(k, self.value()?);
209
                }
2104405×
                Value::Map(m)
211
            }
2122919×
            7 => match n {
2130×
                20 => Value::Bool(false),
2141×
                21 => Value::Bool(true),
2152918×
                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
        };
22025839×
        self.depth -= 1;
22125839×
        Ok(v)
22225877×
    }
223
}
224
225
/// Decode exactly one value, refusing any non-canonical encoding.
2262723×
pub fn decode(b: &[u8]) -> Result<Value, Error> {
2272723×
    let mut r = Reader { b, at: 0, depth: 0 };
2282723×
    let v = r.value()?;
2292717×
    if r.at != b.len() {
2301×
        return Err(Error("bytes after the value".into()));
2312716×
    }
2322716×
    Ok(v)
2332723×
}
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
}