use std::fmt::{Display, Formatter, Result as FmtResult};
use crate::wire::StreamMeta;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegionKind {
Meta,
DataBlob,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecodeHint {
Presence,
Bool,
I32,
U32,
I64,
#[cfg(feature = "unstable-v2")]
Alp(crate::decoder::Alp),
U64,
F32,
F64,
Bytes,
#[cfg(feature = "unstable-v2")]
PackedBits,
}
#[derive(Debug, Clone)]
pub struct BitField {
hi: u8,
lo: u8,
raw: u64,
meaning: String,
}
impl BitField {
pub fn mask(mask: u8, byte: u8, meaning: impl Into<String>) -> Self {
let (hi, lo) = mask_bounds(mask);
Self {
hi,
lo,
raw: u64::from((byte & mask) >> lo),
meaning: meaning.into(),
}
}
#[must_use]
pub fn flag(mask: u8, byte: u8, when_set: &str, when_clear: &str) -> Self {
debug_assert_eq!(mask.count_ones(), 1, "a flag occupies exactly one bit");
let meaning = if byte & mask == 0 {
when_clear
} else {
when_set
};
Self::mask(mask, byte, meaning)
}
#[must_use]
pub fn meaning(&self) -> &str {
&self.meaning
}
}
impl Display for BitField {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
if self.hi == self.lo {
write!(f, "bit {}", self.hi)?;
} else {
write!(f, "bits {}-{}", self.hi, self.lo)?;
}
let width = usize::from(self.hi - self.lo + 1);
write!(f, " = {:0width$b} -> {}", self.raw, self.meaning)
}
}
#[expect(
clippy::cast_possible_truncation,
reason = "a u8 mask spans at most 8 bits"
)]
fn mask_bounds(mask: u8) -> (u8, u8) {
debug_assert!(mask != 0, "a bit field needs at least one bit");
let lo = mask.trailing_zeros() as u8;
let hi = (u8::BITS - 1 - mask.leading_zeros()) as u8;
debug_assert_eq!(
u32::from(hi - lo) + 1,
mask.count_ones(),
"a bit field's mask must be one contiguous run of bits"
);
(hi, lo)
}
#[derive(Debug, Clone, Copy)]
pub struct BlobInfo {
pub meta: StreamMeta,
pub hint: DecodeHint,
}
#[derive(Debug, Clone)]
pub struct Region {
pub offset: usize,
pub len: usize,
pub depth: usize,
pub label: String,
pub value: Option<String>,
pub bits: Vec<BitField>,
pub kind: RegionKind,
pub container: bool,
pub blob: Option<BlobInfo>,
}
pub struct DumpTree {
pub buf_len: usize,
pub regions: Vec<Region>,
}