1use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
4
5macro_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 pub const MIN: Self = Self(<$ty>::MIN);
17
18 pub const MAX: Self = Self(<$ty>::MAX);
20
21 pub const EPSILON: Self = Self(1);
23
24 pub const ZERO: Self = Self(0);
26
27 pub const ONE: Self = Self(1 << $fract_bits);
29
30 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 #[inline(always)]
39 pub const fn from_bits(bits: $ty) -> Self {
40 Self(bits)
41 }
42
43 #[inline(always)]
45 pub const fn to_bits(self) -> $ty {
46 self.0
47 }
48
49 #[inline(always)]
52 pub const fn round(self) -> Self {
53 Self(self.0.wrapping_add(Self::ROUND) & Self::INT_MASK)
54 }
55
56 #[inline(always)]
58 pub const fn abs(self) -> Self {
59 Self(self.0.abs())
60 }
61
62 #[inline(always)]
64 pub const fn floor(self) -> Self {
65 Self(self.0 & Self::INT_MASK)
66 }
67
68 #[inline(always)]
70 pub const fn fract(self) -> Self {
71 Self(self.0 - self.floor().0)
72 }
73
74 #[inline(always)]
76 pub fn wrapping_add(self, other: Self) -> Self {
77 Self(self.0.wrapping_add(other.0))
78 }
79
80 #[inline(always)]
82 pub const fn saturating_add(self, other: Self) -> Self {
83 Self(self.0.saturating_add(other.0))
84 }
85
86 #[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 #[inline(always)]
94 pub const fn wrapping_sub(self, other: Self) -> Self {
95 Self(self.0.wrapping_sub(other.0))
96 }
97
98 #[inline(always)]
100 pub const fn saturating_sub(self, other: Self) -> Self {
101 Self(self.0.saturating_sub(other.0))
102 }
103
104 #[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
143macro_rules! fixed_mul_div {
145 ($ty:ty) => {
146 impl $ty {
147 #[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
233macro_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 #[inline(always)]
245 pub fn $from(x: $ty) -> Self {
246 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 #[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 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 #[inline(always)]
299 pub const fn from_i32(i: i32) -> Self {
300 Self(i << 16)
301 }
302
303 #[inline(always)]
306 pub const fn to_i32(self) -> i32 {
307 self.0.wrapping_add(0x8000) >> 16
308 }
309
310 #[inline(always)]
312 pub const fn to_f26dot6(self) -> F26Dot6 {
313 F26Dot6(self.0.wrapping_add(0x200) >> 10)
314 }
315
316 #[inline(always)]
324 pub const fn to_f2dot14(self) -> F2Dot14 {
325 F2Dot14((self.0.wrapping_add(2) >> 2) as _)
326 }
327
328 #[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 #[inline(always)]
348 pub const fn from_i32(i: i32) -> Self {
349 Self(i << 6)
350 }
351
352 #[inline(always)]
355 pub const fn to_i32(self) -> i32 {
356 self.0.wrapping_add(32) >> 6
357 }
358
359 #[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 #[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)] use super::*;
382
383 #[test]
384 fn f2dot14_floats() {
385 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 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 #[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 #[test]
443 fn fixed_floats_rounding() {
444 fn with_round_intrinsic(x: f64) -> Fixed {
445 Fixed((x * 65536.0).round() as i32)
446 }
447 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 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 #[test]
491 fn fixed_div_neg_overflow() {
492 let a = Fixed::from_f64(-92.5);
493 let b = Fixed::from_f64(0.0028228759765625);
494 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 let _ = a.mul_div(Fixed::ONE, b);
504 }
505
506 #[test]
507 fn fixed_div_min_value() {
508 let min = Fixed(i32::MIN);
510 let one = Fixed::ONE;
511 let _ = min / one;
513 let neg_one = Fixed(-Fixed::ONE.0);
515 let _ = min / neg_one;
516 }
517}