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        super::profile::ensure_lengths_supported(lengths)?;
28        check_input(input, limits)?;
29        Ok(Self {
30            input,
31            offset: 0,
32            consumed: input.get(..0).ok_or(error(ErrorReason::Truncated))?,
33            remaining: input,
34            budget: Budget::new(limits),
35            lengths,
36            failed: false,
37        })
38    }
39    /// Exact successfully consumed received span.
40    #[must_use]
41    pub fn consumed_bytes(&self) -> &'a [u8] {
42        self.consumed
43    }
44    /// Remaining received span, including an item that failed to frame.
45    #[must_use]
46    pub fn remaining_bytes(&self) -> &'a [u8] {
47        self.remaining
48    }
49
50    fn finish_step(
51        &mut self,
52        scanned: Result<Frame<'a>, CborError>,
53    ) -> Result<Frame<'a>, CborError> {
54        let result = scanned.and_then(|frame| {
55            let offset = add(self.offset, frame.received_bytes().len())?;
56            let consumed = self
57                .input
58                .get(..offset)
59                .ok_or(error(ErrorReason::Truncated))?;
60            let remaining = tail(self.input, offset)?;
61            // Commit the three cursor fields together after checking both
62            // spans. A framing error leaves the last valid partition intact.
63            self.offset = offset;
64            self.consumed = consumed;
65            self.remaining = remaining;
66            Ok(frame)
67        });
68        if result.is_err() {
69            self.failed = true;
70        }
71        result
72    }
73}
74
75impl<'a> Iterator for Cursor<'a> {
76    type Item = Result<Frame<'a>, CborError>;
77    fn next(&mut self) -> Option<Self::Item> {
78        if self.failed || self.offset == self.input.len() {
79            return None;
80        }
81        let framed = tail(self.input, self.offset)
82            .and_then(|remaining| scan(remaining, &mut self.budget, 0, None, true, self.lengths));
83        Some(self.finish_step(framed))
84    }
85}
86
87impl core::iter::FusedIterator for Cursor<'_> {}
88
89#[cfg(kani)]
90#[path = "cursor_proof_tests.rs"]
91mod proofs;