hayro_interpret/
util.rs

1//! A number of utility methods.
2
3use hayro_syntax::page::{Page, Rotation};
4use kurbo::{Affine, Rect};
5use log::warn;
6use siphasher::sip128::{Hasher128, SipHasher13};
7use std::hash::Hash;
8use std::ops::Sub;
9
10pub(crate) trait OptionLog {
11    fn warn_none(self, f: &str) -> Self;
12}
13
14impl<T> OptionLog for Option<T> {
15    #[inline]
16    fn warn_none(self, f: &str) -> Self {
17        self.or_else(|| {
18            warn!("{f}");
19
20            None
21        })
22    }
23}
24
25const SCALAR_NEARLY_ZERO: f32 = 1.0 / (1 << 8) as f32;
26
27/// A number of useful methods for f32 numbers.
28pub trait Float32Ext: Sized + Sub<f32, Output = f32> + Copy + PartialOrd<f32> {
29    /// Whether the number is approximately 0.
30    fn is_nearly_zero(&self) -> bool {
31        self.is_nearly_zero_within_tolerance(SCALAR_NEARLY_ZERO)
32    }
33
34    /// Whether the number is nearly equal to another number.
35    fn is_nearly_equal(&self, other: f32) -> bool {
36        (*self - other).is_nearly_zero()
37    }
38
39    /// Whether the number is nearly equal to another number.
40    fn is_nearly_less_or_equal(&self, other: f32) -> bool {
41        (*self - other).is_nearly_zero() || *self < other
42    }
43
44    /// Whether the number is nearly equal to another number.
45    fn is_nearly_greater_or_equal(&self, other: f32) -> bool {
46        (*self - other).is_nearly_zero() || *self > other
47    }
48
49    /// Whether the number is approximately 0, with a given tolerance.
50    fn is_nearly_zero_within_tolerance(&self, tolerance: f32) -> bool;
51}
52
53impl Float32Ext for f32 {
54    fn is_nearly_zero_within_tolerance(&self, tolerance: f32) -> bool {
55        debug_assert!(tolerance >= 0.0, "tolerance must be non-negative");
56
57        self.abs() <= tolerance
58    }
59}
60
61/// A number of useful methods for f64 numbers.
62pub trait Float64Ext: Sized + Sub<f64, Output = f64> + Copy + PartialOrd<f64> {
63    /// Whether the number is approximately 0.
64    fn is_nearly_zero(&self) -> bool {
65        self.is_nearly_zero_within_tolerance(SCALAR_NEARLY_ZERO as f64)
66    }
67
68    /// Whether the number is nearly equal to another number.
69    fn is_nearly_equal(&self, other: f64) -> bool {
70        (*self - other).is_nearly_zero()
71    }
72
73    /// Whether the number is nearly equal to another number.
74    fn is_nearly_less_or_equal(&self, other: f64) -> bool {
75        (*self - other).is_nearly_zero() || *self < other
76    }
77
78    /// Whether the number is nearly equal to another number.
79    fn is_nearly_greater_or_equal(&self, other: f64) -> bool {
80        (*self - other).is_nearly_zero() || *self > other
81    }
82
83    /// Whether the number is approximately 0, with a given tolerance.
84    fn is_nearly_zero_within_tolerance(&self, tolerance: f64) -> bool;
85}
86
87impl Float64Ext for f64 {
88    fn is_nearly_zero_within_tolerance(&self, tolerance: f64) -> bool {
89        debug_assert!(tolerance >= 0.0, "tolerance must be non-negative");
90
91        self.abs() <= tolerance
92    }
93}
94
95pub(crate) trait PointExt: Sized {
96    fn x(&self) -> f32;
97    fn y(&self) -> f32;
98
99    fn nearly_same(&self, other: Self) -> bool {
100        self.x().is_nearly_equal(other.x()) && self.y().is_nearly_equal(other.y())
101    }
102}
103
104impl PointExt for kurbo::Point {
105    fn x(&self) -> f32 {
106        self.x as f32
107    }
108
109    fn y(&self) -> f32 {
110        self.y as f32
111    }
112}
113
114/// Calculate a 128-bit siphash of a value.
115pub(crate) fn hash128<T: Hash + ?Sized>(value: &T) -> u128 {
116    let mut state = SipHasher13::new();
117    value.hash(&mut state);
118    state.finish128().as_u128()
119}
120
121/// Extension methods for rectangles.
122pub trait RectExt {
123    /// Convert the rectangle to a `kurbo` rectangle.
124    fn to_kurbo(&self) -> Rect;
125}
126
127impl RectExt for hayro_syntax::object::Rect {
128    fn to_kurbo(&self) -> Rect {
129        Rect::new(self.x0, self.y0, self.x1, self.y1)
130    }
131}
132
133// Note: Keep in sync with `hayro-write`.
134/// Extension methods for PDF pages.
135pub trait PageExt {
136    /// Return the initial transform that should be applied when rendering. This accounts for a
137    /// number of factors, such as the mismatch between PDF's y-up and most renderers' y-down
138    /// coordinate system, the rotation of the page and the offset of the crop box.
139    fn initial_transform(&self, invert_y: bool) -> Affine;
140}
141
142impl PageExt for Page<'_> {
143    fn initial_transform(&self, invert_y: bool) -> Affine {
144        let crop_box = self.intersected_crop_box();
145        let (_, base_height) = self.base_dimensions();
146        let (width, height) = self.render_dimensions();
147
148        let horizontal_t =
149            Affine::rotate(90.0_f64.to_radians()) * Affine::translate((0.0, -width as f64));
150        let flipped_horizontal_t =
151            Affine::translate((0.0, height as f64)) * Affine::rotate(-90.0_f64.to_radians());
152
153        let rotation_transform = match self.rotation() {
154            Rotation::None => Affine::IDENTITY,
155            Rotation::Horizontal => {
156                if invert_y {
157                    horizontal_t
158                } else {
159                    flipped_horizontal_t
160                }
161            }
162            Rotation::Flipped => {
163                Affine::scale(-1.0) * Affine::translate((-width as f64, -height as f64))
164            }
165            Rotation::FlippedHorizontal => {
166                if invert_y {
167                    flipped_horizontal_t
168                } else {
169                    horizontal_t
170                }
171            }
172        };
173
174        let inversion_transform = if invert_y {
175            Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, base_height as f64])
176        } else {
177            Affine::IDENTITY
178        };
179
180        rotation_transform * inversion_transform * Affine::translate((-crop_box.x0, -crop_box.y0))
181    }
182}