Skip to main content

const_cbor/
head.rs

1//! The CBOR head: initial byte, major types, and argument encoding.
2//!
3//! Every CBOR data item starts with an initial byte whose top three bits
4//! select the major type and whose low five bits are the *additional
5//! information* (`ai`). Values of `ai` below 24 encode the argument inline;
6//! 24–27 indicate that the argument follows in 1, 2, 4, or 8 bytes; 28–30
7//! are reserved; 31 signals indefinite length (not supported by this crate).
8//!
9//! All functions here are `const fn`, so head construction and size
10//! computation can be evaluated at compile time.
11
12use crate::error::Error;
13
14/// Major type of a CBOR data item (RFC 8949 §3.1).
15#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
16#[repr(u8)]
17pub enum Major {
18    /// Unsigned integer (`n >= 0`).
19    Unsigned = 0,
20    /// Negative integer (`-1 - n`).
21    Negative = 1,
22    /// Byte string.
23    Bytes = 2,
24    /// Text string.
25    Text = 3,
26    /// Array of data items.
27    Array = 4,
28    /// Map of key/value pairs.
29    Map = 5,
30    /// Tagged item (semantic tagging).
31    Tag = 6,
32    /// Simple values and floating-point numbers.
33    Simple = 7,
34}
35
36impl Major {
37    /// Extracts the major type from an initial byte.
38    #[inline(always)]
39    #[must_use]
40    pub const fn from_initial(initial: u8) -> Self {
41        match initial >> 5 {
42            0 => Self::Unsigned,
43            1 => Self::Negative,
44            2 => Self::Bytes,
45            3 => Self::Text,
46            4 => Self::Array,
47            5 => Self::Map,
48            6 => Self::Tag,
49            _ => Self::Simple,
50        }
51    }
52
53    /// The three-bit major-type field of the initial byte.
54    #[inline(always)]
55    #[must_use]
56    pub const fn bits(self) -> u8 {
57        (self as u8) << 5
58    }
59}
60
61/// A major type 7 simple value (RFC 8949 §3.3), excluding floats.
62///
63/// Well-known simple values have associated constants; any other value in
64/// `0..=255` can be wrapped directly.
65#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub struct Simple(pub u8);
67
68impl Simple {
69    /// Simple value `false`.
70    pub const FALSE: Self = Self(20);
71    /// Simple value `true`.
72    pub const TRUE: Self = Self(21);
73    /// Simple value `null`.
74    pub const NULL: Self = Self(22);
75    /// Simple value `undefined`.
76    pub const UNDEFINED: Self = Self(23);
77
78    /// The two-byte simple-value form is only legal for values >= 32;
79    /// values below 32 must be encoded in the initial byte itself.
80    #[inline(always)]
81    #[must_use]
82    pub const fn valid_two_byte(self) -> bool {
83        self.0 >= 32
84    }
85}
86
87/// Number of bytes an argument of this width adds after the initial byte.
88#[inline(always)]
89#[must_use]
90#[allow(clippy::unreadable_literal)]
91pub const fn ext_len(ai: u8) -> usize {
92    match ai {
93        24 => 1,
94        25 => 2,
95        26 => 4,
96        27 => 8,
97        _ => 0,
98    }
99}
100
101/// Preferred additional-information selector for a `u64` argument.
102#[inline(always)]
103#[must_use]
104pub const fn ai_of(v: u64) -> u8 {
105    if v < 24 {
106        v as u8
107    } else if v <= 0xff {
108        24
109    } else if v <= 0xffff {
110        25
111    } else if v <= 0xffff_ffff {
112        26
113    } else {
114        27
115    }
116}
117
118/// Total encoded length of a head carrying argument `v`
119/// (initial byte plus any extension bytes).
120#[inline(always)]
121#[must_use]
122pub const fn head_len(v: u64) -> usize {
123    1 + ext_len(ai_of(v))
124}
125
126/// Encoded length of the unsigned integer item `v` (preferred form).
127#[inline(always)]
128#[must_use]
129pub const fn uint_len(v: u64) -> usize {
130    head_len(v)
131}
132
133/// Encoded length of the negative integer item `-1 - n` (preferred form).
134#[inline(always)]
135#[must_use]
136pub const fn neg_len(n: u64) -> usize {
137    uint_len(n)
138}
139
140/// Writes a complete head into `buf` and returns the number of bytes written.
141///
142/// # Errors
143///
144/// Returns [`Error::OUT_OF_SPACE`] when `buf` is shorter than
145/// [`head_len`] for this argument.
146#[inline]
147pub const fn write_head(buf: &mut [u8], major: Major, arg: u64) -> Result<usize, Error> {
148    let ai = ai_of(arg);
149    let ext = ext_len(ai);
150    if buf.len() < 1 + ext {
151        return Err(Error::OUT_OF_SPACE);
152    }
153    buf[0] = major.bits() | ai;
154    let mut i = 0;
155    while i < ext {
156        // Big-endian argument bytes; shift amount is bounded by `ext`.
157        buf[1 + i] = (arg >> ((ext - 1 - i) * 8)) as u8;
158        i += 1;
159    }
160    Ok(1 + ext)
161}
162
163/// Writes a head with an *exact* additional-information selector into `buf`
164/// and returns the number of bytes written.
165///
166/// Unlike [`write_head`] this never chooses a narrower encoding; it is used
167/// for major type 7 floating-point items, whose width must be explicit.
168/// `ai` must be 25, 26, or 27.
169#[cfg_attr(not(feature = "float"), allow(dead_code))]
170#[inline]
171pub(crate) const fn write_head_exact(buf: &mut [u8], arg: u64, ai: u8) -> Result<usize, Error> {
172    match ai {
173        25..=27 => {}
174        _ => return Err(Error::INVALID_ADDITIONAL_INFO),
175    }
176    let ext = ext_len(ai);
177    if buf.len() < 1 + ext {
178        return Err(Error::OUT_OF_SPACE);
179    }
180    buf[0] = Major::Simple.bits() | ai;
181    let mut i = 0;
182    while i < ext {
183        buf[1 + i] = (arg >> ((ext - 1 - i) * 8)) as u8;
184        i += 1;
185    }
186    Ok(1 + ext)
187}
188
189/// The break byte terminating an indefinite-length item (RFC 8949 §3.2).
190pub const BREAK: u8 = 0xff;
191
192/// `true` when `initial` is the break byte.
193#[inline(always)]
194#[must_use]
195pub const fn is_break(initial: u8) -> bool {
196    initial == BREAK
197}
198
199/// Parses a head from `input`, returning `(major, argument, bytes_read, indefinite)`.
200///
201/// `indefinite` is `true` for ai = 31 (open-ended items); the argument is 0.
202/// Reserved ai values 28–30 remain rejected. Non-minimal argument encodings
203/// are accepted: RFC 8949 §4.2.1 makes preferred serialization a SHOULD,
204/// not a well-formedness requirement.
205#[inline]
206pub(crate) fn read_head_ext(input: &[u8]) -> Result<(Major, u64, usize, bool), Error> {
207    let Some(&initial) = input.first() else {
208        return Err(Error::TRUNCATED);
209    };
210    let major = Major::from_initial(initial);
211    let ai = initial & 0x1f;
212    match ai {
213        0..=23 => Ok((major, u64::from(ai), 1, false)),
214        24..=27 => {
215            let len = ext_len(ai);
216            let end = len.checked_add(1).ok_or(Error::INVALID_ADDITIONAL_INFO)?;
217            if input.len() < end {
218                return Err(Error::TRUNCATED);
219            }
220            let mut arg: u64 = 0;
221            let mut i = 0;
222            while i < len {
223                arg = (arg << 8) | u64::from(input[1 + i]);
224                i += 1;
225            }
226            Ok((major, arg, end, false))
227        }
228        28..=30 => Err(Error::INVALID_ADDITIONAL_INFO),
229        _ => Ok((major, 0, 1, true)),
230    }
231}
232
233/// Parses a head, rejecting indefinite lengths (ai = 31).
234#[inline]
235pub(crate) fn read_head(input: &[u8]) -> Result<(Major, u64, usize), Error> {
236    let (major, arg, used, indef) = read_head_ext(input)?;
237    match indef {
238        true => Err(Error::INDEFINITE_UNSUPPORTED),
239        false => Ok((major, arg, used)),
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::{Major, Simple, ai_of, ext_len, head_len, read_head, write_head};
246
247    #[test]
248    fn preferred_argument_widths() {
249        assert_eq!(ai_of(0), 0);
250        assert_eq!(ai_of(23), 23);
251        assert_eq!(ai_of(24), 24);
252        assert_eq!(ai_of(0xff), 24);
253        assert_eq!(ai_of(0x100), 25);
254        assert_eq!(ai_of(0xffff), 25);
255        assert_eq!(ai_of(0x1_0000), 26);
256        assert_eq!(ai_of(0xffff_ffff), 26);
257        assert_eq!(ai_of(0x1_0000_0000), 27);
258        assert_eq!(ai_of(u64::MAX), 27);
259        assert_eq!((head_len(23), head_len(24)), (1, 2));
260        assert_eq!(head_len(u64::MAX), 9);
261        assert_eq!(ext_len(31), 0);
262    }
263
264    #[test]
265    fn head_roundtrip() {
266        let mut buf = [0u8; 9];
267        for arg in [0u64, 23, 24, 255, 256, 65_535, 65_536, u64::from(u32::MAX), u64::MAX] {
268            let n = write_head(&mut buf, Major::Unsigned, arg).unwrap();
269            let (major, parsed, used) = read_head(&buf).unwrap();
270            assert_eq!(major, Major::Unsigned);
271            assert_eq!((parsed, used), (arg, n));
272        }
273    }
274
275    #[test]
276    fn head_out_of_space() {
277        let mut buf = [0u8; 1];
278        assert_eq!(write_head(&mut buf, Major::Map, 300), Err(crate::Error::OUT_OF_SPACE));
279    }
280
281    #[test]
282    fn major_dispatch() {
283        assert_eq!(Major::from_initial(0x18), Major::Unsigned);
284        assert_eq!(Major::from_initial(0x39), Major::Negative);
285        assert_eq!(Major::from_initial(0xf4), Major::Simple);
286        assert_eq!(Major::from_initial(0xff), Major::Simple);
287    }
288
289    #[test]
290    fn simple_two_byte_validity() {
291        assert!(!Simple(31).valid_two_byte());
292        assert!(Simple(32).valid_two_byte());
293    }
294}