Skip to main content

codec_cbor/general/
receipt.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::compare::require_type;
8use super::cursor::Cursor;
9use super::error::{error, CborError, ErrorReason};
10use super::float::Float;
11use super::limits::{Budget, Limits};
12use super::profile::{LengthPolicy, Profile};
13use super::read_header::{read_header_prefix, ArgumentWidth, Header, MajorType};
14use super::scan::{add, scan, tail};
15
16/// Complete integer domain: unsigned values or the negative argument `n`
17/// representing `-1-n`, including -18446744073709551616.
18pub struct Integer {
19    negative: bool,
20    argument: u64,
21}
22
23impl Integer {
24    /// Whether this is a major-type-one integer.
25    #[must_use]
26    pub const fn is_negative(&self) -> bool {
27        self.negative
28    }
29    /// Extract the complete unsigned argument. The caller owns this scalar copy.
30    #[must_use]
31    pub const fn argument(&self) -> u64 {
32        self.argument
33    }
34    /// Convert exactly to a signed type that covers the entire CBOR domain.
35    #[must_use]
36    pub fn to_i128(&self) -> i128 {
37        if self.negative {
38            -1 - i128::from(self.argument)
39        } else {
40            i128::from(self.argument)
41        }
42    }
43}
44
45impl Drop for Integer {
46    fn drop(&mut self) {
47        self.argument.zeroize();
48        self.negative.zeroize();
49    }
50}
51impl ZeroizeOnDrop for Integer {}
52
53/// Receipt for one well-formed item, without a basic-validity claim.
54///
55/// Framing allows invalid UTF-8 and equivalent map keys. Use `validate_exact`
56/// or `Frame::validate` when the basic generic data model is required. Tag
57/// semantics are always separate. All payload spans borrow the original owner.
58pub struct Frame<'a> {
59    pub(super) encoded: &'a [u8],
60    pub(super) body: &'a [u8],
61    pub(super) header: Header<'a>,
62    pub(super) limits: Limits,
63    pub(super) lengths: LengthPolicy,
64}
65
66impl<'a> Frame<'a> {
67    /// Exact complete received item, with its original headers and ordering.
68    #[must_use]
69    pub const fn received_bytes(&self) -> &'a [u8] {
70        self.encoded
71    }
72    /// Inspect the original header without reconstructing it.
73    #[must_use]
74    pub const fn header(&self) -> &Header<'a> {
75        &self.header
76    }
77    /// Validate this receipt using a fresh, caller-selected resource budget.
78    pub fn validate(&self, profile: Profile, limits: Limits) -> Result<Item<'a>, CborError> {
79        validate_exact(self.encoded, profile, limits)
80    }
81    /// Extract an integer without truncating either argument domain.
82    pub fn integer(&self) -> Result<Integer, CborError> {
83        let negative = match self.header.major_type() {
84            MajorType::Unsigned => false,
85            MajorType::Negative => true,
86            _ => return Err(error(ErrorReason::WrongType)),
87        };
88        Ok(Integer {
89            negative,
90            argument: self
91                .header
92                .argument()
93                .ok_or(error(ErrorReason::WrongType))?,
94        })
95    }
96    /// Extract protected floating-point bits.
97    pub fn float(&self) -> Result<Float, CborError> {
98        self.header.float()?.ok_or(error(ErrorReason::WrongType))
99    }
100    /// Extract an untagged simple value (20/21 are booleans, 22 is null).
101    pub fn simple_value(&self) -> Result<u8, CborError> {
102        self.header
103            .simple_value()?
104            .ok_or(error(ErrorReason::WrongType))
105    }
106    /// Extract an untagged boolean; other simple values have a different type.
107    pub fn as_bool(&self) -> Result<bool, CborError> {
108        const FALSE: u8 = 20;
109        const TRUE: u8 = 21;
110        match self.simple_value()? {
111            FALSE => Ok(false),
112            TRUE => Ok(true),
113            _ => Err(error(ErrorReason::WrongType)),
114        }
115    }
116    /// Borrow definite byte-string contents; chunked strings have no single span.
117    pub fn as_bytes(&self) -> Result<&'a [u8], CborError> {
118        require_type(self.header.major_type(), MajorType::Bytes)?;
119        self.contiguous()
120    }
121    /// Borrow definite text, checking UTF-8 even on a framing-only receipt.
122    pub fn as_text(&self) -> Result<&'a str, CborError> {
123        require_type(self.header.major_type(), MajorType::Text)?;
124        core::str::from_utf8(self.contiguous()?).map_err(|_| error(ErrorReason::InvalidUtf8))
125    }
126    fn contiguous(&self) -> Result<&'a [u8], CborError> {
127        if self.header.argument_width() == ArgumentWidth::Indefinite {
128            return Err(error(ErrorReason::NonContiguousString));
129        }
130        Ok(self.body)
131    }
132    /// Iterate borrowed contents of string chunks. Definite strings yield once.
133    /// Framing-only text chunks still require UTF-8 validation by the consumer.
134    pub fn string_chunks(&self) -> Result<StringChunks<'a>, CborError> {
135        if !matches!(self.header.major_type(), MajorType::Bytes | MajorType::Text) {
136            return Err(error(ErrorReason::WrongType));
137        }
138        Ok(StringChunks {
139            remaining: self.body,
140            definite: self.header.argument_width() != ArgumentWidth::Indefinite,
141            done: false,
142        })
143    }
144    /// Traverse direct array children, alternating map keys/values, or a tag's
145    /// single child. This framing cursor has its own cumulative limits; it does
146    /// not inherit or strengthen a parent's validity claim.
147    pub fn children(&self) -> Result<Cursor<'a>, CborError> {
148        if !matches!(
149            self.header.major_type(),
150            MajorType::Array | MajorType::Map | MajorType::Tag
151        ) {
152            return Err(error(ErrorReason::WrongType));
153        }
154        Cursor::new(self.body, self.limits, self.lengths)
155    }
156    /// Borrow an arbitrary tag's exact outer wrapper and contiguous byte payload.
157    /// No claim is made about embedded CBOR or registered tag semantics.
158    pub fn tagged_bytes(&self) -> Result<TaggedBytes<'a>, CborError> {
159        require_type(self.header.major_type(), MajorType::Tag)?;
160        let child = frame_exact(self.body, self.limits, self.lengths)?;
161        Ok(TaggedBytes {
162            tag: self
163                .header
164                .argument()
165                .ok_or(error(ErrorReason::WrongType))?,
166            outer: self.encoded,
167            payload: child.as_bytes()?,
168        })
169    }
170}
171
172/// Basic-valid item under the recorded profile. Registered tag semantics are
173/// opaque; this receipt never implies application-level or tag-24 validation.
174pub struct Item<'a> {
175    frame: Frame<'a>,
176    profile: Profile,
177}
178
179impl<'a> Item<'a> {
180    /// Borrow its exact framing receipt and typed accessors.
181    #[must_use]
182    pub const fn frame(&self) -> &Frame<'a> {
183        &self.frame
184    }
185    /// Inspect the guarantees selected at validation.
186    #[must_use]
187    pub const fn profile(&self) -> Profile {
188        self.profile
189    }
190    /// Iterate direct children as validated items under the same profile.
191    ///
192    /// A parent validated under a profile has every descendant validated
193    /// under it, so children keep the validated receipt type. Map children
194    /// alternate key and value; a tag yields its single enclosed item.
195    pub fn children(&self) -> Result<ItemChildren<'a>, CborError> {
196        Ok(ItemChildren {
197            frames: self.frame.children()?,
198            profile: self.profile,
199        })
200    }
201}
202
203/// Validated direct children of an [`Item`], in received order.
204pub struct ItemChildren<'a> {
205    frames: Cursor<'a>,
206    profile: Profile,
207}
208
209impl<'a> Iterator for ItemChildren<'a> {
210    type Item = Result<Item<'a>, CborError>;
211    fn next(&mut self) -> Option<Self::Item> {
212        let profile = self.profile;
213        self.frames
214            .next()
215            .map(|frame| frame.map(|frame| Item { frame, profile }))
216    }
217}
218
219impl core::iter::FusedIterator for ItemChildren<'_> {}
220
221/// Exact tagged wrapper and opaque byte contents, both tied to the input owner.
222pub struct TaggedBytes<'a> {
223    tag: u64,
224    outer: &'a [u8],
225    payload: &'a [u8],
226}
227
228impl<'a> TaggedBytes<'a> {
229    /// Registered or unregistered tag argument.
230    #[must_use]
231    pub const fn tag(&self) -> u64 {
232        self.tag
233    }
234    /// Complete original tagged item including the byte-string header.
235    #[must_use]
236    pub const fn received_bytes(&self) -> &'a [u8] {
237        self.outer
238    }
239    /// Exact opaque byte-string contents, without either wrapper header.
240    #[must_use]
241    pub const fn payload_bytes(&self) -> &'a [u8] {
242        self.payload
243    }
244    /// For standard tag 24 only, validate exactly one embedded CBOR item.
245    /// Empty payloads and payloads containing trailing items are rejected.
246    pub fn validate_embedded(
247        &self,
248        profile: Profile,
249        limits: Limits,
250    ) -> Result<Item<'a>, CborError> {
251        const ENCODED_CBOR_TAG: u64 = 24;
252        if self.tag != ENCODED_CBOR_TAG {
253            return Err(error(ErrorReason::WrongTag));
254        }
255        if self.payload.is_empty() {
256            return Err(error(ErrorReason::EmptyEmbeddedItem));
257        }
258        validate_exact(self.payload, profile, limits)
259    }
260}
261
262impl Drop for TaggedBytes<'_> {
263    fn drop(&mut self) {
264        self.tag.zeroize();
265    }
266}
267impl ZeroizeOnDrop for TaggedBytes<'_> {}
268
269/// Borrowed chunks with no concatenation or structural allocation.
270pub struct StringChunks<'a> {
271    remaining: &'a [u8],
272    definite: bool,
273    done: bool,
274}
275
276impl<'a> Iterator for StringChunks<'a> {
277    type Item = Result<&'a [u8], CborError>;
278    fn next(&mut self) -> Option<Self::Item> {
279        if self.done {
280            return None;
281        }
282        if self.definite {
283            self.done = true;
284            return Some(Ok(self.remaining));
285        }
286        if self.remaining.is_empty() {
287            self.done = true;
288            return None;
289        }
290        let result = (|| {
291            let header = read_header_prefix(self.remaining)?;
292            let length =
293                usize::try_from(header.argument().ok_or(error(ErrorReason::InvalidChunk))?)
294                    .map_err(|_| error(ErrorReason::ArithmeticOverflow))?;
295            let start = header.received_bytes().len();
296            let end = add(start, length)?;
297            let bytes = self
298                .remaining
299                .get(start..end)
300                .ok_or(error(ErrorReason::Truncated))?;
301            self.remaining = tail(self.remaining, end)?;
302            Ok(bytes)
303        })();
304        if result.is_err() {
305            self.done = true;
306        }
307        Some(result)
308    }
309}
310
311impl core::iter::FusedIterator for StringChunks<'_> {}
312
313pub(super) fn check_input(input: &[u8], limits: Limits) -> Result<(), CborError> {
314    if input.len() > limits.input {
315        Err(error(ErrorReason::InputLimit))
316    } else {
317        Ok(())
318    }
319}
320
321/// Frame one item and return the exact unconsumed suffix separately.
322pub fn frame_prefix(
323    input: &[u8],
324    limits: Limits,
325    lengths: LengthPolicy,
326) -> Result<(Frame<'_>, &[u8]), CborError> {
327    check_input(input, limits)?;
328    let frame = scan(input, &mut Budget::new(limits), 0, None, true, lengths)?;
329    let rest = tail(input, frame.encoded.len())?;
330    Ok((frame, rest))
331}
332
333/// Frame exactly one item, rejecting every trailing byte.
334pub fn frame_exact(
335    input: &[u8],
336    limits: Limits,
337    lengths: LengthPolicy,
338) -> Result<Frame<'_>, CborError> {
339    let (frame, rest) = frame_prefix(input, limits, lengths)?;
340    if !rest.is_empty() {
341        return Err(error(ErrorReason::TrailingData));
342    }
343    Ok(frame)
344}
345
346/// Validate one item under the selected basic-model and serialization profile.
347pub fn validate_prefix(
348    input: &[u8],
349    profile: Profile,
350    limits: Limits,
351) -> Result<(Item<'_>, &[u8]), CborError> {
352    check_input(input, limits)?;
353    let frame = scan(
354        input,
355        &mut Budget::new(limits),
356        0,
357        Some(profile),
358        true,
359        profile.lengths,
360    )?;
361    let rest = tail(input, frame.encoded.len())?;
362    Ok((Item { frame, profile }, rest))
363}
364
365/// Validate exactly one item under the selected profile, rejecting trailing bytes.
366pub fn validate_exact(
367    input: &[u8],
368    profile: Profile,
369    limits: Limits,
370) -> Result<Item<'_>, CborError> {
371    let (item, rest) = validate_prefix(input, profile, limits)?;
372    if !rest.is_empty() {
373        return Err(error(ErrorReason::TrailingData));
374    }
375    Ok(item)
376}