Skip to main content

wl_client/
fixed.rs

1use std::fmt::Debug;
2use std::fmt::Display;
3use std::fmt::Formatter;
4use std::ops::Add;
5use std::ops::AddAssign;
6use std::ops::BitAnd;
7use std::ops::BitAndAssign;
8use std::ops::BitOr;
9use std::ops::BitOrAssign;
10use std::ops::BitXor;
11use std::ops::BitXorAssign;
12use std::ops::Div;
13use std::ops::DivAssign;
14use std::ops::Mul;
15use std::ops::MulAssign;
16use std::ops::Neg;
17use std::ops::Not;
18use std::ops::Rem;
19use std::ops::RemAssign;
20use std::ops::Shl;
21use std::ops::ShlAssign;
22use std::ops::Shr;
23use std::ops::ShrAssign;
24use std::ops::Sub;
25use std::ops::SubAssign;
26
27#[cfg(test)]
28mod tests;
29
30/// A signed 24.8 fixed-point number used in the wayland protocol.
31///
32/// This is a signed decimal type which offers a sign bit, 23 bits of integer precision and 8 bits
33/// of decimal precision.
34///
35/// # Arithmetic operations
36///
37/// This type implements all of the usual arithmetic operations for numbers. On overflow, they
38/// behave like the standard library operations except that multiplication and division always use
39/// wrapping semantics.
40#[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
41#[repr(transparent)]
42pub struct Fixed(i32);
43
44macro_rules! fmul {
45    () => {
46        256.0
47    };
48}
49macro_rules! imul {
50    () => {
51        256
52    };
53}
54macro_rules! shift {
55    () => {
56        8
57    };
58}
59
60impl Fixed {
61    /// The largest [`Fixed`].
62    pub const MAX: Self = Self(i32::MAX);
63
64    /// The smallest [`Fixed`].
65    pub const MIN: Self = Self(i32::MIN);
66
67    /// The 0 [`Fixed`].
68    pub const ZERO: Self = Self(0);
69
70    /// The 1 [`Fixed`].
71    pub const ONE: Self = Self::from_i32_saturating(1);
72
73    /// The 2 [`Fixed`].
74    pub const TWO: Self = Self::from_i32_saturating(2);
75
76    /// The smallest positive [`Fixed`].
77    pub const EPSILON: Self = Self(1);
78
79    /// The largest negative [`Fixed`].
80    pub const NEGATIVE_EPSILON: Self = Self(!0);
81
82    /// Creates a [`Fixed`] from the raw bits that appear in the wire protocol.
83    #[inline]
84    pub const fn from_wire(val: i32) -> Self {
85        Self(val)
86    }
87
88    /// Converts this [`Fixed`] to the bits that should be set in the wire protocol.
89    #[inline]
90    pub const fn to_wire(self) -> i32 {
91        self.0
92    }
93
94    /// Converts this [`Fixed`] to an `f64`.
95    ///
96    /// This conversion is lossless.
97    #[inline]
98    pub const fn to_f64(self) -> f64 {
99        self.0 as f64 / fmul!()
100    }
101
102    /// Converts this [`Fixed`] to an `f32`.
103    ///
104    /// This conversion is lossy if there are more than 24 significant bits in this [`Fixed`].
105    #[inline]
106    pub const fn to_f32_lossy(self) -> f32 {
107        self.to_f64() as f32
108    }
109
110    /// Creates a [`Fixed`] from an `f64`.
111    ///
112    /// If the value cannot be represented exactly, the behavior is as when an `f64` is cast to an
113    /// integer. That is
114    ///
115    /// - Values are rounded towards 0.
116    /// - `NaN` returns [`Fixed::ZERO`].
117    /// - Values larger than the maximum return [`Fixed::MAX`].
118    /// - Values smaller than the minimum return [`Fixed::MIN`].
119    #[inline]
120    pub const fn from_f64_lossy(val: f64) -> Self {
121        Self((val * fmul!()) as i32)
122    }
123
124    /// Creates a [`Fixed`] from an `f32`.
125    ///
126    /// The conversion behavior is the same as for [`Fixed::from_f64_lossy`].
127    #[inline]
128    pub const fn from_f32_lossy(val: f32) -> Self {
129        Self((val as f64 * fmul!()) as i32)
130    }
131
132    /// Creates a [`Fixed`] from an `i32`.
133    ///
134    /// Values outside of the representable range are clamped to [`Fixed::MIN`] and [`Fixed::MAX`].
135    #[inline]
136    pub const fn from_i32_saturating(val: i32) -> Self {
137        Self(val.saturating_mul(imul!()))
138    }
139
140    /// Creates a [`Fixed`] from an `i64`.
141    ///
142    /// Values outside of the representable range are clamped to [`Fixed::MIN`] and [`Fixed::MAX`].
143    #[inline]
144    pub const fn from_i64_saturating(val: i64) -> Self {
145        let val = val.saturating_mul(imul!());
146        if val > i32::MAX as i64 {
147            Self(i32::MAX)
148        } else if val < i32::MIN as i64 {
149            Self(i32::MIN)
150        } else {
151            Self(val as i32)
152        }
153    }
154
155    /// Converts this [`Fixed`] to an `i32`.
156    ///
157    /// The conversion rounds towards the nearest integer and half-way away from 0.
158    #[inline]
159    pub const fn to_i32_round_towards_nearest(self) -> i32 {
160        if self.0 >= 0 {
161            ((self.0 as i64 + (imul!() / 2)) / imul!()) as i32
162        } else {
163            ((self.0 as i64 - (imul!() / 2)) / imul!()) as i32
164        }
165    }
166
167    /// Converts this [`Fixed`] to an `i32`.
168    ///
169    /// The conversion rounds towards zero.
170    #[inline]
171    pub const fn to_i32_round_towards_zero(self) -> i32 {
172        (self.0 as i64 / imul!()) as i32
173    }
174
175    /// Converts this [`Fixed`] to an `i32`.
176    ///
177    /// The conversion rounds towards minus infinity.
178    #[inline]
179    pub const fn to_i32_floor(self) -> i32 {
180        self.0 >> shift!()
181    }
182
183    /// Converts this [`Fixed`] to an `i32`.
184    ///
185    /// The conversion rounds towards infinity.
186    #[inline]
187    pub const fn to_i32_ceil(self) -> i32 {
188        ((self.0 as i64 + imul!() - 1) >> shift!()) as i32
189    }
190}
191
192macro_rules! from {
193    ($t:ty) => {
194        impl From<$t> for Fixed {
195            #[inline]
196            fn from(value: $t) -> Self {
197                Self(value as i32 * imul!())
198            }
199        }
200    };
201}
202
203from!(i8);
204from!(u8);
205from!(i16);
206from!(u16);
207
208impl From<Fixed> for f64 {
209    #[inline]
210    fn from(value: Fixed) -> Self {
211        value.to_f64()
212    }
213}
214
215impl Debug for Fixed {
216    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
217        Debug::fmt(&self.to_f64(), f)
218    }
219}
220
221impl Display for Fixed {
222    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
223        Display::fmt(&self.to_f64(), f)
224    }
225}
226
227macro_rules! forward_simple_immutable_binop {
228    ($slf:ty, $arg:ty, $big_name:ident, $small_name:ident, $op:tt) => {
229        impl $big_name<$arg> for $slf {
230            type Output = Fixed;
231
232            #[inline]
233            fn $small_name(self, rhs: $arg) -> Self::Output {
234                Fixed(self.0 $op rhs.0)
235            }
236        }
237    };
238}
239
240macro_rules! forward_simple_binop {
241    ($big_name:ident, $small_name:ident, $op:tt, $assign_big_name:ident, $assign_small_name:ident, $assign_op:tt) => {
242        forward_simple_immutable_binop!(Fixed,  Fixed,  $big_name, $small_name, $op);
243        forward_simple_immutable_binop!(Fixed,  &Fixed, $big_name, $small_name, $op);
244        forward_simple_immutable_binop!(&Fixed, Fixed,  $big_name, $small_name, $op);
245        forward_simple_immutable_binop!(&Fixed, &Fixed, $big_name, $small_name, $op);
246
247        impl $assign_big_name for Fixed {
248            #[inline]
249            fn $assign_small_name(&mut self, rhs: Self) {
250                self.0 $assign_op rhs.0;
251            }
252        }
253    };
254}
255
256forward_simple_binop!(Add,    add,    +, AddAssign,    add_assign,    +=);
257forward_simple_binop!(Sub,    sub,    -, SubAssign,    sub_assign,    -=);
258forward_simple_binop!(Rem,    rem,    %, RemAssign,    rem_assign,    %=);
259forward_simple_binop!(BitAnd, bitand, &, BitAndAssign, bitand_assign, &=);
260forward_simple_binop!(BitOr,  bitor,  |, BitOrAssign,  bitor_assign,  |=);
261forward_simple_binop!(BitXor, bitxor, ^, BitXorAssign, bitxor_assign, ^=);
262
263#[inline(always)]
264const fn mul(slf: i32, rhs: i32) -> i32 {
265    (slf as i64 * rhs as i64 / imul!()) as i32
266}
267
268#[inline(always)]
269const fn div(slf: i32, rhs: i32) -> i32 {
270    (slf as i64 * imul!() / rhs as i64) as i32
271}
272
273macro_rules! forward_complex_immutable_binop {
274    ($slf:ty, $arg:ty, $big_name:ident, $small_name:ident) => {
275        impl $big_name<$arg> for $slf {
276            type Output = Fixed;
277
278            #[inline]
279            fn $small_name(self, rhs: $arg) -> Self::Output {
280                Fixed($small_name(self.0, rhs.0))
281            }
282        }
283    };
284}
285
286macro_rules! forward_complex_binop {
287    ($big_name:ident, $small_name:ident, $assign_big_name:ident, $assign_small_name:ident) => {
288        forward_complex_immutable_binop!(Fixed, Fixed, $big_name, $small_name);
289        forward_complex_immutable_binop!(Fixed, &Fixed, $big_name, $small_name);
290        forward_complex_immutable_binop!(&Fixed, Fixed, $big_name, $small_name);
291        forward_complex_immutable_binop!(&Fixed, &Fixed, $big_name, $small_name);
292
293        impl $assign_big_name for Fixed {
294            #[inline]
295            fn $assign_small_name(&mut self, rhs: Self) {
296                self.0 = $small_name(self.0, rhs.0);
297            }
298        }
299    };
300}
301
302forward_complex_binop!(Mul, mul, MulAssign, mul_assign);
303forward_complex_binop!(Div, div, DivAssign, div_assign);
304
305macro_rules! forward_shiftop {
306    ($big_name:ident, $small_name:ident, $arg:ty, $op:tt, $assign_big_name:ident, $assign_small_name:ident, $assign_op:tt) => {
307        impl $big_name<$arg> for Fixed {
308            type Output = Fixed;
309
310            #[inline]
311            fn $small_name(self, rhs: $arg) -> Self::Output {
312                Fixed(self.0 $op rhs)
313            }
314        }
315
316        impl $big_name<$arg> for &Fixed {
317            type Output = Fixed;
318
319            #[inline]
320            fn $small_name(self, rhs: $arg) -> Self::Output {
321                Fixed(self.0 $op rhs)
322            }
323        }
324
325        impl $assign_big_name<$arg> for Fixed {
326            #[inline]
327            fn $assign_small_name(&mut self, rhs: $arg) {
328                self.0 $assign_op rhs;
329            }
330        }
331    };
332}
333
334macro_rules! forward_shift {
335    ($arg:ty) => {
336        forward_shiftop!(Shl, shl, $arg,  <<, ShlAssign, shl_assign, <<=);
337        forward_shiftop!(Shl, shl, &$arg, <<, ShlAssign, shl_assign, <<=);
338        forward_shiftop!(Shr, shr, $arg,  >>, ShrAssign, shr_assign, >>=);
339        forward_shiftop!(Shr, shr, &$arg, >>, ShrAssign, shr_assign, >>=);
340    }
341}
342
343forward_shift!(u8);
344forward_shift!(i8);
345forward_shift!(u16);
346forward_shift!(i16);
347forward_shift!(u32);
348forward_shift!(i32);
349forward_shift!(u64);
350forward_shift!(i64);
351forward_shift!(u128);
352forward_shift!(i128);
353forward_shift!(usize);
354forward_shift!(isize);
355
356macro_rules! forward_immutable_unop {
357    ($slf:ty, $big_name:ident, $small_name:ident, $op:tt) => {
358        impl $big_name for $slf {
359            type Output = Fixed;
360
361            #[inline]
362            fn $small_name(self) -> Self::Output {
363                Fixed($op self.0)
364            }
365        }
366    };
367}
368
369macro_rules! forward_unop {
370    ($big_name:ident, $small_name:ident, $op:tt) => {
371        forward_immutable_unop!(Fixed, $big_name, $small_name, $op);
372        forward_immutable_unop!(&Fixed, $big_name, $small_name, $op);
373    };
374}
375
376forward_unop!(Neg, neg, -);
377forward_unop!(Not, not, !);