use core::fmt;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DiagKind {
UnknownChunk,
ShortChunk,
TrailingBytes,
BadVarint,
ChunkOverrun,
BadMagic,
EventListCorrupt,
RaggedArray,
EntryBudgetExhausted,
}
impl DiagKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::UnknownChunk => "unknown chunk",
Self::ShortChunk => "chunk too short for field",
Self::TrailingBytes => "trailing bytes in chunk",
Self::BadVarint => "malformed compressed integer",
Self::ChunkOverrun => "chunk length past end of parent",
Self::BadMagic => "unexpected file magic",
Self::EventListCorrupt => "event command list not terminated",
Self::RaggedArray => "array payload not a multiple of element size",
Self::EntryBudgetExhausted => "string list over the load's entry budget",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Diagnostic {
pub offset: u32,
pub chunk_id: u32,
pub struct_name: &'static str,
pub kind: DiagKind,
}
impl Diagnostic {
pub const EMPTY: Self = Self {
offset: 0,
chunk_id: 0,
struct_name: "",
kind: DiagKind::UnknownChunk,
};
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}: {} (chunk 0x{:02x}, offset {})",
self.struct_name,
self.kind.as_str(),
self.chunk_id,
self.offset
)
}
}
pub trait DiagSink {
fn push(&mut self, diag: Diagnostic);
#[inline]
fn should_abort(&self) -> bool {
false
}
#[inline]
fn first(&self) -> Option<Diagnostic> {
None
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct NullSink;
impl DiagSink for NullSink {
#[inline]
fn push(&mut self, _diag: Diagnostic) {}
}
#[derive(Debug)]
pub struct SliceSink<'b> {
slots: &'b mut [Diagnostic],
len: usize,
dropped: u32,
}
impl<'b> SliceSink<'b> {
#[must_use]
pub fn new(slots: &'b mut [Diagnostic]) -> Self {
Self {
slots,
len: 0,
dropped: 0,
}
}
#[must_use]
pub fn as_slice(&self) -> &[Diagnostic] {
&self.slots[..self.len]
}
#[must_use]
pub const fn dropped(&self) -> u32 {
self.dropped
}
}
impl DiagSink for SliceSink<'_> {
#[inline]
fn push(&mut self, diag: Diagnostic) {
if self.len < self.slots.len() {
self.slots[self.len] = diag;
self.len += 1;
} else {
self.dropped = self.dropped.saturating_add(1);
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct StrictSink {
first: Option<Diagnostic>,
}
impl StrictSink {
#[must_use]
pub const fn new() -> Self {
Self { first: None }
}
}
impl DiagSink for StrictSink {
#[inline]
fn push(&mut self, diag: Diagnostic) {
if self.first.is_none() {
self.first = Some(diag);
}
}
#[inline]
fn should_abort(&self) -> bool {
self.first.is_some()
}
#[inline]
fn first(&self) -> Option<Diagnostic> {
self.first
}
}
#[cfg(feature = "alloc")]
impl DiagSink for alloc::vec::Vec<Diagnostic> {
#[inline]
fn push(&mut self, diag: Diagnostic) {
Self::push(self, diag);
}
}