use super::error::{error, CborError, ErrorReason};
use super::limits::{Budget, Limits};
use super::profile::LengthPolicy;
use super::receipt::{check_input, Frame};
use super::scan::{add, scan, tail};
pub struct Cursor<'a> {
input: &'a [u8],
offset: usize,
consumed: &'a [u8],
remaining: &'a [u8],
budget: Budget,
lengths: LengthPolicy,
failed: bool,
}
impl<'a> Cursor<'a> {
pub fn new(input: &'a [u8], limits: Limits, lengths: LengthPolicy) -> Result<Self, CborError> {
super::profile::ensure_lengths_supported(lengths)?;
check_input(input, limits)?;
Ok(Self {
input,
offset: 0,
consumed: input.get(..0).ok_or(error(ErrorReason::Truncated))?,
remaining: input,
budget: Budget::new(limits),
lengths,
failed: false,
})
}
#[must_use]
pub fn consumed_bytes(&self) -> &'a [u8] {
self.consumed
}
#[must_use]
pub fn remaining_bytes(&self) -> &'a [u8] {
self.remaining
}
fn finish_step(
&mut self,
scanned: Result<Frame<'a>, CborError>,
) -> Result<Frame<'a>, CborError> {
let result = scanned.and_then(|frame| {
let offset = add(self.offset, frame.received_bytes().len())?;
let consumed = self
.input
.get(..offset)
.ok_or(error(ErrorReason::Truncated))?;
let remaining = tail(self.input, offset)?;
self.offset = offset;
self.consumed = consumed;
self.remaining = remaining;
Ok(frame)
});
if result.is_err() {
self.failed = true;
}
result
}
}
impl<'a> Iterator for Cursor<'a> {
type Item = Result<Frame<'a>, CborError>;
fn next(&mut self) -> Option<Self::Item> {
if self.failed || self.offset == self.input.len() {
return None;
}
let framed = tail(self.input, self.offset)
.and_then(|remaining| scan(remaining, &mut self.budget, 0, None, true, self.lengths));
Some(self.finish_step(framed))
}
}
impl core::iter::FusedIterator for Cursor<'_> {}
#[cfg(kani)]
#[path = "cursor_proof_tests.rs"]
mod proofs;