use super::error::{overflow, size};
use super::read_header::{identifier_length, measure_length, span};
use super::validate_options::ValidatedOptions;
use super::{Options, TlvError};
use codec_proto::generated::proto::reallyme::codec::v1::{CodecTlvIdentifier, CodecTlvLength};
pub fn read_identifier<'a>(input: &'a [u8], options: &Options) -> Result<Identifier<'a>, TlvError> {
let options = ValidatedOptions::for_input(input, options)?;
let end = identifier_length(input, &options)?;
Ok(Identifier {
bytes: input.get(..end).ok_or_else(overflow)?,
remainder: input.get(end..).ok_or_else(overflow)?,
receipt: CodecTlvIdentifier {
identifier: Some(span(0, end)?).into(),
consumed_bytes: size(end)?,
},
})
}
pub fn read_length<'a>(input: &'a [u8], options: &Options) -> Result<Length<'a>, TlvError> {
let options = ValidatedOptions::for_input(input, options)?;
let (end, declared) = measure_length(input, &options)?;
Ok(Length {
bytes: input.get(..end).ok_or_else(overflow)?,
remainder: input.get(end..).ok_or_else(overflow)?,
receipt: CodecTlvLength {
length_octets: Some(span(0, end)?).into(),
declared_value_length: *declared,
consumed_bytes: size(end)?,
},
})
}
pub struct Identifier<'a> {
bytes: &'a [u8],
remainder: &'a [u8],
receipt: CodecTlvIdentifier,
}
impl<'a> Identifier<'a> {
#[must_use]
pub const fn identifier_bytes(&self) -> &'a [u8] {
self.bytes
}
#[must_use]
pub const fn supplied_remainder(&self) -> &'a [u8] {
self.remainder
}
#[must_use]
pub const fn consumed_bytes(&self) -> usize {
self.bytes.len()
}
#[must_use]
pub const fn contract(&self) -> &CodecTlvIdentifier {
&self.receipt
}
#[must_use]
pub fn into_contract(self) -> CodecTlvIdentifier {
self.receipt
}
}
pub struct Length<'a> {
bytes: &'a [u8],
remainder: &'a [u8],
receipt: CodecTlvLength,
}
impl<'a> Length<'a> {
#[must_use]
pub const fn length_octets(&self) -> &'a [u8] {
self.bytes
}
#[must_use]
pub const fn supplied_remainder(&self) -> &'a [u8] {
self.remainder
}
#[must_use]
pub const fn consumed_bytes(&self) -> usize {
self.bytes.len()
}
#[must_use]
pub const fn declared_value_length(&self) -> u64 {
self.receipt.declared_value_length
}
#[must_use]
pub const fn contract(&self) -> &CodecTlvLength {
&self.receipt
}
#[must_use]
pub fn into_contract(self) -> CodecTlvLength {
self.receipt
}
}