font_parse/error.rs
1//! Typed, exhaustive error taxonomy for every parser in the crate.
2//!
3//! All decoding is bounds-checked and total: every malformed, truncated, or
4//! hostile input yields one of these variants — never a panic, never an
5//! out-of-bounds read. The enum is deliberately **exhaustive** (no
6//! `#[non_exhaustive]`): callers are expected to match every variant, and a
7//! new variant is a semver-minor event by design.
8//!
9//! `TruncatedTable` conventions: `tag` is the table tag (or container
10//! pseudo-tag, e.g. `*b"wOFF"`) that was being read, `expected` is the
11//! required absolute end offset in the buffer being read, and `got` is the
12//! number of bytes actually available. Where the exact tag is not known (e.g.
13//! the SFNT offset table itself) the closest container tag is used.
14
15use alloc::format;
16use alloc::string::String;
17use core::fmt;
18
19/// A four-byte table tag, as raw bytes (used in [`ParseError::TruncatedTable`]).
20pub type RawTag = [u8; 4];
21
22/// The single crate-level error for all font parsing.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum ParseError {
25 /// The SFNT offset table (or WOFF/WOFF2 header) is malformed: bad
26 /// signature, impossible table count, or a directory entry whose
27 /// offset/length pair is out of range.
28 InvalidSfnt,
29 /// A four-byte tag carried a value outside the known table set, where a
30 /// known tag was required. Raw (unknown) table access is available via
31 /// [`crate::FontRef::table_by_tag`] — this variant applies to typed
32 /// lookups only.
33 UnknownTableTag(RawTag),
34 /// A structure declared (or a read required) more bytes than the buffer
35 /// holds. Bounds are checked at every read; `tag` is the table (or
36 /// container) being read, `expected` the required absolute end offset,
37 /// `got` the bytes actually available.
38 TruncatedTable {
39 /// Tag of the table (or container pseudo-tag) being read.
40 tag: RawTag,
41 /// Required absolute end offset in the buffer.
42 expected: usize,
43 /// Bytes actually available.
44 got: usize,
45 },
46 /// A `cmap` subtable carries a format this parser does not implement
47 /// (formats 2, 8, 10, 13, 14) or a structurally invalid format number.
48 /// Supported formats: 0, 4, 6, 12.
49 InvalidCmapFormat(u16),
50 /// A `glyf`/`loca`/`gvar` record is structurally invalid: bad coordinate
51 /// runs, a composite component loop that exceeds the nesting cap, a loca
52 /// entry descending, or a WOFF2 glyph substream inconsistency.
53 InvalidGlyphFormat,
54 /// A WOFF2 table directory entry declares a transformation version that
55 /// is not defined for its tag (e.g. transformed `name`), so the entry
56 /// cannot be decoded. Only glyf/loca (version 0) and hmtx (version 1)
57 /// transforms are defined by WOFF2 2.0.
58 UnsupportedWoff2Transform,
59 /// A collection (TTC) index beyond the number of fonts declared by the
60 /// `ttcf` header.
61 CollectionIndexOutOfBounds {
62 /// Index that was requested.
63 index: usize,
64 /// Number of fonts the collection declares.
65 count: usize,
66 },
67 /// The `head` table's `unitsPerEm` is zero or above the OpenType maximum
68 /// of 16384.
69 InvalidUnitsPerEm(u16),
70}
71
72impl fmt::Display for ParseError {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 match self {
75 ParseError::InvalidSfnt => write!(f, "invalid SFNT/WOFF container"),
76 ParseError::UnknownTableTag(tag) => {
77 write!(
78 f,
79 "unknown table tag {:?}",
80 char::from_u32(u32::from_be_bytes(*tag)).unwrap_or(char::REPLACEMENT_CHARACTER)
81 )
82 }
83 ParseError::TruncatedTable { tag, expected, got } => {
84 let name = tag_display(tag);
85 write!(
86 f,
87 "truncated table {name}: need {expected} bytes, have {got}"
88 )
89 }
90 ParseError::InvalidCmapFormat(fmt_) => {
91 write!(f, "unsupported cmap subtable format {fmt_}")
92 }
93 ParseError::InvalidGlyphFormat => write!(f, "invalid glyph/gvar record"),
94 ParseError::UnsupportedWoff2Transform => {
95 write!(f, "unsupported WOFF2 table transform")
96 }
97 ParseError::CollectionIndexOutOfBounds { index, count } => {
98 write!(f, "collection index {index} out of bounds ({count} fonts)")
99 }
100 ParseError::InvalidUnitsPerEm(upem) => {
101 write!(f, "invalid unitsPerEm {upem} (must be 1..=16384)")
102 }
103 }
104 }
105}
106
107/// Render a raw tag as its closest printable form, for diagnostics.
108pub(crate) fn tag_display(tag: &[u8; 4]) -> String {
109 let printable: String = tag
110 .iter()
111 .map(|&b| {
112 if b.is_ascii_graphic() || b == b' ' {
113 b as char
114 } else {
115 '.'
116 }
117 })
118 .collect();
119 format!("'{printable}'")
120}
121
122#[cfg(test)]
123mod tests {
124 #![allow(clippy::unwrap_used, clippy::expect_used)]
125 use super::ParseError;
126 use alloc::string::ToString;
127
128 // Test harness: assertions legitimately panic; the parse paths under test
129 // (the lib target) remain lint-clean.
130
131 #[test]
132 fn display_is_informative_and_total() {
133 // Every variant renders without panicking — the error type itself is
134 // part of the never-panic surface.
135 let cases = [
136 ParseError::InvalidSfnt,
137 ParseError::UnknownTableTag(*b"\x00\x01\x02\xff"),
138 ParseError::TruncatedTable {
139 tag: *b"head",
140 expected: 54,
141 got: 12,
142 },
143 ParseError::InvalidCmapFormat(14),
144 ParseError::InvalidGlyphFormat,
145 ParseError::UnsupportedWoff2Transform,
146 ParseError::CollectionIndexOutOfBounds { index: 3, count: 2 },
147 ParseError::InvalidUnitsPerEm(0),
148 ];
149 for e in cases {
150 let s = e.to_string();
151 assert!(!s.is_empty(), "{e:?} rendered empty");
152 }
153 }
154}