Skip to main content

font_types/
fixed.rs

1//! fixed-point numerical types
2
3use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
4
5// shared between Fixed, F26Dot6, F2Dot14, F4Dot12, F6Dot10
6macro_rules! fixed_impl {
7    ($name:ident, $bits:literal, $fract_bits:literal, $ty:ty) => {
8        #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
9        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
10        #[cfg_attr(feature = "bytemuck", derive(bytemuck::AnyBitPattern, bytemuck::NoUninit))]
11        #[repr(transparent)]
12        #[doc = concat!(stringify!($bits), "-bit signed fixed point number with ", stringify!($fract_bits), " bits of fraction." )]
13        pub struct $name($ty);
14        impl $name {
15            /// Minimum value.
16            pub const MIN: Self = Self(<$ty>::MIN);
17
18            /// Maximum value.
19            pub const MAX: Self = Self(<$ty>::MAX);
20
21            /// This type's smallest representable value
22            pub const EPSILON: Self = Self(1);
23
24            /// Representation of 0.0.
25            pub const ZERO: Self = Self(0);
26
27            /// Representation of 1.0.
28            pub const ONE: Self = Self(1 << $fract_bits);
29
30            /// Representation of -1.0.
31            pub const NEG_ONE: Self = Self((!0 << $fract_bits) as $ty);
32
33            const INT_MASK: $ty = !0 << $fract_bits;
34            const ROUND: $ty = 1 << ($fract_bits - 1);
35            const FRACT_BITS: usize = $fract_bits;
36
37            /// Creates a new fixed point value from the underlying bit representation.
38            #[inline(always)]
39            pub const fn from_bits(bits: $ty) -> Self {
40                Self(bits)
41            }
42
43            /// Returns the underlying bit representation of the value.
44            #[inline(always)]
45            pub const fn to_bits(self) -> $ty {
46                self.0
47            }
48
49            //TODO: is this actually useful?
50            /// Returns the nearest integer value.
51            #[inline(always)]
52            pub const fn round(self) -> Self {
53                Self(self.0.wrapping_add(Self::ROUND) & Self::INT_MASK)
54            }
55
56            /// Returns the absolute value of the number.
57            #[inline(always)]
58            pub const fn abs(self) -> Self {
59                Self(self.0.abs())
60            }
61
62            /// Returns the largest integer less than or equal to the number.
63            #[inline(always)]
64            pub const fn floor(self) -> Self {
65                Self(self.0 & Self::INT_MASK)
66            }
67
68            /// Returns the fractional part of the number.
69            #[inline(always)]
70            pub const fn fract(self) -> Self {
71                Self(self.0 - self.floor().0)
72            }
73
74            /// Wrapping addition.
75            #[inline(always)]
76            pub fn wrapping_add(self, other: Self) -> Self {
77                Self(self.0.wrapping_add(other.0))
78            }
79
80            /// Saturating addition.
81            #[inline(always)]
82            pub const fn saturating_add(self, other: Self) -> Self {
83                Self(self.0.saturating_add(other.0))
84            }
85
86            /// Checked addition.
87            #[inline(always)]
88            pub fn checked_add(self, other: Self) -> Option<Self> {
89                self.0.checked_add(other.0).map(|inner| Self(inner))
90            }
91
92            /// Wrapping substitution.
93            #[inline(always)]
94            pub const fn wrapping_sub(self, other: Self) -> Self {
95                Self(self.0.wrapping_sub(other.0))
96            }
97
98            /// Saturating substitution.
99            #[inline(always)]
100            pub const fn saturating_sub(self, other: Self) -> Self {
101                Self(self.0.saturating_sub(other.0))
102            }
103
104            /// The representation of this number as a big-endian byte array.
105            #[inline(always)]
106            pub const fn to_be_bytes(self) -> [u8; $bits / 8] {
107                self.0.to_be_bytes()
108            }
109        }
110
111        impl Add for $name {
112            type Output = Self;
113            #[inline(always)]
114            fn add(self, other: Self) -> Self {
115                Self(self.0.wrapping_add(other.0))
116            }
117        }
118
119        impl AddAssign for $name {
120            #[inline(always)]
121            fn add_assign(&mut self, other: Self) {
122                *self = *self + other;
123            }
124        }
125
126        impl Sub for $name {
127            type Output = Self;
128            #[inline(always)]
129            fn sub(self, other: Self) -> Self {
130                Self(self.0.wrapping_sub(other.0))
131            }
132        }
133
134        impl SubAssign for $name {
135            #[inline(always)]
136            fn sub_assign(&mut self, other: Self) {
137                *self = *self - other;
138            }
139        }
140    };
141}
142
143/// Implements multiplication and division operators for fixed types.
144macro_rules! fixed_mul_div {
145    ($ty:ty) => {
146        impl $ty {
147            /// Multiplies `self` by `a` and divides the product by `b`.
148            // This one is specifically not always inlined due to size and
149            // frequency of use. We leave it to compiler discretion.
150            #[inline]
151            pub const fn mul_div(&self, a: Self, b: Self) -> Self {
152                let mut sign = 1;
153                let mut su = self.0 as u64;
154                let mut au = a.0 as u64;
155                let mut bu = b.0 as u64;
156                if self.0 < 0 {
157                    su = 0u64.wrapping_sub(su);
158                    sign = -1;
159                }
160                if a.0 < 0 {
161                    au = 0u64.wrapping_sub(au);
162                    sign = -sign;
163                }
164                if b.0 < 0 {
165                    bu = 0u64.wrapping_sub(bu);
166                    sign = -sign;
167                }
168                let result = if bu > 0 {
169                    su.wrapping_mul(au).wrapping_add(bu >> 1) / bu
170                } else {
171                    0x7FFFFFFF
172                };
173                Self(if sign < 0 {
174                    (result as i32).wrapping_neg()
175                } else {
176                    result as i32
177                })
178            }
179        }
180
181        impl Mul for $ty {
182            type Output = Self;
183            #[inline(always)]
184            fn mul(self, other: Self) -> Self::Output {
185                let ab = self.0 as i64 * other.0 as i64;
186                Self(((ab + 0x8000 - i64::from(ab < 0)) >> 16) as i32)
187            }
188        }
189
190        impl MulAssign for $ty {
191            #[inline(always)]
192            fn mul_assign(&mut self, rhs: Self) {
193                *self = *self * rhs;
194            }
195        }
196
197        impl Div for $ty {
198            type Output = Self;
199            fn div(self, other: Self) -> Self {
200                let sign = (self.0 < 0) ^ (other.0 < 0);
201                let au = self.0.unsigned_abs() as u64;
202                let bu = other.0.unsigned_abs() as u64;
203                let q = if bu == 0 {
204                    0x7FFFFFFF_u32
205                } else {
206                    (((au << 16) + (bu >> 1)) / bu) as u32
207                };
208                Self(if sign {
209                    (q as i32).wrapping_neg()
210                } else {
211                    q as i32
212                })
213            }
214        }
215
216        impl DivAssign for $ty {
217            #[inline(always)]
218            fn div_assign(&mut self, rhs: Self) {
219                *self = *self / rhs;
220            }
221        }
222
223        impl Neg for $ty {
224            type Output = Self;
225            #[inline(always)]
226            fn neg(self) -> Self {
227                Self(-self.0)
228            }
229        }
230    };
231}
232
233/// impl float conversion methods.
234///
235/// We convert to different float types in order to ensure we can roundtrip
236/// without floating point error.
237macro_rules! float_conv {
238    ($name:ident, $to:ident, $from:ident, $ty:ty) => {
239        impl $name {
240            #[doc = concat!("Creates a fixed point value from a", stringify!($ty), ".")]
241            ///
242            /// This operation is lossy; the float will be rounded to the nearest
243            /// representable value.
244            #[inline(always)]
245            pub fn $from(x: $ty) -> Self {
246                // When x is positive: 1.0 - 0.5 =  0.5
247                // When x is negative: 0.0 - 0.5 = -0.5
248                let frac = (x.is_sign_positive() as u8 as $ty) - 0.5;
249                Self((x * Self::ONE.0 as $ty + frac) as _)
250            }
251
252            #[doc = concat!("Returns the value as an ", stringify!($ty), ".")]
253            ///
254            /// This operation is lossless: all representable values can be
255            /// round-tripped.
256            #[inline(always)]
257            pub fn $to(self) -> $ty {
258                let int = ((self.0 & Self::INT_MASK) >> Self::FRACT_BITS) as $ty;
259                let fract = (self.0 & !Self::INT_MASK) as $ty / Self::ONE.0 as $ty;
260                int + fract
261            }
262        }
263
264        //hack: we can losslessly go to float, so use those fmt impls
265        impl std::fmt::Display for $name {
266            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
267                self.$to().fmt(f)
268            }
269        }
270
271        impl std::fmt::Debug for $name {
272            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
273                self.$to().fmt(f)
274            }
275        }
276    };
277}
278
279fixed_impl!(F2Dot14, 16, 14, i16);
280fixed_impl!(F4Dot12, 16, 12, i16);
281fixed_impl!(F6Dot10, 16, 10, i16);
282fixed_impl!(Fixed, 32, 16, i32);
283fixed_impl!(F26Dot6, 32, 6, i32);
284fixed_mul_div!(Fixed);
285fixed_mul_div!(F26Dot6);
286float_conv!(F2Dot14, to_f32, from_f32, f32);
287float_conv!(F4Dot12, to_f32, from_f32, f32);
288float_conv!(F6Dot10, to_f32, from_f32, f32);
289float_conv!(Fixed, to_f64, from_f64, f64);
290float_conv!(F26Dot6, to_f64, from_f64, f64);
291crate::newtype_scalar!(F2Dot14, [u8; 2]);
292crate::newtype_scalar!(F4Dot12, [u8; 2]);
293crate::newtype_scalar!(F6Dot10, [u8; 2]);
294crate::newtype_scalar!(Fixed, [u8; 4]);
295
296impl Fixed {
297    /// Creates a 16.16 fixed point value from a 32 bit integer.
298    #[inline(always)]
299    pub const fn from_i32(i: i32) -> Self {
300        Self(i << 16)
301    }
302
303    /// Converts a 16.16 fixed point value to a 32 bit integer, rounding off
304    /// the fractional bits.
305    #[inline(always)]
306    pub const fn to_i32(self) -> i32 {
307        self.0.wrapping_add(0x8000) >> 16
308    }
309
310    /// Converts a 16.16 to 26.6 fixed point value.
311    #[inline(always)]
312    pub const fn to_f26dot6(self) -> F26Dot6 {
313        F26Dot6(self.0.wrapping_add(0x200) >> 10)
314    }
315
316    /// Converts a 16.16 to 2.14 fixed point value.
317    ///
318    /// This specific conversion is defined by the spec:
319    /// <https://learn.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>
320    ///
321    /// "5. Convert the final, normalized 16.16 coordinate value to 2.14 by this method: add 0x00000002,
322    /// and sign-extend shift to the right by 2."
323    #[inline(always)]
324    pub const fn to_f2dot14(self) -> F2Dot14 {
325        F2Dot14((self.0.wrapping_add(2) >> 2) as _)
326    }
327
328    /// Converts a 16.16 fixed point value to a single precision floating
329    /// point value.
330    ///
331    /// This operation is lossy. Use `to_f64()` for a lossless conversion.
332    #[inline(always)]
333    pub fn to_f32(self) -> f32 {
334        const SCALE_FACTOR: f32 = 1.0 / 65536.0;
335        self.0 as f32 * SCALE_FACTOR
336    }
337}
338
339impl From<i32> for Fixed {
340    fn from(value: i32) -> Self {
341        Self::from_i32(value)
342    }
343}
344
345impl F26Dot6 {
346    /// Creates a 26.6 fixed point value from a 32 bit integer.
347    #[inline(always)]
348    pub const fn from_i32(i: i32) -> Self {
349        Self(i << 6)
350    }
351
352    /// Converts a 26.6 fixed point value to a 32 bit integer, rounding off
353    /// the fractional bits.
354    #[inline(always)]
355    pub const fn to_i32(self) -> i32 {
356        self.0.wrapping_add(32) >> 6
357    }
358
359    /// Converts a 26.6 fixed point value to a single precision floating
360    /// point value.
361    ///
362    /// This operation is lossy. Use `to_f64()` for a lossless conversion.
363    #[inline(always)]
364    pub fn to_f32(self) -> f32 {
365        const SCALE_FACTOR: f32 = 1.0 / 64.0;
366        self.0 as f32 * SCALE_FACTOR
367    }
368}
369
370impl F2Dot14 {
371    /// Converts a 2.14 to 16.16 fixed point value.
372    #[inline(always)]
373    pub const fn to_fixed(self) -> Fixed {
374        Fixed(self.0 as i32 * 4)
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    #![allow(overflowing_literals)] // we want to specify byte values directly
381    use super::*;
382
383    #[test]
384    fn f2dot14_floats() {
385        // Examples from https://docs.microsoft.com/en-us/typography/opentype/spec/otff#data-types
386        assert_eq!(F2Dot14(0x7fff), F2Dot14::from_f32(1.999939));
387        assert_eq!(F2Dot14(0x7000), F2Dot14::from_f32(1.75));
388        assert_eq!(F2Dot14(0x0001), F2Dot14::from_f32(0.0000610356));
389        assert_eq!(F2Dot14(0x0000), F2Dot14::from_f32(0.0));
390        assert_eq!(F2Dot14(0xffff), F2Dot14::from_f32(-0.000061));
391        assert_eq!(F2Dot14(0x8000), F2Dot14::from_f32(-2.0));
392    }
393
394    #[test]
395    fn roundtrip_f2dot14() {
396        for i in i16::MIN..=i16::MAX {
397            let val = F2Dot14(i);
398            assert_eq!(val, F2Dot14::from_f32(val.to_f32()));
399        }
400    }
401
402    #[test]
403    fn round_f2dot14() {
404        assert_eq!(F2Dot14(0x7000).round(), F2Dot14::from_f32(-2.0));
405        assert_eq!(F2Dot14(0x1F00).round(), F2Dot14::from_f32(0.0));
406        assert_eq!(F2Dot14(0x2000).round(), F2Dot14::from_f32(1.0));
407    }
408
409    #[test]
410    fn round_fixed() {
411        //TODO: make good test cases
412        assert_eq!(Fixed(0x0001_7FFE).round(), Fixed(0x0001_0000));
413        assert_eq!(Fixed(0x0001_7FFF).round(), Fixed(0x0001_0000));
414        assert_eq!(Fixed(0x0001_8000).round(), Fixed(0x0002_0000));
415    }
416
417    // disabled because it's slow; these were just for my edification anyway
418    //#[test]
419    //fn roundtrip_fixed() {
420    //for i in i32::MIN..=i32::MAX {
421    //let val = Fixed(i);
422    //assert_eq!(val, Fixed::from_f64(val.to_f64()));
423    //}
424    //}
425
426    #[test]
427    fn fixed_floats() {
428        assert_eq!(Fixed(0x7fff_0000), Fixed::from_f64(32767.));
429        assert_eq!(Fixed(0x7000_0001), Fixed::from_f64(28672.00001525879));
430        assert_eq!(Fixed(0x0001_0000), Fixed::from_f64(1.0));
431        assert_eq!(Fixed(0x0000_0000), Fixed::from_f64(0.0));
432        assert_eq!(
433            Fixed(i32::from_be_bytes([0xff; 4])),
434            Fixed::from_f64(-0.000015259)
435        );
436        assert_eq!(Fixed(0x7fff_ffff), Fixed::from_f64(32768.0));
437    }
438
439    // We lost the f64::round() intrinsic when dropping std and the
440    // alternative implementation was very slightly incorrect, throwing
441    // off some tests. This makes sure we match.
442    #[test]
443    fn fixed_floats_rounding() {
444        fn with_round_intrinsic(x: f64) -> Fixed {
445            Fixed((x * 65536.0).round() as i32)
446        }
447        // These particular values were tripping up tests
448        let inputs = [0.05, 0.6, 0.2, 0.4, 0.67755];
449        for input in inputs {
450            assert_eq!(Fixed::from_f64(input), with_round_intrinsic(input));
451            // Test negated values as well for good measure
452            assert_eq!(Fixed::from_f64(-input), with_round_intrinsic(-input));
453        }
454    }
455
456    #[test]
457    fn fixed_to_int() {
458        assert_eq!(Fixed::from_f64(1.0).to_i32(), 1);
459        assert_eq!(Fixed::from_f64(1.5).to_i32(), 2);
460        assert_eq!(F26Dot6::from_f64(1.0).to_i32(), 1);
461        assert_eq!(F26Dot6::from_f64(1.5).to_i32(), 2);
462    }
463
464    #[test]
465    fn fixed_from_int() {
466        assert_eq!(Fixed::from_i32(1000).to_bits(), 1000 << 16);
467        assert_eq!(F26Dot6::from_i32(1000).to_bits(), 1000 << 6);
468    }
469
470    #[test]
471    fn fixed_to_f26dot6() {
472        assert_eq!(Fixed::from_f64(42.5).to_f26dot6(), F26Dot6::from_f64(42.5));
473    }
474
475    #[test]
476    fn fixed_muldiv() {
477        assert_eq!(
478            Fixed::from_f64(0.5) * Fixed::from_f64(2.0),
479            Fixed::from_f64(1.0)
480        );
481        assert_eq!(
482            Fixed::from_f64(0.5) / Fixed::from_f64(2.0),
483            Fixed::from_f64(0.25)
484        );
485    }
486
487    // OSS Fuzz caught panic with overflow in fixed point division.
488    // See <https://oss-fuzz.com/testcase-detail/5666843647082496> and
489    // <https://issues.oss-fuzz.com/issues/443104630>
490    #[test]
491    fn fixed_div_neg_overflow() {
492        let a = Fixed::from_f64(-92.5);
493        let b = Fixed::from_f64(0.0028228759765625);
494        // Just don't panic with overflow
495        let _ = a / b;
496    }
497
498    #[test]
499    fn fixed_mul_div_neg_overflow() {
500        let a = Fixed::from_f64(-92.5);
501        let b = Fixed::from_f64(0.0028228759765625);
502        // Just don't panic with overflow
503        let _ = a.mul_div(Fixed::ONE, b);
504    }
505
506    #[test]
507    fn fixed_div_min_value() {
508        // i32::MIN.abs() overflows i32, unsigned_abs() handles this correctly
509        let min = Fixed(i32::MIN);
510        let one = Fixed::ONE;
511        // Just don't panic with overflow
512        let _ = min / one;
513        // Dividing by -1 is also an edge case
514        let neg_one = Fixed(-Fixed::ONE.0);
515        let _ = min / neg_one;
516    }
517}