Skip to main content

codec_cbor/general/
cursor.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use super::error::{error, CborError, ErrorReason};
6use super::limits::{Budget, Limits};
7use super::profile::LengthPolicy;
8use super::receipt::{check_input, Frame};
9use super::scan::{add, scan, tail};
10
11/// Framing cursor for a bounded sequence. Limits accumulate across items.
12/// After a parsing error it is fused; no malformed suffix can be skipped.
13/// Empty sequences are allowed, while `frame_exact` requires one item.
14pub struct Cursor<'a> {
15    input: &'a [u8],
16    offset: usize,
17    consumed: &'a [u8],
18    remaining: &'a [u8],
19    budget: Budget,
20    lengths: LengthPolicy,
21    failed: bool,
22}
23
24impl<'a> Cursor<'a> {
25    /// Create a cursor with explicit transport and indefinite-length limits.
26    pub fn new(input: &'a [u8], limits: Limits, lengths: LengthPolicy) -> Result<Self, CborError> {
27        check_input(input, limits)?;
28        Ok(Self {
29            input,
30            offset: 0,
31            consumed: input.get(..0).ok_or(error(ErrorReason::Truncated))?,
32            remaining: input,
33            budget: Budget::new(limits),
34            lengths,
35            failed: false,
36        })
37    }
38    /// Exact successfully consumed received span.
39    #[must_use]
40    pub fn consumed_bytes(&self) -> &'a [u8] {
41        self.consumed
42    }
43    /// Remaining received span, including an item that failed to frame.
44    #[must_use]
45    pub fn remaining_bytes(&self) -> &'a [u8] {
46        self.remaining
47    }
48}
49
50impl<'a> Iterator for Cursor<'a> {
51    type Item = Result<Frame<'a>, CborError>;
52    fn next(&mut self) -> Option<Self::Item> {
53        if self.failed || self.offset == self.input.len() {
54            return None;
55        }
56        let result = (|| {
57            let frame = scan(
58                tail(self.input, self.offset)?,
59                &mut self.budget,
60                0,
61                None,
62                true,
63                self.lengths,
64            )?;
65            let offset = add(self.offset, frame.received_bytes().len())?;
66            let consumed = self
67                .input
68                .get(..offset)
69                .ok_or(error(ErrorReason::Truncated))?;
70            let remaining = tail(self.input, offset)?;
71            self.offset = offset;
72            self.consumed = consumed;
73            self.remaining = remaining;
74            Ok(frame)
75        })();
76        if result.is_err() {
77            self.failed = true;
78        }
79        Some(result)
80    }
81}
82
83impl core::iter::FusedIterator for Cursor<'_> {}