#[must_use]
pub fn tpm_offset(base: &[u8], cursor: &[u8]) -> usize {
let base_addr = base.as_ptr() as usize;
let cursor_addr = cursor.as_ptr() as usize;
cursor_addr.saturating_sub(base_addr).min(base.len())
}
#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub const fn tpm_value(value: usize) -> u64 {
value as u64
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum TpmError {
BufferOverflow {
offset: usize,
needed: usize,
available: usize,
},
IntegerTooLarge {
offset: usize,
value: u64,
},
InvalidBoolean {
offset: usize,
value: u64,
},
InvalidCc {
offset: usize,
value: u64,
},
InvalidMagicNumber {
offset: usize,
value: u64,
},
InvalidRc {
offset: usize,
value: u64,
},
InvalidTag {
offset: usize,
value: u64,
},
TooManyBytes {
offset: usize,
limit: usize,
actual: usize,
},
TooManyItems {
offset: usize,
limit: usize,
actual: usize,
},
TrailingData {
offset: usize,
actual: usize,
},
UnexpectedEnd {
offset: usize,
needed: usize,
available: usize,
},
VariantNotAvailable {
offset: usize,
value: u64,
},
}
impl TpmError {
#[must_use]
pub const fn kind(self) -> &'static str {
match self {
Self::BufferOverflow { .. } => "BufferOverflow",
Self::IntegerTooLarge { .. } => "IntegerTooLarge",
Self::InvalidBoolean { .. } => "InvalidBoolean",
Self::InvalidCc { .. } => "InvalidCc",
Self::InvalidMagicNumber { .. } => "InvalidMagicNumber",
Self::InvalidRc { .. } => "InvalidRc",
Self::InvalidTag { .. } => "InvalidTag",
Self::TooManyBytes { .. } => "TooManyBytes",
Self::TooManyItems { .. } => "TooManyItems",
Self::TrailingData { .. } => "TrailingData",
Self::UnexpectedEnd { .. } => "UnexpectedEnd",
Self::VariantNotAvailable { .. } => "VariantNotAvailable",
}
}
}
impl core::fmt::Display for TpmError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
use core::fmt::Write as _;
for (i, ch) in self.kind().char_indices() {
if ch.is_ascii_uppercase() {
if i != 0 {
f.write_char(' ')?;
}
f.write_char(ch.to_ascii_lowercase())?;
} else {
f.write_char(ch)?;
}
}
Ok(())
}
}
impl core::error::Error for TpmError {}
pub type TpmResult<T> = Result<T, TpmError>;