diff options
author | Federico Mena Quintero <federico@gnome.org> | 2023-02-14 18:47:04 -0600 |
---|---|---|
committer | Federico Mena Quintero <federico@gnome.org> | 2023-02-14 19:09:24 -0600 |
commit | a1a4be2a38cd3178274a76d452a67dd15e269a38 (patch) | |
tree | d16686ba628f5f7c9a6b97bbf47a8d8045d26b71 | |
parent | 688d8b3f02d93a9ce95a0039cd5854c13c9dc998 (diff) | |
download | librsvg-a1a4be2a38cd3178274a76d452a67dd15e269a38.tar.gz |
Newtype PangoUnits(i32): used to check for overflow when converting to i32 pango units
Part-of: <https://gitlab.gnome.org/GNOME/librsvg/-/merge_requests/796>
-rw-r--r-- | src/text.rs | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/src/text.rs b/src/text.rs index a02b5077..3ca8ec9f 100644 --- a/src/text.rs +++ b/src/text.rs @@ -340,6 +340,21 @@ impl Span { } } +/// Use as `PangoUnits::from_pixels()` so that we can check for overflow. +struct PangoUnits(i32); + +impl PangoUnits { + fn from_pixels(v: f64) -> Option<Self> { + // We want (v * f64::from(pango::SCALE) + 0.5) as i32 + // + // But check for overflow. + + cast::i32(v * f64::from(pango::SCALE) + 0.5) + .ok() + .map(PangoUnits) + } +} + impl MeasuredSpan { fn from_span(layout_context: &LayoutContext, span: &Span) -> MeasuredSpan { let values = span.values.clone(); @@ -1410,4 +1425,14 @@ mod tests { (0.0, -4.0) ); } + + #[test] + fn pango_units_works() { + assert_eq!(PangoUnits::from_pixels(10.0).unwrap().0, pango::SCALE * 10); + } + + #[test] + fn pango_units_detects_overflow() { + assert!(PangoUnits::from_pixels(1e7).is_none()); + } } |