use zeroize::{Zeroize, ZeroizeOnDrop};
use super::compare::require_type;
use super::cursor::Cursor;
use super::error::{error, CborError, ErrorReason};
use super::float::Float;
use super::limits::{Budget, Limits};
use super::profile::{LengthPolicy, Profile};
use super::read_header::{read_header_prefix, ArgumentWidth, Header, MajorType};
use super::scan::{add, scan, tail};
pub struct Integer {
negative: bool,
argument: u64,
}
impl Integer {
#[must_use]
pub const fn is_negative(&self) -> bool {
self.negative
}
#[must_use]
pub const fn argument(&self) -> u64 {
self.argument
}
#[must_use]
pub fn to_i128(&self) -> i128 {
if self.negative {
-1 - i128::from(self.argument)
} else {
i128::from(self.argument)
}
}
}
impl Drop for Integer {
fn drop(&mut self) {
self.argument.zeroize();
self.negative.zeroize();
}
}
impl ZeroizeOnDrop for Integer {}
pub struct Frame<'a> {
pub(super) encoded: &'a [u8],
pub(super) body: &'a [u8],
pub(super) header: Header<'a>,
pub(super) limits: Limits,
pub(super) lengths: LengthPolicy,
}
impl<'a> Frame<'a> {
#[must_use]
pub const fn received_bytes(&self) -> &'a [u8] {
self.encoded
}
#[must_use]
pub const fn header(&self) -> &Header<'a> {
&self.header
}
pub fn validate(&self, profile: Profile, limits: Limits) -> Result<Item<'a>, CborError> {
validate_exact(self.encoded, profile, limits)
}
pub fn integer(&self) -> Result<Integer, CborError> {
let negative = match self.header.major_type() {
MajorType::Unsigned => false,
MajorType::Negative => true,
_ => return Err(error(ErrorReason::WrongType)),
};
Ok(Integer {
negative,
argument: self
.header
.argument()
.ok_or(error(ErrorReason::WrongType))?,
})
}
pub fn float(&self) -> Result<Float, CborError> {
self.header.float()?.ok_or(error(ErrorReason::WrongType))
}
pub fn simple_value(&self) -> Result<u8, CborError> {
self.header
.simple_value()?
.ok_or(error(ErrorReason::WrongType))
}
pub fn as_bool(&self) -> Result<bool, CborError> {
const FALSE: u8 = 20;
const TRUE: u8 = 21;
match self.simple_value()? {
FALSE => Ok(false),
TRUE => Ok(true),
_ => Err(error(ErrorReason::WrongType)),
}
}
pub fn as_bytes(&self) -> Result<&'a [u8], CborError> {
require_type(self.header.major_type(), MajorType::Bytes)?;
self.contiguous()
}
pub fn as_text(&self) -> Result<&'a str, CborError> {
require_type(self.header.major_type(), MajorType::Text)?;
core::str::from_utf8(self.contiguous()?).map_err(|_| error(ErrorReason::InvalidUtf8))
}
fn contiguous(&self) -> Result<&'a [u8], CborError> {
if self.header.argument_width() == ArgumentWidth::Indefinite {
return Err(error(ErrorReason::NonContiguousString));
}
Ok(self.body)
}
pub fn string_chunks(&self) -> Result<StringChunks<'a>, CborError> {
if !matches!(self.header.major_type(), MajorType::Bytes | MajorType::Text) {
return Err(error(ErrorReason::WrongType));
}
Ok(StringChunks {
remaining: self.body,
definite: self.header.argument_width() != ArgumentWidth::Indefinite,
done: false,
})
}
pub fn children(&self) -> Result<Cursor<'a>, CborError> {
if !matches!(
self.header.major_type(),
MajorType::Array | MajorType::Map | MajorType::Tag
) {
return Err(error(ErrorReason::WrongType));
}
Cursor::new(self.body, self.limits, self.lengths)
}
pub fn tagged_bytes(&self) -> Result<TaggedBytes<'a>, CborError> {
require_type(self.header.major_type(), MajorType::Tag)?;
let child = frame_exact(self.body, self.limits, self.lengths)?;
Ok(TaggedBytes {
tag: self
.header
.argument()
.ok_or(error(ErrorReason::WrongType))?,
outer: self.encoded,
payload: child.as_bytes()?,
})
}
}
pub struct Item<'a> {
frame: Frame<'a>,
profile: Profile,
}
impl<'a> Item<'a> {
#[must_use]
pub const fn frame(&self) -> &Frame<'a> {
&self.frame
}
#[must_use]
pub const fn profile(&self) -> Profile {
self.profile
}
pub fn children(&self) -> Result<ItemChildren<'a>, CborError> {
Ok(ItemChildren {
frames: self.frame.children()?,
profile: self.profile,
})
}
}
pub struct ItemChildren<'a> {
frames: Cursor<'a>,
profile: Profile,
}
impl<'a> Iterator for ItemChildren<'a> {
type Item = Result<Item<'a>, CborError>;
fn next(&mut self) -> Option<Self::Item> {
let profile = self.profile;
self.frames
.next()
.map(|frame| frame.map(|frame| Item { frame, profile }))
}
}
impl core::iter::FusedIterator for ItemChildren<'_> {}
pub struct TaggedBytes<'a> {
tag: u64,
outer: &'a [u8],
payload: &'a [u8],
}
impl<'a> TaggedBytes<'a> {
#[must_use]
pub const fn tag(&self) -> u64 {
self.tag
}
#[must_use]
pub const fn received_bytes(&self) -> &'a [u8] {
self.outer
}
#[must_use]
pub const fn payload_bytes(&self) -> &'a [u8] {
self.payload
}
pub fn validate_embedded(
&self,
profile: Profile,
limits: Limits,
) -> Result<Item<'a>, CborError> {
const ENCODED_CBOR_TAG: u64 = 24;
if self.tag != ENCODED_CBOR_TAG {
return Err(error(ErrorReason::WrongTag));
}
if self.payload.is_empty() {
return Err(error(ErrorReason::EmptyEmbeddedItem));
}
validate_exact(self.payload, profile, limits)
}
}
impl Drop for TaggedBytes<'_> {
fn drop(&mut self) {
self.tag.zeroize();
}
}
impl ZeroizeOnDrop for TaggedBytes<'_> {}
pub struct StringChunks<'a> {
remaining: &'a [u8],
definite: bool,
done: bool,
}
impl<'a> Iterator for StringChunks<'a> {
type Item = Result<&'a [u8], CborError>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
if self.definite {
self.done = true;
return Some(Ok(self.remaining));
}
if self.remaining.is_empty() {
self.done = true;
return None;
}
let result = (|| {
let header = read_header_prefix(self.remaining)?;
let length =
usize::try_from(header.argument().ok_or(error(ErrorReason::InvalidChunk))?)
.map_err(|_| error(ErrorReason::ArithmeticOverflow))?;
let start = header.received_bytes().len();
let end = add(start, length)?;
let bytes = self
.remaining
.get(start..end)
.ok_or(error(ErrorReason::Truncated))?;
self.remaining = tail(self.remaining, end)?;
Ok(bytes)
})();
if result.is_err() {
self.done = true;
}
Some(result)
}
}
impl core::iter::FusedIterator for StringChunks<'_> {}
pub(super) fn check_input(input: &[u8], limits: Limits) -> Result<(), CborError> {
if input.len() > limits.input {
Err(error(ErrorReason::InputLimit))
} else {
Ok(())
}
}
pub fn frame_prefix(
input: &[u8],
limits: Limits,
lengths: LengthPolicy,
) -> Result<(Frame<'_>, &[u8]), CborError> {
check_input(input, limits)?;
let frame = scan(input, &mut Budget::new(limits), 0, None, true, lengths)?;
let rest = tail(input, frame.encoded.len())?;
Ok((frame, rest))
}
pub fn frame_exact(
input: &[u8],
limits: Limits,
lengths: LengthPolicy,
) -> Result<Frame<'_>, CborError> {
let (frame, rest) = frame_prefix(input, limits, lengths)?;
if !rest.is_empty() {
return Err(error(ErrorReason::TrailingData));
}
Ok(frame)
}
pub fn validate_prefix(
input: &[u8],
profile: Profile,
limits: Limits,
) -> Result<(Item<'_>, &[u8]), CborError> {
profile.ensure_supported()?;
check_input(input, limits)?;
let frame = scan(
input,
&mut Budget::new(limits),
0,
Some(profile),
true,
profile.lengths,
)?;
let rest = tail(input, frame.encoded.len())?;
Ok((Item { frame, profile }, rest))
}
pub fn validate_exact(
input: &[u8],
profile: Profile,
limits: Limits,
) -> Result<Item<'_>, CborError> {
let (item, rest) = validate_prefix(input, profile, limits)?;
if !rest.is_empty() {
return Err(error(ErrorReason::TrailingData));
}
Ok(item)
}