write_fonts/
util.rs

1//! Misc utility functions
2
3/// Iterator that iterates over a vector of iterators simultaneously.
4///
5/// Adapted from <https://stackoverflow.com/a/55292215>
6pub struct MultiZip<I: Iterator>(Vec<I>);
7
8impl<I: Iterator> MultiZip<I> {
9    /// Create a new MultiZip from a vector of iterators
10    pub fn new(vec_of_iters: Vec<I>) -> Self {
11        Self(vec_of_iters)
12    }
13}
14
15impl<I: Iterator> Iterator for MultiZip<I> {
16    type Item = Vec<I::Item>;
17
18    fn next(&mut self) -> Option<Self::Item> {
19        self.0.iter_mut().map(Iterator::next).collect()
20    }
21}
22
23/// Read next or previous, wrapping if we go out of bounds.
24///
25/// This is particularly useful when porting from Python where reading
26/// idx - 1, with -1 meaning last, is common.
27pub trait WrappingGet<T> {
28    fn wrapping_next(&self, idx: usize) -> &T;
29    fn wrapping_prev(&self, idx: usize) -> &T;
30}
31
32impl<T> WrappingGet<T> for &[T] {
33    fn wrapping_next(&self, idx: usize) -> &T {
34        &self[match idx {
35            _ if idx == self.len() - 1 => 0,
36            _ => idx + 1,
37        }]
38    }
39
40    fn wrapping_prev(&self, idx: usize) -> &T {
41        &self[match idx {
42            _ if idx == 0 => self.len() - 1,
43            _ => idx - 1,
44        }]
45    }
46}
47
48/// Compare two floats for equality using relative and absolute tolerances.
49///
50/// This is useful when porting from Python where `math.isclose` is common.
51///
52/// References:
53/// - [PEP425](https://peps.python.org/pep-0485/)
54/// - [math.isclose](https://docs.python.org/3/library/math.html#math.isclose)
55#[derive(Clone, Copy, Debug)]
56pub struct FloatComparator {
57    // TODO: Make it generic over T: Float? Need to add num-traits as a dependency
58    rel_tol: f64,
59    abs_tol: f64,
60}
61
62impl FloatComparator {
63    /// Create a new FloatComparator with the specified relative and absolute tolerances.
64    pub fn new(rel_tol: f64, abs_tol: f64) -> Self {
65        Self { rel_tol, abs_tol }
66    }
67
68    #[inline]
69    /// Return true if a and b are close according to the specified tolerances.
70    pub fn isclose(self, a: f64, b: f64) -> bool {
71        if a == b {
72            return true;
73        }
74        if !a.is_finite() || !b.is_finite() {
75            return false;
76        }
77        // The https://peps.python.org/pep-0485/ describes the algorithm used as:
78        //   abs(a-b) <= max( rel_tol * max(abs(a), abs(b)), abs_tol )
79        // In Rust, that would literally be:
80        //   diff <= f64::max(self.rel_tol * f64::max(f64::abs(a), f64::abs(b)), self.abs_tol)
81        // However below I use || instead of max(), since the logic works out the same and
82        // should be a bit faster. In the PEP it's referred to as Boost's 'weak' formulation.
83        let diff = (a - b).abs();
84        diff <= (self.rel_tol * b).abs() || diff <= (self.rel_tol * a).abs() || diff <= self.abs_tol
85    }
86}
87
88impl Default for FloatComparator {
89    /// Create a new FloatComparator with `rel_to=1e-9` and `abs_tol=0.0`.
90    fn default() -> Self {
91        // same defaults as Python's math.isclose so we can match fontTools
92        Self::new(1e-9, 0.0)
93    }
94}
95
96/// Compare two floats for equality using the default FloatComparator.
97///
98/// To use different relative or absolute tolerances, create a FloatComparator
99/// and use its `isclose` method.
100pub fn isclose(a: f64, b: f64) -> bool {
101    FloatComparator::default().isclose(a, b)
102}
103
104/// Search range values used in various tables
105#[derive(Clone, Copy, Debug)]
106pub struct SearchRange {
107    pub search_range: u16,
108    pub entry_selector: u16,
109    pub range_shift: u16,
110}
111
112impl SearchRange {
113    //https://github.com/fonttools/fonttools/blob/729b3d2960ef/Lib/fontTools/ttLib/ttFont.py#L1147
114    /// calculate searchRange, entrySelector, and rangeShift
115    ///
116    /// these values are used in various places, such as [the base table directory]
117    /// and [cmap format 4].
118    ///
119    /// [the base table directory]: https://learn.microsoft.com/en-us/typography/opentype/spec/otff#table-directory
120    /// [cmap format 4]: https://learn.microsoft.com/en-us/typography/opentype/spec/cmap#format-4-segment-mapping-to-delta-values
121    pub fn compute(n_items: usize, item_size: usize) -> Self {
122        let entry_selector = (n_items as f64).log2().floor() as usize;
123        let search_range = (2.0_f64.powi(entry_selector as i32) * item_size as f64) as usize;
124        // The result doesn't really make sense with 0 tables but ... let's at least not fail
125        let range_shift = (n_items * item_size).saturating_sub(search_range);
126        SearchRange {
127            search_range: search_range.try_into().unwrap(),
128            entry_selector: entry_selector.try_into().unwrap(),
129            range_shift: range_shift.try_into().unwrap(),
130        }
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    /// based on example at
139    /// <https://learn.microsoft.com/en-us/typography/opentype/spec/cmap#format-4-segment-mapping-to-delta-values>
140    #[test]
141    fn simple_search_range() {
142        let SearchRange {
143            search_range,
144            entry_selector,
145            range_shift,
146        } = SearchRange::compute(39, 2);
147        assert_eq!((search_range, entry_selector, range_shift), (64, 5, 14));
148    }
149
150    #[test]
151    fn search_range_no_crashy() {
152        let foo = SearchRange::compute(0, 0);
153        assert_eq!(
154            (foo.search_range, foo.entry_selector, foo.range_shift),
155            (0, 0, 0)
156        )
157    }
158}