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 const INT_MASK: $ty = !0 << $fract_bits;
31 const ROUND: $ty = 1 << ($fract_bits - 1);
32 const FRACT_BITS: usize = $fract_bits;
33
34 #[inline(always)]
36 pub const fn from_bits(bits: $ty) -> Self {
37 Self(bits)
38 }
39
40 #[inline(always)]
42 pub const fn to_bits(self) -> $ty {
43 self.0
44 }
45
46 #[inline(always)]
49 pub const fn round(self) -> Self {
50 Self(self.0.wrapping_add(Self::ROUND) & Self::INT_MASK)
51 }
52
53 #[inline(always)]
55 pub const fn abs(self) -> Self {
56 Self(self.0.abs())
57 }
58
59 #[inline(always)]
61 pub const fn floor(self) -> Self {
62 Self(self.0 & Self::INT_MASK)
63 }
64
65 #[inline(always)]
67 pub const fn fract(self) -> Self {
68 Self(self.0 - self.floor().0)
69 }
70
71 #[inline(always)]
73 pub fn wrapping_add(self, other: Self) -> Self {
74 Self(self.0.wrapping_add(other.0))
75 }
76
77 #[inline(always)]
79 pub const fn saturating_add(self, other: Self) -> Self {
80 Self(self.0.saturating_add(other.0))
81 }
82
83 #[inline(always)]
85 pub fn checked_add(self, other: Self) -> Option<Self> {
86 self.0.checked_add(other.0).map(|inner| Self(inner))
87 }
88
89 #[inline(always)]
91 pub const fn wrapping_sub(self, other: Self) -> Self {
92 Self(self.0.wrapping_sub(other.0))
93 }
94
95 #[inline(always)]
97 pub const fn saturating_sub(self, other: Self) -> Self {
98 Self(self.0.saturating_sub(other.0))
99 }
100
101 #[inline(always)]
103 pub const fn to_be_bytes(self) -> [u8; $bits / 8] {
104 self.0.to_be_bytes()
105 }
106 }
107
108 impl Add for $name {
109 type Output = Self;
110 #[inline(always)]
111 fn add(self, other: Self) -> Self {
112 Self(self.0.wrapping_add(other.0))
113 }
114 }
115
116 impl AddAssign for $name {
117 #[inline(always)]
118 fn add_assign(&mut self, other: Self) {
119 *self = *self + other;
120 }
121 }
122
123 impl Sub for $name {
124 type Output = Self;
125 #[inline(always)]
126 fn sub(self, other: Self) -> Self {
127 Self(self.0.wrapping_sub(other.0))
128 }
129 }
130
131 impl SubAssign for $name {
132 #[inline(always)]
133 fn sub_assign(&mut self, other: Self) {
134 *self = *self - other;
135 }
136 }
137 };
138}
139
140macro_rules! fixed_mul_div {
142 ($ty:ty) => {
143 impl $ty {
144 #[inline]
148 pub const fn mul_div(&self, a: Self, b: Self) -> Self {
149 let mut sign = 1;
150 let mut su = self.0 as u64;
151 let mut au = a.0 as u64;
152 let mut bu = b.0 as u64;
153 if self.0 < 0 {
154 su = 0u64.wrapping_sub(su);
155 sign = -1;
156 }
157 if a.0 < 0 {
158 au = 0u64.wrapping_sub(au);
159 sign = -sign;
160 }
161 if b.0 < 0 {
162 bu = 0u64.wrapping_sub(bu);
163 sign = -sign;
164 }
165 let result = if bu > 0 {
166 su.wrapping_mul(au).wrapping_add(bu >> 1) / bu
167 } else {
168 0x7FFFFFFF
169 };
170 Self(if sign < 0 {
171 -(result as i32)
172 } else {
173 result as i32
174 })
175 }
176 }
177
178 impl Mul for $ty {
179 type Output = Self;
180 #[inline(always)]
181 fn mul(self, other: Self) -> Self::Output {
182 let ab = self.0 as i64 * other.0 as i64;
183 Self(((ab + 0x8000 - i64::from(ab < 0)) >> 16) as i32)
184 }
185 }
186
187 impl MulAssign for $ty {
188 #[inline(always)]
189 fn mul_assign(&mut self, rhs: Self) {
190 *self = *self * rhs;
191 }
192 }
193
194 impl Div for $ty {
195 type Output = Self;
196 #[inline(always)]
197 fn div(self, other: Self) -> Self::Output {
198 let mut sign = 1;
199 let mut a = self.0;
200 let mut b = other.0;
201 if a < 0 {
202 a = -a;
203 sign = -1;
204 }
205 if b < 0 {
206 b = -b;
207 sign = -sign;
208 }
209 let q = if b == 0 {
210 0x7FFFFFFF
211 } else {
212 ((((a as u64) << 16) + ((b as u64) >> 1)) / (b as u64)) as u32
213 };
214 Self(if sign < 0 { -(q as i32) } else { q as i32 })
215 }
216 }
217
218 impl DivAssign for $ty {
219 #[inline(always)]
220 fn div_assign(&mut self, rhs: Self) {
221 *self = *self / rhs;
222 }
223 }
224
225 impl Neg for $ty {
226 type Output = Self;
227 #[inline(always)]
228 fn neg(self) -> Self {
229 Self(-self.0)
230 }
231 }
232 };
233}
234
235macro_rules! float_conv {
240 ($name:ident, $to:ident, $from:ident, $ty:ty) => {
241 impl $name {
242 #[doc = concat!("Creates a fixed point value from a", stringify!($ty), ".")]
243 #[inline(always)]
247 pub fn $from(x: $ty) -> Self {
248 let frac = (x.is_sign_positive() as u8 as $ty) - 0.5;
251 Self((x * Self::ONE.0 as $ty + frac) as _)
252 }
253
254 #[doc = concat!("Returns the value as an ", stringify!($ty), ".")]
255 #[inline(always)]
259 pub fn $to(self) -> $ty {
260 let int = ((self.0 & Self::INT_MASK) >> Self::FRACT_BITS) as $ty;
261 let fract = (self.0 & !Self::INT_MASK) as $ty / Self::ONE.0 as $ty;
262 int + fract
263 }
264 }
265
266 impl std::fmt::Display for $name {
268 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
269 self.$to().fmt(f)
270 }
271 }
272
273 impl std::fmt::Debug for $name {
274 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
275 self.$to().fmt(f)
276 }
277 }
278 };
279}
280
281fixed_impl!(F2Dot14, 16, 14, i16);
282fixed_impl!(F4Dot12, 16, 12, i16);
283fixed_impl!(F6Dot10, 16, 10, i16);
284fixed_impl!(Fixed, 32, 16, i32);
285fixed_impl!(F26Dot6, 32, 6, i32);
286fixed_mul_div!(Fixed);
287fixed_mul_div!(F26Dot6);
288float_conv!(F2Dot14, to_f32, from_f32, f32);
289float_conv!(F4Dot12, to_f32, from_f32, f32);
290float_conv!(F6Dot10, to_f32, from_f32, f32);
291float_conv!(Fixed, to_f64, from_f64, f64);
292float_conv!(F26Dot6, to_f64, from_f64, f64);
293crate::newtype_scalar!(F2Dot14, [u8; 2]);
294crate::newtype_scalar!(F4Dot12, [u8; 2]);
295crate::newtype_scalar!(F6Dot10, [u8; 2]);
296crate::newtype_scalar!(Fixed, [u8; 4]);
297
298impl Fixed {
299 #[inline(always)]
301 pub const fn from_i32(i: i32) -> Self {
302 Self(i << 16)
303 }
304
305 #[inline(always)]
308 pub const fn to_i32(self) -> i32 {
309 self.0.wrapping_add(0x8000) >> 16
310 }
311
312 #[inline(always)]
314 pub const fn to_f26dot6(self) -> F26Dot6 {
315 F26Dot6(self.0.wrapping_add(0x200) >> 10)
316 }
317
318 #[inline(always)]
326 pub const fn to_f2dot14(self) -> F2Dot14 {
327 F2Dot14((self.0.wrapping_add(2) >> 2) as _)
328 }
329
330 #[inline(always)]
335 pub fn to_f32(self) -> f32 {
336 const SCALE_FACTOR: f32 = 1.0 / 65536.0;
337 self.0 as f32 * SCALE_FACTOR
338 }
339}
340
341impl From<i32> for Fixed {
342 fn from(value: i32) -> Self {
343 Self::from_i32(value)
344 }
345}
346
347impl F26Dot6 {
348 #[inline(always)]
350 pub const fn from_i32(i: i32) -> Self {
351 Self(i << 6)
352 }
353
354 #[inline(always)]
357 pub const fn to_i32(self) -> i32 {
358 self.0.wrapping_add(32) >> 6
359 }
360
361 #[inline(always)]
366 pub fn to_f32(self) -> f32 {
367 const SCALE_FACTOR: f32 = 1.0 / 64.0;
368 self.0 as f32 * SCALE_FACTOR
369 }
370}
371
372impl F2Dot14 {
373 #[inline(always)]
375 pub const fn to_fixed(self) -> Fixed {
376 Fixed(self.0 as i32 * 4)
377 }
378}
379
380#[cfg(test)]
381mod tests {
382 #![allow(overflowing_literals)] use super::*;
384
385 #[test]
386 fn f2dot14_floats() {
387 assert_eq!(F2Dot14(0x7fff), F2Dot14::from_f32(1.999939));
389 assert_eq!(F2Dot14(0x7000), F2Dot14::from_f32(1.75));
390 assert_eq!(F2Dot14(0x0001), F2Dot14::from_f32(0.0000610356));
391 assert_eq!(F2Dot14(0x0000), F2Dot14::from_f32(0.0));
392 assert_eq!(F2Dot14(0xffff), F2Dot14::from_f32(-0.000061));
393 assert_eq!(F2Dot14(0x8000), F2Dot14::from_f32(-2.0));
394 }
395
396 #[test]
397 fn roundtrip_f2dot14() {
398 for i in i16::MIN..=i16::MAX {
399 let val = F2Dot14(i);
400 assert_eq!(val, F2Dot14::from_f32(val.to_f32()));
401 }
402 }
403
404 #[test]
405 fn round_f2dot14() {
406 assert_eq!(F2Dot14(0x7000).round(), F2Dot14::from_f32(-2.0));
407 assert_eq!(F2Dot14(0x1F00).round(), F2Dot14::from_f32(0.0));
408 assert_eq!(F2Dot14(0x2000).round(), F2Dot14::from_f32(1.0));
409 }
410
411 #[test]
412 fn round_fixed() {
413 assert_eq!(Fixed(0x0001_7FFE).round(), Fixed(0x0001_0000));
415 assert_eq!(Fixed(0x0001_7FFF).round(), Fixed(0x0001_0000));
416 assert_eq!(Fixed(0x0001_8000).round(), Fixed(0x0002_0000));
417 }
418
419 #[test]
429 fn fixed_floats() {
430 assert_eq!(Fixed(0x7fff_0000), Fixed::from_f64(32767.));
431 assert_eq!(Fixed(0x7000_0001), Fixed::from_f64(28672.00001525879));
432 assert_eq!(Fixed(0x0001_0000), Fixed::from_f64(1.0));
433 assert_eq!(Fixed(0x0000_0000), Fixed::from_f64(0.0));
434 assert_eq!(
435 Fixed(i32::from_be_bytes([0xff; 4])),
436 Fixed::from_f64(-0.000015259)
437 );
438 assert_eq!(Fixed(0x7fff_ffff), Fixed::from_f64(32768.0));
439 }
440
441 #[test]
445 fn fixed_floats_rounding() {
446 fn with_round_intrinsic(x: f64) -> Fixed {
447 Fixed((x * 65536.0).round() as i32)
448 }
449 let inputs = [0.05, 0.6, 0.2, 0.4, 0.67755];
451 for input in inputs {
452 assert_eq!(Fixed::from_f64(input), with_round_intrinsic(input));
453 assert_eq!(Fixed::from_f64(-input), with_round_intrinsic(-input));
455 }
456 }
457
458 #[test]
459 fn fixed_to_int() {
460 assert_eq!(Fixed::from_f64(1.0).to_i32(), 1);
461 assert_eq!(Fixed::from_f64(1.5).to_i32(), 2);
462 assert_eq!(F26Dot6::from_f64(1.0).to_i32(), 1);
463 assert_eq!(F26Dot6::from_f64(1.5).to_i32(), 2);
464 }
465
466 #[test]
467 fn fixed_from_int() {
468 assert_eq!(Fixed::from_i32(1000).to_bits(), 1000 << 16);
469 assert_eq!(F26Dot6::from_i32(1000).to_bits(), 1000 << 6);
470 }
471
472 #[test]
473 fn fixed_to_f26dot6() {
474 assert_eq!(Fixed::from_f64(42.5).to_f26dot6(), F26Dot6::from_f64(42.5));
475 }
476
477 #[test]
478 fn fixed_muldiv() {
479 assert_eq!(
480 Fixed::from_f64(0.5) * Fixed::from_f64(2.0),
481 Fixed::from_f64(1.0)
482 );
483 assert_eq!(
484 Fixed::from_f64(0.5) / Fixed::from_f64(2.0),
485 Fixed::from_f64(0.25)
486 );
487 }
488}