use alloc::format;
use alloc::string::String;
use core::fmt;
#[derive(Debug, Clone, PartialEq)]
pub enum ShapeError {
SingularAffine {
determinant: f32,
},
UnbalancedPop {
depth: usize,
},
InvalidSize {
width: u32,
height: u32,
},
InvalidScale {
scale: f32,
},
UnknownGlyph {
glyph: u32,
glyph_count: usize,
},
NonFiniteCoordinate {
axis: &'static str,
},
RasterTooLarge {
pixels: usize,
limit: usize,
},
DegenerateUnitsPerEm,
}
impl fmt::Display for ShapeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ShapeError::SingularAffine { determinant } => write!(
f,
"affine transform is singular (determinant {determinant})"
),
ShapeError::UnbalancedPop { depth } => {
write!(f, "transform stack popped at depth {depth} (already empty)")
}
ShapeError::InvalidSize { width, height } => {
write!(f, "invalid raster size {width}x{height}")
}
ShapeError::InvalidScale { scale } => write!(f, "invalid scale {scale}"),
ShapeError::UnknownGlyph { glyph, glyph_count } => write!(
f,
"glyph {} requested but the font holds only {glyph_count}",
glyph
),
ShapeError::NonFiniteCoordinate { axis } => {
write!(f, "{axis} coordinate is not finite")
}
ShapeError::RasterTooLarge { pixels, limit } => {
write!(f, "raster of {pixels} pixels exceeds the {limit}-pixel cap")
}
ShapeError::DegenerateUnitsPerEm => write!(f, "font has unitsPerEm == 0"),
}
}
}
impl From<crate::affine::Affine2D> for ShapeError {
fn from(_t: crate::affine::Affine2D) -> Self {
ShapeError::SingularAffine { determinant: 0.0 }
}
}
impl From<core::num::ParseFloatError> for ShapeError {
fn from(_e: core::num::ParseFloatError) -> Self {
ShapeError::InvalidScale { scale: f32::NAN }
}
}
pub type Result<T> = core::result::Result<T, ShapeError>;
#[must_use]
pub fn message(e: &ShapeError) -> String {
format!("{e}")
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::float_cmp
)]
use super::message;
use crate::ShapeError;
use alloc::string::ToString;
#[test]
fn every_variant_renders_informatively() {
let cases = [
(ShapeError::SingularAffine { determinant: 0.0 }, "singular"),
(ShapeError::UnbalancedPop { depth: 0 }, "popped"),
(
ShapeError::InvalidSize {
width: 0,
height: 16,
},
"0x16",
),
(ShapeError::InvalidScale { scale: -1.0 }, "-1"),
(
ShapeError::UnknownGlyph {
glyph: 9,
glyph_count: 2,
},
"glyph 9",
),
(
ShapeError::NonFiniteCoordinate { axis: "y" },
"y coordinate",
),
(
ShapeError::RasterTooLarge {
pixels: 1_000_000,
limit: 16_777_216,
},
"1000000",
),
(ShapeError::DegenerateUnitsPerEm, "unitsPerEm == 0"),
];
for (e, needle) in cases {
let s = e.to_string();
assert!(!s.is_empty());
assert!(s.contains(needle), "{s:?} should mention {needle:?}");
assert_eq!(message(&e), s);
}
}
#[test]
fn error_is_send_sync_and_static() {
fn assert_bounds<T: Send + Sync + 'static>(_: &T) {}
assert_bounds(&ShapeError::DegenerateUnitsPerEm);
let e = ShapeError::DegenerateUnitsPerEm;
assert_eq!(e.clone(), e);
}
}