Skip to main content

font_shape/
error.rs

1//! Typed, exhaustive error taxonomy for the rasteriser and the measurement
2//! layer.
3//!
4//! The contract under fuzz and hostile geometry is *totality with a typed
5//! escape hatch*: a singular transform, an empty raster, or a missing glyph is
6//! one of these variants — never a panic, never an out-of-bounds write. The
7//! enum is deliberately exhaustive (no `#[non_exhaustive]`): callers match every
8//! variant, and a new variant is a semver-minor event by design.
9
10use alloc::format;
11use alloc::string::String;
12use core::fmt;
13
14/// The single crate-level error for rasterization and measurement.
15#[derive(Debug, Clone, PartialEq)]
16pub enum ShapeError {
17    /// The affine transform's linear part is singular, so it has no inverse
18    /// and collapses the plane.
19    SingularAffine {
20        /// The determinant that was (near) zero.
21        determinant: f32,
22    },
23    /// A transform stack was popped when empty. [`PathBuilder::pop_transform`]
24    /// returns this instead of quietly returning the identity, which would
25    /// silently drop a transform.
26    ///
27    /// [`PathBuilder::pop_transform`]: crate::PathBuilder::pop_transform
28    UnbalancedPop {
29        /// The stack depth at the pop.
30        depth: usize,
31    },
32    /// A size argument was zero, negative, or otherwise outside the usable
33    /// range for a raster of this dimension.
34    InvalidSize {
35        /// The requested width in pixels.
36        width: u32,
37        /// The requested height in pixels.
38        height: u32,
39    },
40    /// A scale factor was zero, negative, NaN, or infinite.
41    InvalidScale {
42        /// The rejected scale.
43        scale: f32,
44    },
45    /// A glyph id beyond the font's store was requested.
46    UnknownGlyph {
47        /// The dangling id's numeric value.
48        glyph: u32,
49        /// How many glyphs the font holds.
50        glyph_count: usize,
51    },
52    /// A coordinate was NaN or infinite where a finite one was required.
53    NonFiniteCoordinate {
54        /// Which axis: `"x"` or `"y"`.
55        axis: &'static str,
56    },
57    /// The raster is too large to allocate: `width × height` exceeded the
58    /// element cap, so the mask would be gigabytes.
59    RasterTooLarge {
60        /// Total mask elements requested.
61        pixels: usize,
62        /// The cap that was exceeded.
63        limit: usize,
64    },
65    /// A font's `units_per_em` was zero, which would make the scale factor
66    /// infinite.
67    DegenerateUnitsPerEm,
68}
69
70impl fmt::Display for ShapeError {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            ShapeError::SingularAffine { determinant } => write!(
74                f,
75                "affine transform is singular (determinant {determinant})"
76            ),
77            ShapeError::UnbalancedPop { depth } => {
78                write!(f, "transform stack popped at depth {depth} (already empty)")
79            }
80            ShapeError::InvalidSize { width, height } => {
81                write!(f, "invalid raster size {width}x{height}")
82            }
83            ShapeError::InvalidScale { scale } => write!(f, "invalid scale {scale}"),
84            ShapeError::UnknownGlyph { glyph, glyph_count } => write!(
85                f,
86                "glyph {} requested but the font holds only {glyph_count}",
87                glyph
88            ),
89            ShapeError::NonFiniteCoordinate { axis } => {
90                write!(f, "{axis} coordinate is not finite")
91            }
92            ShapeError::RasterTooLarge { pixels, limit } => {
93                write!(f, "raster of {pixels} pixels exceeds the {limit}-pixel cap")
94            }
95            ShapeError::DegenerateUnitsPerEm => write!(f, "font has unitsPerEm == 0"),
96        }
97    }
98}
99
100impl From<crate::affine::Affine2D> for ShapeError {
101    /// A transform with no inverse is the only way this conversion applies.
102    fn from(_t: crate::affine::Affine2D) -> Self {
103        ShapeError::SingularAffine { determinant: 0.0 }
104    }
105}
106
107impl From<core::num::ParseFloatError> for ShapeError {
108    /// A string that was meant to be a scale did not parse.
109    fn from(_e: core::num::ParseFloatError) -> Self {
110        ShapeError::InvalidScale { scale: f32::NAN }
111    }
112}
113
114/// A convenience alias for this crate's error.
115pub type Result<T> = core::result::Result<T, ShapeError>;
116
117/// The message a `ShapeError` carries, for diagnostics in a host that cannot
118/// propagate the type.
119#[must_use]
120pub fn message(e: &ShapeError) -> String {
121    format!("{e}")
122}
123
124#[cfg(test)]
125mod tests {
126    #![allow(
127        clippy::unwrap_used,
128        clippy::expect_used,
129        clippy::panic,
130        clippy::float_cmp
131    )]
132    use super::message;
133    use crate::ShapeError;
134    use alloc::string::ToString;
135
136    // Test harness: assertions legitimately panic; the lib target stays
137    // lint-clean.
138
139    #[test]
140    fn every_variant_renders_informatively() {
141        let cases = [
142            (ShapeError::SingularAffine { determinant: 0.0 }, "singular"),
143            (ShapeError::UnbalancedPop { depth: 0 }, "popped"),
144            (
145                ShapeError::InvalidSize {
146                    width: 0,
147                    height: 16,
148                },
149                "0x16",
150            ),
151            (ShapeError::InvalidScale { scale: -1.0 }, "-1"),
152            (
153                ShapeError::UnknownGlyph {
154                    glyph: 9,
155                    glyph_count: 2,
156                },
157                "glyph 9",
158            ),
159            (
160                ShapeError::NonFiniteCoordinate { axis: "y" },
161                "y coordinate",
162            ),
163            (
164                ShapeError::RasterTooLarge {
165                    pixels: 1_000_000,
166                    limit: 16_777_216,
167                },
168                "1000000",
169            ),
170            (ShapeError::DegenerateUnitsPerEm, "unitsPerEm == 0"),
171        ];
172        for (e, needle) in cases {
173            let s = e.to_string();
174            assert!(!s.is_empty());
175            assert!(s.contains(needle), "{s:?} should mention {needle:?}");
176            assert_eq!(message(&e), s);
177        }
178    }
179
180    #[test]
181    fn error_is_send_sync_and_static() {
182        // A `'static + Send + Sync` error composes into any host's error type.
183        fn assert_bounds<T: Send + Sync + 'static>(_: &T) {}
184        assert_bounds(&ShapeError::DegenerateUnitsPerEm);
185        // And it is Clone, so a host can keep a copy for its diagnostics.
186        let e = ShapeError::DegenerateUnitsPerEm;
187        assert_eq!(e.clone(), e);
188    }
189}