use alloc::format;
use alloc::string::String;
use core::fmt;
pub type RawTag = [u8; 4];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseError {
InvalidSfnt,
UnknownTableTag(RawTag),
TruncatedTable {
tag: RawTag,
expected: usize,
got: usize,
},
InvalidCmapFormat(u16),
InvalidGlyphFormat,
UnsupportedWoff2Transform,
CollectionIndexOutOfBounds {
index: usize,
count: usize,
},
InvalidUnitsPerEm(u16),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::InvalidSfnt => write!(f, "invalid SFNT/WOFF container"),
ParseError::UnknownTableTag(tag) => {
write!(
f,
"unknown table tag {:?}",
char::from_u32(u32::from_be_bytes(*tag)).unwrap_or(char::REPLACEMENT_CHARACTER)
)
}
ParseError::TruncatedTable { tag, expected, got } => {
let name = tag_display(tag);
write!(
f,
"truncated table {name}: need {expected} bytes, have {got}"
)
}
ParseError::InvalidCmapFormat(fmt_) => {
write!(f, "unsupported cmap subtable format {fmt_}")
}
ParseError::InvalidGlyphFormat => write!(f, "invalid glyph/gvar record"),
ParseError::UnsupportedWoff2Transform => {
write!(f, "unsupported WOFF2 table transform")
}
ParseError::CollectionIndexOutOfBounds { index, count } => {
write!(f, "collection index {index} out of bounds ({count} fonts)")
}
ParseError::InvalidUnitsPerEm(upem) => {
write!(f, "invalid unitsPerEm {upem} (must be 1..=16384)")
}
}
}
}
pub(crate) fn tag_display(tag: &[u8; 4]) -> String {
let printable: String = tag
.iter()
.map(|&b| {
if b.is_ascii_graphic() || b == b' ' {
b as char
} else {
'.'
}
})
.collect();
format!("'{printable}'")
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::ParseError;
use alloc::string::ToString;
#[test]
fn display_is_informative_and_total() {
let cases = [
ParseError::InvalidSfnt,
ParseError::UnknownTableTag(*b"\x00\x01\x02\xff"),
ParseError::TruncatedTable {
tag: *b"head",
expected: 54,
got: 12,
},
ParseError::InvalidCmapFormat(14),
ParseError::InvalidGlyphFormat,
ParseError::UnsupportedWoff2Transform,
ParseError::CollectionIndexOutOfBounds { index: 3, count: 2 },
ParseError::InvalidUnitsPerEm(0),
];
for e in cases {
let s = e.to_string();
assert!(!s.is_empty(), "{e:?} rendered empty");
}
}
}