Skip to main content

codec_cbor/general/
read_header.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use zeroize::{Zeroize, ZeroizeOnDrop};
6
7use super::error::{error, CborError, ErrorReason};
8use super::float::Float;
9
10pub(super) const INLINE_ARGUMENT_LIMIT: u64 = 24;
11const SIMPLE_EXTENDED_MINIMUM: u64 = 32;
12const ADDITIONAL_INFORMATION_MASK: u8 = 0x1f;
13const MAJOR_TYPE_SHIFT: u32 = 5;
14
15/// CBOR major type, independent of application or tag semantics.
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
17#[non_exhaustive]
18pub enum MajorType {
19    /// Unsigned integer.
20    Unsigned,
21    /// Negative integer, represented by its complete unsigned argument.
22    Negative,
23    /// Byte string.
24    Bytes,
25    /// Text string.
26    Text,
27    /// Array.
28    Array,
29    /// Map.
30    Map,
31    /// Tagged value.
32    Tag,
33    /// Simple value, float, or a standalone header break token.
34    Simple,
35}
36
37impl MajorType {
38    fn decode(code: u8) -> Result<Self, CborError> {
39        match code {
40            0 => Ok(Self::Unsigned),
41            1 => Ok(Self::Negative),
42            2 => Ok(Self::Bytes),
43            3 => Ok(Self::Text),
44            4 => Ok(Self::Array),
45            5 => Ok(Self::Map),
46            6 => Ok(Self::Tag),
47            7 => Ok(Self::Simple),
48            _ => Err(error(ErrorReason::ReservedAdditionalInformation)),
49        }
50    }
51
52    pub(super) const fn prefix(self) -> u8 {
53        match self {
54            Self::Unsigned => 0x00,
55            Self::Negative => 0x20,
56            Self::Bytes => 0x40,
57            Self::Text => 0x60,
58            Self::Array => 0x80,
59            Self::Map => 0xa0,
60            Self::Tag => 0xc0,
61            Self::Simple => 0xe0,
62        }
63    }
64}
65
66/// Received argument/payload width, including indefinite and break tokens.
67#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68#[non_exhaustive]
69pub enum ArgumentWidth {
70    /// The argument is in the initial byte.
71    Inline,
72    /// One additional byte.
73    One,
74    /// Two additional bytes, or a binary16 float.
75    Two,
76    /// Four additional bytes, or a binary32 float.
77    Four,
78    /// Eight additional bytes, or a binary64 float.
79    Eight,
80    /// An indefinite-length header.
81    Indefinite,
82    /// A break token, which is not itself a data item.
83    Break,
84}
85
86pub(super) fn preferred_width(value: u64) -> ArgumentWidth {
87    if value < INLINE_ARGUMENT_LIMIT {
88        ArgumentWidth::Inline
89    } else if value <= u64::from(u8::MAX) {
90        ArgumentWidth::One
91    } else if value <= u64::from(u16::MAX) {
92        ArgumentWidth::Two
93    } else if value <= u64::from(u32::MAX) {
94        ArgumentWidth::Four
95    } else {
96        ArgumentWidth::Eight
97    }
98}
99
100/// Borrowed received header. Successful header decoding makes no payload claim.
101///
102/// Numeric argument copies are wiped on drop. The received bytes remain owned
103/// by the caller, which must provide a zeroizing owner for sensitive input.
104pub struct Header<'a> {
105    encoded: &'a [u8],
106    major: MajorType,
107    width: ArgumentWidth,
108    argument: Option<u64>,
109}
110
111impl<'a> Header<'a> {
112    /// Exact received header bytes, including any non-preferred width.
113    #[must_use]
114    pub const fn received_bytes(&self) -> &'a [u8] {
115        self.encoded
116    }
117    /// Inspect the major type.
118    #[must_use]
119    pub const fn major_type(&self) -> MajorType {
120        self.major
121    }
122    /// Inspect the received argument or float-payload width.
123    #[must_use]
124    pub const fn argument_width(&self) -> ArgumentWidth {
125        self.width
126    }
127    /// Return an integer argument; floats, indefinite lengths, and breaks have none.
128    #[must_use]
129    pub fn argument(&self) -> Option<u64> {
130        if self.is_float() {
131            None
132        } else {
133            self.argument
134        }
135    }
136    /// Observe shortest argument encoding independently of payload validation.
137    /// Floats, indefinite lengths, and breaks return `None`.
138    #[must_use]
139    pub fn has_preferred_argument(&self) -> Option<bool> {
140        self.argument()
141            .map(|value| preferred_width(value) == self.width)
142    }
143    /// Observe whether a float uses the shortest width that holds its value
144    /// exactly, including NaN significands. Non-float headers return `None`.
145    pub fn has_preferred_float(&self) -> Result<Option<bool>, CborError> {
146        Ok(self.float()?.map(|value| value.width() == value.shortest()))
147    }
148    /// Inspect whether this header carries IEEE floating-point bits.
149    #[must_use]
150    pub const fn is_float(&self) -> bool {
151        matches!(self.major, MajorType::Simple)
152            && matches!(
153                self.width,
154                ArgumentWidth::Two | ArgumentWidth::Four | ArgumentWidth::Eight
155            )
156    }
157    /// Extract owned protected floating-point bits, if present.
158    pub fn float(&self) -> Result<Option<Float>, CborError> {
159        if !self.is_float() {
160            return Ok(None);
161        }
162        let value = self.argument.ok_or(error(ErrorReason::Truncated))?;
163        match self.width {
164            ArgumentWidth::Two => Ok(Some(Float::binary16(
165                u16::try_from(value).map_err(|_| error(ErrorReason::ArithmeticOverflow))?,
166            ))),
167            ArgumentWidth::Four => Ok(Some(Float::binary32(
168                u32::try_from(value).map_err(|_| error(ErrorReason::ArithmeticOverflow))?,
169            ))),
170            ArgumentWidth::Eight => Ok(Some(Float::binary64(value))),
171            _ => Err(error(ErrorReason::WrongType)),
172        }
173    }
174    /// Extract a simple-value code; floats and breaks return `None`.
175    pub fn simple_value(&self) -> Result<Option<u8>, CborError> {
176        if self.major != MajorType::Simple || self.is_float() || self.width == ArgumentWidth::Break
177        {
178            return Ok(None);
179        }
180        self.argument
181            .map(|value| u8::try_from(value).map_err(|_| error(ErrorReason::ArithmeticOverflow)))
182            .transpose()
183    }
184}
185
186impl Drop for Header<'_> {
187    fn drop(&mut self) {
188        self.argument.zeroize();
189    }
190}
191impl ZeroizeOnDrop for Header<'_> {}
192
193fn argument_bytes<const N: usize>(input: &[u8]) -> Result<[u8; N], CborError> {
194    let end = 1_usize
195        .checked_add(N)
196        .ok_or(error(ErrorReason::ArithmeticOverflow))?;
197    input
198        .get(1..end)
199        .ok_or(error(ErrorReason::Truncated))?
200        .try_into()
201        .map_err(|_| error(ErrorReason::Truncated))
202}
203
204/// Decode at most nine header bytes, without inspecting or normalizing the payload.
205pub fn read_header_prefix(input: &[u8]) -> Result<Header<'_>, CborError> {
206    let initial = *input.first().ok_or(error(ErrorReason::EmptyInput))?;
207    let major = MajorType::decode(initial >> MAJOR_TYPE_SHIFT)?;
208    let info = initial & ADDITIONAL_INFORMATION_MASK;
209    let (width, argument, length) = match info {
210        0..=23 => (ArgumentWidth::Inline, Some(u64::from(info)), 1),
211        24 => (
212            ArgumentWidth::One,
213            Some(u64::from(u8::from_be_bytes(argument_bytes::<1>(input)?))),
214            2,
215        ),
216        25 => (
217            ArgumentWidth::Two,
218            Some(u64::from(u16::from_be_bytes(argument_bytes::<2>(input)?))),
219            3,
220        ),
221        26 => (
222            ArgumentWidth::Four,
223            Some(u64::from(u32::from_be_bytes(argument_bytes::<4>(input)?))),
224            5,
225        ),
226        27 => (
227            ArgumentWidth::Eight,
228            Some(u64::from_be_bytes(argument_bytes::<8>(input)?)),
229            9,
230        ),
231        31 if matches!(
232            major,
233            MajorType::Bytes | MajorType::Text | MajorType::Array | MajorType::Map
234        ) =>
235        {
236            (ArgumentWidth::Indefinite, None, 1)
237        }
238        31 if major == MajorType::Simple => (ArgumentWidth::Break, None, 1),
239        31 => return Err(error(ErrorReason::InvalidIndefiniteArgument)),
240        _ => return Err(error(ErrorReason::ReservedAdditionalInformation)),
241    };
242    if major == MajorType::Simple
243        && width == ArgumentWidth::One
244        && argument.is_some_and(|value| value < SIMPLE_EXTENDED_MINIMUM)
245    {
246        return Err(error(ErrorReason::InvalidSimpleValue));
247    }
248    let encoded = input.get(..length).ok_or(error(ErrorReason::Truncated))?;
249    Ok(Header {
250        encoded,
251        major,
252        width,
253        argument,
254    })
255}