Skip to main content

weida_http_codec/
varint.rs

1//! QUIC variable-length integers (RFC 9000 §16), the integer of every HTTP/3
2//! frame and stream header.
3//!
4//! The two most significant bits of the first octet give the length (1, 2, 4
5//! or 8 octets); the rest is the value, network byte order, up to 2^62 - 1.
6
7use crate::error::{DecodeError, EncodeError};
8
9/// The largest value: 2^62 - 1.
10pub const MAX: u64 = (1 << 62) - 1;
11
12/// Decodes one integer. Returns it and the octets used. A value written in a
13/// longer form than it needs is accepted, as RFC 9000 §16 allows.
14///
15/// # Errors
16///
17/// `Incomplete` with the exact number of missing octets.
18pub fn decode(input: &[u8]) -> Result<(u64, usize), DecodeError> {
19    let first = *input.first().ok_or(DecodeError::Incomplete { needed: 1 })?;
20    let len = 1usize << (first >> 6);
21    if input.len() < len {
22        return Err(DecodeError::Incomplete {
23            needed: len - input.len(),
24        });
25    }
26    let value = input[1..len]
27        .iter()
28        .fold(u64::from(first & 0x3f), |acc, &b| (acc << 8) | u64::from(b));
29    Ok((value, len))
30}
31
32/// The length of the shortest encoding of `v`; 8 for anything above
33/// [`MAX`], which [`encode`] refuses.
34#[must_use]
35pub const fn len(v: u64) -> usize {
36    if v < 1 << 6 {
37        1
38    } else if v < 1 << 14 {
39        2
40    } else if v < 1 << 30 {
41        4
42    } else {
43        8
44    }
45}
46
47/// Appends the shortest encoding of `v`.
48///
49/// # Errors
50///
51/// `TooLarge` `"varint"` above [`MAX`]: a caller bug, since every value this
52/// crate's users encode is a length or an identifier far below it. Nothing is
53/// written on error.
54pub fn encode(v: u64, out: &mut Vec<u8>) -> Result<(), EncodeError> {
55    if v > MAX {
56        return Err(EncodeError::TooLarge {
57            what: "varint",
58            len: v,
59            cap: MAX,
60        });
61    }
62    let n = len(v);
63    let tag = match n {
64        1 => 0x00,
65        2 => 0x40,
66        4 => 0x80,
67        _ => 0xc0,
68    };
69    let bytes = v.to_be_bytes();
70    let start = out.len();
71    out.extend_from_slice(&bytes[8 - n..]);
72    out[start] |= tag;
73    Ok(())
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn boundaries_take_the_next_length() {
82        for (v, n) in [
83            (63, 1),
84            (64, 2),
85            (16_383, 2),
86            (16_384, 4),
87            ((1 << 30) - 1, 4),
88            (1 << 30, 8),
89            (MAX, 8),
90        ] {
91            let mut out = Vec::new();
92            encode(v, &mut out).unwrap();
93            assert_eq!(out.len(), n, "{v}");
94            assert_eq!(decode(&out), Ok((v, n)));
95        }
96        let mut out = vec![7];
97        assert!(encode(MAX + 1, &mut out).is_err());
98        assert_eq!(out, [7]);
99    }
100
101    #[test]
102    fn a_short_input_names_the_missing_octets() {
103        assert_eq!(
104            decode(&[0xc0, 0, 0]),
105            Err(DecodeError::Incomplete { needed: 5 })
106        );
107        assert_eq!(decode(&[]), Err(DecodeError::Incomplete { needed: 1 }));
108    }
109}