Skip to main content

font_model/
error.rs

1//! Typed, exhaustive error taxonomy for the model.
2//!
3//! Every failure the model can produce names **the glyph and the field** it
4//! came from, so an editor can highlight the offending cell and a writer can
5//! emit a diagnostic without re-deriving context. The enum is deliberately
6//! exhaustive (no `#[non_exhaustive]`): callers are expected to match every
7//! variant, and a new variant is a semver-minor event by design.
8
9use alloc::format;
10use alloc::string::String;
11use core::fmt;
12
13use crate::GlyphId;
14
15/// The single crate-level error for model construction, validation, and
16/// subsetting.
17#[derive(Debug, Clone, PartialEq)]
18pub enum ModelError {
19    /// `unitsPerEm` is outside the OpenType-legal range `16..=16384`.
20    InvalidUnitsPerEm {
21        /// The rejected value.
22        units_per_em: u16,
23    },
24    /// A glyph with at least one outline point has a zero advance width.
25    /// An empty (space-like) glyph may legitimately have a zero advance.
26    ZeroAdvance {
27        /// The glyph whose `advance_width` is zero.
28        glyph: GlyphId,
29    },
30    /// A glyph's outline contour is not closed with a trailing
31    /// [`Close`](crate::Command::Close) command.
32    UnclosedContour {
33        /// The glyph with the unclosed contour.
34        glyph: GlyphId,
35        /// Index of the offending contour within the outline.
36        contour: usize,
37    },
38    /// An outline coordinate is NaN or infinite. Named per field so the
39    /// message points at the exact command slot that is corrupt.
40    NonFiniteCoordinate {
41        /// The glyph with the corrupt coordinate.
42        glyph: GlyphId,
43        /// Index of the contour within the outline.
44        contour: usize,
45        /// Index of the command within the contour.
46        command: usize,
47        /// The field name (`"x"`, `"y"`, `"control.x"`, …).
48        field: &'static str,
49    },
50    /// `cmap` entries are not strictly increasing in codepoint order — either
51    /// unsorted segments or two segments that overlap.
52    NonMonotonicCmap {
53        /// Index of the offending subtable within the `cmap`.
54        subtable: usize,
55        /// The previously seen codepoint.
56        previous: u32,
57        /// The codepoint that broke monotonicity.
58        current: u32,
59    },
60    /// A glyph id referenced by the model (from `cmap` or kerning) does not
61    /// exist in the font's glyph store.
62    UnknownGlyph {
63        /// The dangling reference.
64        glyph: GlyphId,
65        /// How many glyphs the font actually holds.
66        glyph_count: usize,
67    },
68    /// A computed advance width does not fit the `u16` that `hmtx` stores.
69    AdvanceOverflow {
70        /// The glyph whose advance could not be represented.
71        glyph: GlyphId,
72        /// The unclamped advance in font units.
73        advance: i32,
74    },
75    /// A `cmap` subtable format outside the modelled set (4 and 12) was
76    /// encountered while reading a font.
77    UnsupportedCmapFormat {
78        /// The rejected format number.
79        format: u16,
80    },
81    /// Reading a font failed: the byte-level parser rejected the input.
82    Parse {
83        /// The parser's own message, verbatim.
84        message: String,
85    },
86}
87
88impl fmt::Display for ModelError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            ModelError::InvalidUnitsPerEm { units_per_em } => write!(
92                f,
93                "unitsPerEm {units_per_em} out of range (must be 16..=16384)"
94            ),
95            ModelError::ZeroAdvance { glyph } => {
96                write!(f, "glyph {glyph} has outline but zero advance width")
97            }
98            ModelError::UnclosedContour { glyph, contour } => write!(
99                f,
100                "glyph {glyph} contour {contour} is not closed (no trailing Close)"
101            ),
102            ModelError::NonFiniteCoordinate {
103                glyph,
104                contour,
105                command,
106                field,
107            } => write!(
108                f,
109                "glyph {glyph} contour {contour} command {command} field {field} is not finite"
110            ),
111            ModelError::NonMonotonicCmap {
112                subtable,
113                previous,
114                current,
115            } => write!(
116                f,
117                "cmap subtable {subtable} is not strictly increasing: \
118                 U+{previous:04X} followed by U+{current:04X}"
119            ),
120            ModelError::UnknownGlyph { glyph, glyph_count } => write!(
121                f,
122                "glyph {} referenced but the font holds only {glyph_count}",
123                glyph.to_u32()
124            ),
125            ModelError::AdvanceOverflow { glyph, advance } => write!(
126                f,
127                "glyph {glyph} advance {advance} exceeds the u16 hmtx range"
128            ),
129            ModelError::UnsupportedCmapFormat { format } => write!(
130                f,
131                "unsupported cmap subtable format {format} (this model carries formats 4 and 12)"
132            ),
133            ModelError::Parse { message } => write!(f, "font parse failed: {message}"),
134        }
135    }
136}
137
138impl From<font_parse::ParseError> for ModelError {
139    fn from(e: font_parse::ParseError) -> Self {
140        ModelError::Parse {
141            message: format!("{e}"),
142        }
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    #![allow(clippy::unwrap_used, clippy::expect_used)]
149    use super::ModelError;
150    use crate::GlyphId;
151    use alloc::string::{String, ToString};
152
153    // Test harness: assertions legitimately panic; the lib target stays
154    // lint-clean.
155
156    /// Every variant, rendered once — `Display` coverage for the taxonomy.
157    fn all_variants() -> [ModelError; 10] {
158        [
159            ModelError::InvalidUnitsPerEm { units_per_em: 0 },
160            ModelError::ZeroAdvance {
161                glyph: GlyphId::new(1),
162            },
163            ModelError::UnclosedContour {
164                glyph: GlyphId::new(2),
165                contour: 3,
166            },
167            ModelError::NonFiniteCoordinate {
168                glyph: GlyphId::new(3),
169                contour: 1,
170                command: 4,
171                field: "control.y",
172            },
173            ModelError::NonMonotonicCmap {
174                subtable: 0,
175                previous: 0x41,
176                current: 0x40,
177            },
178            ModelError::UnknownGlyph {
179                glyph: GlyphId::new(9),
180                glyph_count: 2,
181            },
182            ModelError::AdvanceOverflow {
183                glyph: GlyphId::new(4),
184                advance: 70_000,
185            },
186            ModelError::UnsupportedCmapFormat { format: 6 },
187            ModelError::Parse {
188                message: String::from("truncated table 'head'"),
189            },
190            ModelError::InvalidUnitsPerEm {
191                units_per_em: 20_000,
192            },
193        ]
194    }
195
196    #[test]
197    fn display_names_the_glyph_and_field() {
198        for e in all_variants() {
199            let s = e.to_string();
200            assert!(!s.is_empty(), "{e:?} rendered empty");
201        }
202        let zero = ModelError::ZeroAdvance {
203            glyph: GlyphId::new(7),
204        }
205        .to_string();
206        assert!(
207            zero.contains('7'),
208            "zero-advance message omits the glyph: {zero}"
209        );
210        let nfc = ModelError::NonFiniteCoordinate {
211            glyph: GlyphId::new(2),
212            contour: 0,
213            command: 1,
214            field: "control.x",
215        }
216        .to_string();
217        assert!(
218            nfc.contains("control.x"),
219            "coordinate message omits the field"
220        );
221        let mono = ModelError::NonMonotonicCmap {
222            subtable: 1,
223            previous: 0x100,
224            current: 0x0F,
225        }
226        .to_string();
227        assert!(mono.contains("U+0100"), "cmap message omits the codepoints");
228    }
229
230    #[test]
231    fn parse_error_converts() {
232        let e: ModelError = font_parse::ParseError::InvalidSfnt.into();
233        assert!(matches!(e, ModelError::Parse { .. }));
234        assert!(e.to_string().starts_with("font parse failed:"));
235    }
236}