1use std::{
2 cmp::Ordering,
3 fmt::{Debug, Display},
4 io::Write,
5 ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
6 str::FromStr,
7};
8
9use num_traits::{cast, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, Zero};
10use smallvec::{Array, SmallVec};
11
12use crate::u256::I256;
13
14#[cfg(feature = "dbsp")]
15mod dbsp_impl;
16
17#[cfg(feature = "serde")]
18mod serde_impl;
19mod u256;
20
21#[cfg(feature = "rkyv")]
22mod rkyv_impl;
23
24#[derive(Copy, Clone, Default, Eq, Ord, Hash)]
50#[cfg_attr(feature = "size_of", derive(size_of::SizeOf))]
51pub struct Fixed<const P: usize, const S: usize>(i128);
52
53impl<const P0: usize, const S0: usize, const P1: usize, const S1: usize> PartialEq<Fixed<P1, S1>>
54 for Fixed<P0, S0>
55{
56 fn eq(&self, other: &Fixed<P1, S1>) -> bool {
57 match S0.cmp(&S1) {
58 Ordering::Less => I256::from_product(self.0, pow10(S1 - S0)) == I256::from(other.0),
59 Ordering::Equal => self.0 == other.0,
60 Ordering::Greater => I256::from(self.0) == I256::from_product(other.0, pow10(S0 - S1)),
61 }
62 }
63}
64
65macro_rules! partial_eq_int {
66 ($type_name:ty) => {
67 impl<const P0: usize, const S0: usize> PartialEq<$type_name> for Fixed<P0, S0> {
68 fn eq(&self, other: &$type_name) -> bool {
69 self.0 % Self::scale() == 0 && self.0 / Self::scale() == *other as i128
70 }
71 }
72 };
73}
74partial_eq_int!(i8);
75partial_eq_int!(i16);
76partial_eq_int!(i32);
77partial_eq_int!(i64);
78partial_eq_int!(i128);
79partial_eq_int!(isize);
80partial_eq_int!(u8);
81partial_eq_int!(u16);
82partial_eq_int!(u32);
83partial_eq_int!(u64);
84
85impl<const P0: usize, const S0: usize> PartialEq<u128> for Fixed<P0, S0> {
86 fn eq(&self, other: &u128) -> bool {
87 self.0 >= 0
88 && self.0 % Self::scale() == 0
89 && (self.0 / Self::scale()).cast_unsigned() == *other
90 }
91}
92
93impl<const P0: usize, const S0: usize> PartialEq<usize> for Fixed<P0, S0> {
94 fn eq(&self, other: &usize) -> bool {
95 self.0 >= 0
96 && self.0 % Self::scale() == 0
97 && (self.0 / Self::scale()).cast_unsigned() == *other as u128
98 }
99}
100
101#[inline(never)]
102pub fn eq_i32(f: Fixed<38, 0>, x: i32) -> bool {
103 f == x
104}
105
106impl<const P0: usize, const S0: usize, const P1: usize, const S1: usize> PartialOrd<Fixed<P1, S1>>
107 for Fixed<P0, S0>
108{
109 fn partial_cmp(&self, other: &Fixed<P1, S1>) -> Option<Ordering> {
110 match S0.cmp(&S1) {
111 Ordering::Less => {
112 I256::from_product(self.0, pow10(S1 - S0)).partial_cmp(&I256::from(other.0))
113 }
114 Ordering::Equal => self.0.partial_cmp(&other.0),
115 Ordering::Greater => {
116 I256::from(self.0).partial_cmp(&I256::from_product(other.0, pow10(S0 - S1)))
117 }
118 }
119 }
120}
121
122pub type FixedInteger = Fixed<38, 0>;
124
125impl<const P: usize, const S: usize> Debug for Fixed<P, S> {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 if S == 0 {
128 write!(f, "{}", self.0)
129 } else if self.0 % Self::scale() == 0 {
130 write!(f, "{}", self.0 / Self::scale())
131 } else {
132 write!(
133 f,
134 "{}{}.{}",
135 if self.0 < 0 { "-" } else { "" },
136 self.0.abs() / Self::scale(),
137 (self.0.abs() % Self::scale()).abs()
138 )
139 }
140 }
141}
142
143impl<const P: usize, const S: usize> Display for Fixed<P, S> {
144 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 let mut buf = SmallVec::<[u8; 64]>::new();
146 write!(&mut buf, "{:01$}", self.0.abs(), S + 1).unwrap();
147 debug_assert!(buf.len() > S);
148 let decimals = if let Some(precision) = f.precision() {
149 match precision.cmp(&S) {
150 Ordering::Less => {
151 let new_len = buf.len() - (S - precision);
152 let mut discard = buf[new_len..].iter();
153 enum Rounding {
154 Up,
155 Down,
156 Even,
157 }
158 impl Rounding {
159 fn round<A>(&self, s: &mut SmallVec<A>)
160 where
161 A: Array<Item = u8>,
162 {
163 let round_up = match self {
164 Rounding::Down => false,
165 Rounding::Up => true,
166 Rounding::Even => s.last().unwrap() % 2 == 1,
167 };
168 if round_up {
169 let mut nines = 0;
170 let c = loop {
171 match s.pop() {
172 Some(b'9') => nines += 1,
173 Some(c) => break c,
174 None => break b'0',
175 }
176 };
177 s.push(c + 1);
178 for _ in 0..nines {
179 s.push(b'0');
180 }
181 }
182 }
183 }
184 let rounding = match discard.next().unwrap() {
185 b'0'..=b'4' => Rounding::Down,
186 b'5' => loop {
187 match discard.next() {
188 Some(b'0') => (),
189 Some(_) => break Rounding::Up,
190 None => break Rounding::Even,
191 }
192 },
193 b'6'..=b'9' => Rounding::Up,
194 _ => unreachable!(),
195 };
196 buf.truncate(new_len);
197 rounding.round(&mut buf);
198 }
199 Ordering::Equal => (),
200 Ordering::Greater => {
201 for _ in S..precision {
202 buf.push(b'0');
203 }
204 }
205 }
206 precision
207 } else {
208 let mut decimals = S;
209 while decimals > 0 && buf.ends_with(b"0") {
210 buf.pop();
211 decimals -= 1;
212 }
213 decimals
214 };
215 if decimals > 0 {
216 buf.insert(buf.len() - decimals, b'.');
217 }
218
219 f.pad_integral(self.0 >= 0, "", unsafe { str::from_utf8_unchecked(&buf) })
221 }
222}
223
224#[derive(Copy, Clone, Debug)]
225pub struct OutOfRange;
226
227const fn checked_pow10(exponent: u32) -> Option<i128> {
230 10i128.checked_pow(exponent)
231}
232
233const fn pow10(exponent: usize) -> i128 {
240 10i128.checked_pow(exponent as u32).unwrap()
241}
242
243#[derive(Copy, Clone, PartialEq, Eq)]
245enum Halfway {
246 AwayFromZero,
248
249 Even,
251}
252
253fn round_inner(value: i128, scale: i32, n: i32, halfway: Halfway) -> Option<i128> {
254 let position = scale.saturating_sub(n);
255 if position <= 0 {
256 Some(value)
257 } else if position < scale {
258 let divisor = pow10(position as usize);
259 let quotient = value / divisor;
260 let remainder = value % divisor;
261 let round_away_from_zero = match remainder.abs().cmp(&(divisor / 2)) {
262 Ordering::Less => false,
263 Ordering::Equal => match halfway {
264 Halfway::AwayFromZero => true,
265 Halfway::Even => (quotient % 2) != 0,
266 },
267 Ordering::Greater => true,
268 };
269 let rounded_quotient = if round_away_from_zero {
270 quotient + quotient.signum()
271 } else {
272 quotient
273 };
274 Some(divisor * rounded_quotient)
275 } else if position > scale || value.abs() >= 5 * pow10(scale as usize - 1) {
276 Some(0)
277 } else {
278 None
279 }
280}
281
282const fn div_floor(x: i128, y: i128) -> i128 {
285 let d = x / y;
286 let r = x % y;
287
288 let correction = (x ^ y) >> (i128::BITS - 1);
295 if r != 0 {
296 d + correction
297 } else {
298 d
299 }
300}
301
302const fn div_ceil(x: i128, y: i128) -> i128 {
305 let d = x / y;
306 let r = x % y;
307
308 let correction = 1 + ((x ^ y) >> (i128::BITS - 1));
311 if r != 0 {
312 d + correction
313 } else {
314 d
315 }
316}
317
318impl<const P: usize, const S: usize> Fixed<P, S> {
319 pub const MAX: Self = Self(pow10(P) - 1);
321
322 pub const MIN: Self = Self(-Self::MAX.0);
326
327 pub const ZERO: Self = Self(0);
329
330 pub const ONE: Self = {
337 if S < P {
338 Self(pow10(S))
339 } else {
340 panic!("all values of Fixed::<S,P>::one() for S >= P have magnitude less than one");
341 }
342 };
343
344 pub const fn for_i64(value: i64) -> Self {
350 assert!(P.saturating_sub(S) >= 19);
351 Self(value as i128 * Self::scale())
352 }
353
354 pub const fn for_u64(value: u64) -> Self {
360 assert!(P.saturating_sub(S) >= 19);
361 Self(value as i128 * Self::scale())
362 }
363
364 pub const fn for_i32(value: i32) -> Self {
370 assert!(P.saturating_sub(S) >= 10);
371 Self(value as i128 * Self::scale())
372 }
373
374 pub const fn for_u32(value: u32) -> Self {
380 assert!(P.saturating_sub(S) >= 10);
381 Self(value as i128 * Self::scale())
382 }
383
384 pub const fn for_i16(value: i16) -> Self {
390 assert!(P.saturating_sub(S) >= 5);
391 Self(value as i128 * Self::scale())
392 }
393
394 pub const fn for_u16(value: u16) -> Self {
400 assert!(P.saturating_sub(S) >= 5);
401 Self(value as i128 * Self::scale())
402 }
403
404 pub const fn for_i8(value: i8) -> Self {
410 assert!(P.saturating_sub(S) >= 3);
411 Self(value as i128 * Self::scale())
412 }
413
414 pub const fn for_u8(value: u8) -> Self {
420 assert!(P.saturating_sub(S) >= 3);
421 Self(value as i128 * Self::scale())
422 }
423
424 pub const fn for_isize(value: isize) -> Self {
430 match isize::BITS {
431 64 => Self::for_i64(value as i64),
432 32 => Self::for_i32(value as i32),
433 16 => Self::for_i16(value as i16),
434 _ => panic!(),
435 }
436 }
437
438 pub const fn for_usize(value: usize) -> Self {
444 match usize::BITS {
445 64 => Self::for_u64(value as u64),
446 32 => Self::for_u32(value as u32),
447 16 => Self::for_u16(value as u16),
448 _ => panic!(),
449 }
450 }
451
452 fn try_new(value: i128) -> Option<Self> {
454 const { Self::check_constraints() };
455 (Self::MIN.0..=Self::MAX.0)
456 .contains(&value)
457 .then_some(Self(value))
458 }
459
460 fn try_new_with_exponent_round_even(value: i128, exponent: i32) -> Option<Self> {
463 fn inner(value: i128, exponent: i32) -> Option<i128> {
465 Some(match exponent.cmp(&0) {
466 Ordering::Less => {
467 if let Some(divisor) = checked_pow10(exponent.unsigned_abs()) {
469 debug_assert!(divisor >= 2);
474 let quotient = value / divisor;
475 let remainder = value % divisor;
476 let round_away_from_zero = match remainder.abs().cmp(&(divisor / 2)) {
477 Ordering::Less => false,
478 Ordering::Equal => (quotient % 2) != 0,
479 Ordering::Greater => true,
480 };
481 if round_away_from_zero {
482 quotient + quotient.signum()
483 } else {
484 quotient
485 }
486 } else {
487 0
490 }
491 }
492 Ordering::Equal => value,
493 Ordering::Greater => {
494 value.checked_mul(checked_pow10(exponent.cast_unsigned())?)?
496 }
497 })
498 }
499 inner(value, exponent).and_then(Self::try_new)
500 }
501
502 fn try_new_with_exponent(value: i128, exponent: i32) -> Option<Self> {
505 fn inner(value: i128, exponent: i32) -> Option<i128> {
507 Some(match exponent.cmp(&0) {
508 Ordering::Less => {
509 if let Some(divisor) = checked_pow10(exponent.unsigned_abs()) {
511 value / divisor
512 } else {
513 0
516 }
517 }
518 Ordering::Equal => value,
519 Ordering::Greater => {
520 value.checked_mul(checked_pow10(exponent.cast_unsigned())?)?
522 }
523 })
524 }
525 inner(value, exponent).and_then(Self::try_new)
526 }
527
528 const fn check_constraints() {
530 assert!(P >= 1 && P <= 38, "Fixed<S,P> must have 1 <= S <= 38");
531 assert!(S <= P, "Fixed<S,P> must have S <= P");
532 }
533
534 const fn scale() -> i128 {
536 Self::check_constraints();
537 pow10(S)
538 }
539
540 pub const fn checked_div_integer(self, other: Self) -> Option<i128> {
546 self.0.checked_div(other.0)
547 }
548
549 pub const fn strict_div_integer(self, other: Self) -> i128 {
556 self.checked_div_integer(other).unwrap()
557 }
558
559 pub const fn checked_rem_integer(self, _other: Self) -> Option<Self> {
564 todo!()
565 }
566
567 pub const fn strict_rem_integer(self, other: Self) -> Self {
574 self.checked_rem_integer(other).unwrap()
575 }
576
577 pub const fn abs(self) -> Self {
580 Self(self.0.abs())
581 }
582
583 pub const fn is_negative(self) -> bool {
585 self.0.is_negative()
586 }
587
588 pub fn checked_sqrt(self) -> Option<Self> {
594 Some(Self(
595 I256::from_product(self.0, Self::scale()).checked_isqrt()?,
596 ))
597 }
598
599 pub fn sqrt(self) -> Self {
608 self.checked_sqrt().unwrap()
609 }
610
611 pub fn checked_round(&self, n: i32) -> Option<Self> {
616 round_inner(self.0, S as i32, n, Halfway::AwayFromZero).and_then(Self::try_new)
617 }
618
619 pub fn round(&self, n: i32) -> Self {
628 self.checked_round(n).unwrap()
629 }
630
631 pub fn checked_round_ties_even(&self, n: i32) -> Option<Self> {
636 round_inner(self.0, S as i32, n, Halfway::Even).and_then(Self::try_new)
637 }
638
639 pub fn round_ties_even(&self, n: i32) -> Self {
649 self.checked_round_ties_even(n).unwrap()
650 }
651
652 pub fn checked_floor(&self) -> Option<Self> {
655 if S > 0 {
656 Self::try_new(div_floor(self.0, Self::scale()) * Self::scale())
657 } else {
658 Some(*self)
659 }
660 }
661
662 pub fn floor(&self) -> Self {
670 self.checked_floor().unwrap()
671 }
672
673 pub fn truncate(&self) -> Self {
676 Self(self.0 / Self::scale() * Self::scale())
677 }
678
679 pub fn checked_ceil(&self) -> Option<Self> {
682 if S > 0 {
683 Self::try_new(div_ceil(self.0, Self::scale()) * Self::scale())
684 } else {
685 Some(*self)
686 }
687 }
688
689 pub fn ceil(&self) -> Self {
697 self.checked_ceil().unwrap()
698 }
699
700 pub fn sign(&self) -> Fixed<1, 0> {
703 self.checked_sign_generic().unwrap()
704 }
705
706 pub fn checked_recip(&self) -> Option<Self> {
709 if S < P {
710 Self(Self::scale()).checked_div(self)
711 } else {
712 None
716 }
717 }
718
719 pub fn recip(&self) -> Self {
726 self.checked_recip().unwrap()
727 }
728
729 pub fn checked_powi(&self, exp: i32) -> Option<Self> {
739 if self.is_zero() {
740 (exp > 0).then_some(Self::ZERO)
741 } else if exp == 0 {
742 if S < P {
743 Some(Self::ONE)
744 } else {
745 None
747 }
748 } else if exp > 0 {
749 let mut exp = exp.unsigned_abs();
750 let mut base = self.0;
751 let mut base_scale = S as i32;
752 let mut acc = None;
753 loop {
754 if (exp & 1) == 1 {
755 acc = if let Some((acc, acc_scale)) = acc {
756 let (acc, shift) = I256::from_product(acc, base).reduce_to_i128();
757 Some((acc, (acc_scale + base_scale) - shift as i32))
758 } else {
759 Some((base, base_scale))
760 };
761 }
762 exp /= 2;
763 if exp == 0 {
764 let (acc, acc_scale) = acc.unwrap();
765 return Self::try_new_with_exponent(acc, S as i32 - acc_scale);
766 }
767
768 let (next_base, shift) = I256::from_product(base, base).reduce_to_i128();
769 base = next_base;
770 base_scale = base_scale * 2 - shift as i32;
771 }
772 } else {
773 let mut exp = exp.unsigned_abs();
774 let mut base = *self;
775 let mut acc: Option<Fixed<P, S>> = None;
776 loop {
777 if (exp & 1) == 1 {
778 acc = Some(if let Some(acc) = acc {
779 acc.checked_div(&base)
780 } else {
781 base.checked_recip()
782 }?)
783 }
784 exp /= 2;
785 if exp == 0 {
786 return acc;
787 }
788 base *= base;
789 }
790 }
791 }
792
793 pub fn powi(&self, exp: i32) -> Self {
804 self.checked_powi(exp).unwrap()
805 }
806
807 pub fn next_up(&self) -> Option<Self> {
810 if *self < Self::MAX {
811 Some(Self(self.0 + 1))
812 } else {
813 None
814 }
815 }
816
817 pub fn next_down(&self) -> Option<Self> {
820 if *self > Self::MIN {
821 Some(Self(self.0 - 1))
822 } else {
823 None
824 }
825 }
826
827 pub fn encode(&self) -> (i128, u8) {
830 (self.0, S as u8)
831 }
832
833 pub fn decode(value: i128, scale: u8) -> Option<Self> {
840 Self::try_new_with_exponent(value, S as i32 - scale as i32)
841 }
842}
843
844impl<const P0: usize, const S0: usize> Fixed<P0, S0> {
845 pub fn convert<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
854 Fixed::try_new_with_exponent(self.0, S1 as i32 - S0 as i32)
855 }
856
857 pub fn convert_round_even<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
862 Fixed::try_new_with_exponent_round_even(self.0, S1 as i32 - S0 as i32)
863 }
864
865 pub fn checked_sign_generic<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
869 let one = Fixed::<P1, S1>::scale();
870 match self.0.cmp(&0) {
871 Ordering::Less if S1 < P1 => Some(Fixed(-one)),
872 Ordering::Equal => Some(Fixed::ZERO),
873 Ordering::Greater if S1 < P1 => Some(Fixed(one)),
874 _ => None,
875 }
876 }
877
878 pub fn checked_add_generic<
884 const P1: usize,
885 const S1: usize,
886 const P2: usize,
887 const S2: usize,
888 >(
889 self,
890 other: Fixed<P1, S1>,
891 ) -> Option<Fixed<P2, S2>> {
892 match S0.cmp(&S1) {
893 Ordering::Less => {
894 let factor = pow10(S1 - S0);
895 if self.0 <= i128::MAX / factor / 10 {
896 Fixed::try_new_with_exponent(
897 other.0.checked_add(self.0 * factor)?,
898 S2 as i32 - S1 as i32,
899 )
900 } else {
901 let result = (I256::from_product(self.0, factor) + I256::from(other.0))
902 .narrowing_div(pow10(S2.saturating_sub(S1)))?;
903 Fixed::try_new_with_exponent(result, S1.saturating_sub(S2) as i32)
904 }
905 }
906 Ordering::Equal => {
907 Fixed::try_new_with_exponent(self.0.checked_add(other.0)?, (S2 - S0) as i32)
908 }
909 Ordering::Greater => {
910 let factor = pow10(S0 - S1);
911 if other.0 <= i128::MAX / factor / 10 {
912 Fixed::try_new_with_exponent(
913 self.0.checked_add(other.0 * factor)?,
914 S2 as i32 - S0 as i32,
915 )
916 } else {
917 let result = (I256::from_product(other.0, factor) + I256::from(self.0))
918 .narrowing_div(pow10(S2.saturating_sub(S0)))?;
919 Fixed::try_new_with_exponent(result, S0.saturating_sub(S2) as i32)
920 }
921 }
922 }
923 }
924
925 pub fn checked_sub_generic<
931 const P1: usize,
932 const S1: usize,
933 const P2: usize,
934 const S2: usize,
935 >(
936 self,
937 other: Fixed<P1, S1>,
938 ) -> Option<Fixed<P2, S2>> {
939 self.checked_add_generic(-other)
940 }
941
942 pub fn checked_mul_generic<
948 const P1: usize,
949 const S1: usize,
950 const P2: usize,
951 const S2: usize,
952 >(
953 self,
954 other: Fixed<P1, S1>,
955 ) -> Option<Fixed<P2, S2>> {
956 Fixed::<P2, S2>::try_new_with_exponent(
957 I256::from_product(self.0, other.0)
958 .narrowing_div(pow10((S0 + S1).saturating_sub(S2)))?,
959 S2.saturating_sub(S0 + S1) as i32,
960 )
961 }
962
963 pub fn checked_div_generic<
969 const P1: usize,
970 const S1: usize,
971 const P2: usize,
972 const S2: usize,
973 >(
974 self,
975 other: Fixed<P1, S1>,
976 ) -> Option<Fixed<P2, S2>> {
977 if other == 0 {
978 None
979 } else {
980 let shift_left = (S1 + S2).saturating_sub(S0);
981 if shift_left > 38 {
982 None
986 } else {
987 Fixed::try_new_with_exponent(
988 I256::from_product(self.0, pow10(shift_left)).narrowing_div(other.0)?,
989 S0.saturating_sub(S1 + S2) as i32,
990 )
991 }
992 }
993 }
994
995 pub fn strict_add_generic<
998 const P1: usize,
999 const S1: usize,
1000 const P2: usize,
1001 const S2: usize,
1002 >(
1003 self,
1004 other: Fixed<P1, S1>,
1005 ) -> Fixed<P2, S2> {
1006 self.checked_add_generic(other).unwrap()
1007 }
1008
1009 pub fn strict_sub_generic<
1012 const P1: usize,
1013 const S1: usize,
1014 const P2: usize,
1015 const S2: usize,
1016 >(
1017 self,
1018 other: Fixed<P1, S1>,
1019 ) -> Fixed<P2, S2> {
1020 self.checked_sub_generic(other).unwrap()
1021 }
1022
1023 pub fn strict_mul_generic<
1026 const P1: usize,
1027 const S1: usize,
1028 const P2: usize,
1029 const S2: usize,
1030 >(
1031 self,
1032 other: Fixed<P1, S1>,
1033 ) -> Fixed<P2, S2> {
1034 self.checked_mul_generic(other).unwrap()
1035 }
1036
1037 pub fn strict_div_generic<
1040 const P1: usize,
1041 const S1: usize,
1042 const P2: usize,
1043 const S2: usize,
1044 >(
1045 self,
1046 other: Fixed<P1, S1>,
1047 ) -> Fixed<P2, S2> {
1048 self.checked_div_generic(other).unwrap()
1049 }
1050}
1051
1052impl<const P: usize, const S: usize> Zero for Fixed<P, S> {
1053 fn zero() -> Self {
1054 Self::ZERO
1055 }
1056
1057 fn is_zero(&self) -> bool {
1058 *self == Self::ZERO
1059 }
1060}
1061
1062impl<const P: usize, const S: usize> One for Fixed<P, S> {
1063 fn one() -> Self {
1065 Self::ONE
1066 }
1067}
1068
1069impl<const P: usize, const S: usize> TryFrom<f64> for Fixed<P, S> {
1070 type Error = OutOfRange;
1071
1072 fn try_from(value: f64) -> Result<Self, Self::Error> {
1075 cast(value * Self::scale() as f64)
1076 .and_then(Self::try_new)
1077 .ok_or(OutOfRange)
1078 }
1079}
1080
1081impl<const P: usize, const S: usize> From<Fixed<P, S>> for f64 {
1082 fn from(value: Fixed<P, S>) -> Self {
1083 value.0 as f64 / Fixed::<P, S>::scale() as f64
1084 }
1085}
1086
1087impl<const P: usize, const S: usize> TryFrom<i128> for Fixed<P, S> {
1088 type Error = OutOfRange;
1089
1090 fn try_from(value: i128) -> Result<Self, Self::Error> {
1094 if value.unsigned_abs() <= Self::max_u128() {
1095 Ok(Self(value * Self::scale()))
1096 } else {
1097 Err(OutOfRange)
1098 }
1099 }
1100}
1101
1102macro_rules! try_from_signed_int {
1103 ($type_name:ty) => {
1104 impl<const P: usize, const S: usize> TryFrom<$type_name> for Fixed<P, S> {
1105 type Error = OutOfRange;
1106
1107 fn try_from(value: $type_name) -> Result<Self, Self::Error> {
1110 (value as i128).try_into()
1111 }
1112 }
1113 };
1114}
1115
1116try_from_signed_int!(isize);
1117try_from_signed_int!(i64);
1118try_from_signed_int!(i32);
1119try_from_signed_int!(i16);
1120try_from_signed_int!(i8);
1121
1122impl<const P: usize, const S: usize> TryFrom<u128> for Fixed<P, S> {
1123 type Error = OutOfRange;
1124
1125 fn try_from(value: u128) -> Result<Self, Self::Error> {
1129 if value <= Self::max_i128() as u128 {
1130 Ok(Self(value as i128 * Self::scale()))
1131 } else {
1132 Err(OutOfRange)
1133 }
1134 }
1135}
1136
1137macro_rules! try_from_unsigned_int {
1138 ($type_name:ty) => {
1139 impl<const P: usize, const S: usize> TryFrom<$type_name> for Fixed<P, S> {
1140 type Error = OutOfRange;
1141
1142 fn try_from(value: $type_name) -> Result<Self, Self::Error> {
1146 (value as u128).try_into()
1147 }
1148 }
1149 };
1150}
1151
1152try_from_unsigned_int!(usize);
1153try_from_unsigned_int!(u64);
1154try_from_unsigned_int!(u32);
1155try_from_unsigned_int!(u16);
1156try_from_unsigned_int!(u8);
1157
1158macro_rules! min_max_int {
1159 ($signed_type:ty, $max_signed:ident, $min_signed:ident, $unsigned_type:ty, $max_unsigned:ident) => {
1160 #[doc = "Returns the maximum `"]
1161 #[doc = stringify!($signed_type)]
1162 #[doc = "` that can be converted to this type."]
1163 pub const fn $max_signed() -> $signed_type {
1164 if Self::max_i128() > <$signed_type>::MAX as i128 {
1165 <$signed_type>::MAX
1166 } else {
1167 Self::max_i128() as $signed_type
1168 }
1169 }
1170
1171 #[doc = "Returns the minimum `"]
1172 #[doc = stringify!($signed_type)]
1173 #[doc = "` that can be converted to this type."]
1174 pub const fn $min_signed() -> $signed_type {
1175 -Self::$max_signed()
1176 }
1177
1178 #[doc = "Returns the maximum `"]
1179 #[doc = stringify!($unsigned_type)]
1180 #[doc = "` that can be converted to this type.\n\nThe minimum is 0."]
1181 pub const fn $max_unsigned() -> $unsigned_type {
1182 if Self::max_u128() > <$unsigned_type>::MAX as u128 {
1183 <$unsigned_type>::MAX
1184 } else {
1185 Self::max_u128() as $unsigned_type
1186 }
1187 }
1188 };
1189}
1190
1191impl<const P: usize, const S: usize> Fixed<P, S> {
1192 pub const fn max_i128() -> i128 {
1194 if P > S {
1195 pow10(P - S) - 1
1196 } else {
1197 0
1198 }
1199 }
1200
1201 pub const fn min_i128() -> i128 {
1203 -Self::max_i128()
1204 }
1205
1206 pub const fn max_u128() -> u128 {
1210 Self::max_i128().cast_unsigned()
1211 }
1212
1213 min_max_int!(isize, max_isize, min_isize, usize, max_usize);
1214 min_max_int!(i64, max_i64, min_i64, u64, max_u64);
1215 min_max_int!(i32, max_i32, min_i32, u32, max_u32);
1216 min_max_int!(i16, max_i16, min_i16, u16, max_u16);
1217 min_max_int!(i8, max_i8, min_i8, u8, max_u8);
1218}
1219
1220impl<const P: usize, const S: usize> From<Fixed<P, S>> for i128 {
1221 fn from(value: Fixed<P, S>) -> Self {
1224 value.0 / <Fixed<P, S>>::scale()
1226 }
1227}
1228
1229impl<const P: usize, const S: usize> Add for Fixed<P, S> {
1230 type Output = Self;
1231
1232 fn add(self, other: Self) -> Self::Output {
1238 self.checked_add(&other).unwrap()
1239 }
1240}
1241
1242impl<const P: usize, const S: usize> Add for &Fixed<P, S> {
1243 type Output = Fixed<P, S>;
1244
1245 fn add(self, other: Self) -> Self::Output {
1251 self.checked_add(other).unwrap()
1252 }
1253}
1254
1255impl<const P: usize, const S: usize> CheckedAdd for Fixed<P, S> {
1256 fn checked_add(&self, other: &Self) -> Option<Self> {
1259 self.checked_add_generic(*other)
1260 }
1261}
1262
1263impl<const P: usize, const S: usize> AddAssign for Fixed<P, S> {
1264 fn add_assign(&mut self, other: Self) {
1270 *self = *self + other;
1271 }
1272}
1273
1274impl<const P: usize, const S: usize> AddAssign<&Fixed<P, S>> for Fixed<P, S> {
1275 fn add_assign(&mut self, other: &Fixed<P, S>) {
1281 *self = *self + *other;
1282 }
1283}
1284
1285impl<const P: usize, const S: usize> Sub for Fixed<P, S> {
1286 type Output = Self;
1287
1288 fn sub(self, other: Self) -> Self::Output {
1294 self.checked_sub(&other).unwrap()
1295 }
1296}
1297
1298impl<const P: usize, const S: usize> Sub for &Fixed<P, S> {
1299 type Output = Fixed<P, S>;
1300
1301 fn sub(self, other: Self) -> Self::Output {
1307 self.checked_sub(other).unwrap()
1308 }
1309}
1310
1311impl<const P: usize, const S: usize> CheckedSub for Fixed<P, S> {
1312 fn checked_sub(&self, other: &Self) -> Option<Self> {
1315 self.checked_sub_generic(*other)
1316 }
1317}
1318
1319impl<const P: usize, const S: usize> SubAssign for Fixed<P, S> {
1320 fn sub_assign(&mut self, other: Self) {
1326 *self = *self - other;
1327 }
1328}
1329
1330impl<const P: usize, const S: usize> Mul for Fixed<P, S> {
1331 type Output = Self;
1332
1333 fn mul(self, other: Self) -> Self::Output {
1339 self.checked_mul(&other).unwrap()
1340 }
1341}
1342
1343impl<const P: usize, const S: usize> Mul for &Fixed<P, S> {
1344 type Output = Fixed<P, S>;
1345
1346 fn mul(self, other: Self) -> Self::Output {
1352 self.checked_mul(other).unwrap()
1353 }
1354}
1355
1356impl<const P: usize, const S: usize> CheckedMul for Fixed<P, S> {
1357 fn checked_mul(&self, other: &Self) -> Option<Self> {
1360 Self::checked_mul_generic(*self, *other)
1361 }
1362}
1363
1364impl<const P: usize, const S: usize> MulAssign for Fixed<P, S> {
1365 fn mul_assign(&mut self, other: Self) {
1371 *self = *self * other;
1372 }
1373}
1374
1375impl<const P: usize, const S: usize> Div for Fixed<P, S> {
1376 type Output = Self;
1377
1378 fn div(self, other: Self) -> Self::Output {
1384 self.checked_div(&other).unwrap()
1385 }
1386}
1387
1388impl<const P: usize, const S: usize> Div for &Fixed<P, S> {
1389 type Output = Fixed<P, S>;
1390
1391 fn div(self, other: Self) -> Self::Output {
1397 self.checked_div(other).unwrap()
1398 }
1399}
1400
1401impl<const P: usize, const S: usize> CheckedDiv for Fixed<P, S> {
1402 fn checked_div(&self, other: &Self) -> Option<Self> {
1405 Self::checked_div_generic(*self, *other)
1406 }
1407}
1408
1409impl<const P: usize, const S: usize> DivAssign for Fixed<P, S> {
1410 fn div_assign(&mut self, other: Self) {
1416 *self = *self / other;
1417 }
1418}
1419
1420impl<const P: usize, const S: usize> Neg for Fixed<P, S> {
1421 type Output = Self;
1422
1423 fn neg(self) -> Self::Output {
1425 Self(-self.0)
1426 }
1427}
1428
1429impl<const P: usize, const S: usize> Neg for &Fixed<P, S> {
1430 type Output = Fixed<P, S>;
1431
1432 fn neg(self) -> Self::Output {
1434 Fixed(-self.0)
1435 }
1436}
1437
1438#[derive(Copy, Clone, Debug)]
1439pub struct ParseFixedError;
1440
1441impl<const P: usize, const S: usize> FromStr for Fixed<P, S> {
1442 type Err = ParseFixedError;
1443
1444 fn from_str(s: &str) -> Result<Self, Self::Err> {
1451 fn inner(s: &str, scale: i32) -> Option<(i128, i32)> {
1453 let mut value = 0;
1456 let mut exponent = scale;
1457
1458 let mut saw_dot = false;
1459 let mut saw_digit = false;
1460
1461 let mut sign = None;
1462 enum Sign {
1463 Positive,
1464 Negative,
1465 }
1466
1467 let mut iter = s.chars();
1468 while let Some(c) = iter.next() {
1469 match c {
1470 '-' | '+' if sign.is_some() => return None,
1471 '-' => {
1472 sign = Some(Sign::Negative);
1473 }
1474 '+' => {
1475 sign = Some(Sign::Positive);
1476 }
1477 '0'..='9' => {
1478 saw_digit = true;
1479 if value < i128::MAX / 10 {
1480 value = value * 10 + (c as u8 - b'0') as i128;
1481 if saw_dot {
1482 exponent = exponent.checked_sub(1)?;
1483 }
1484 } else if !saw_dot {
1485 exponent = exponent.checked_add(1)?;
1486 }
1487 }
1488 '.' => {
1489 if saw_dot {
1490 return None;
1491 }
1492 saw_dot = true;
1493 }
1494 'e' | 'E' => {
1495 exponent = exponent.checked_add(iter.as_str().parse().ok()?)?;
1496 break;
1497 }
1498 _ => return None,
1499 }
1500 }
1501 if !saw_digit {
1502 return None;
1503 }
1504 let value = match sign {
1505 Some(Sign::Negative) => -value,
1506 _ => value,
1507 };
1508 Some((value, exponent))
1509 }
1510
1511 inner(s, S as i32)
1512 .and_then(|(value, exponent)| Self::try_new_with_exponent_round_even(value, exponent))
1513 .ok_or(ParseFixedError)
1514 }
1515}
1516
1517fn _invalid_constant_test() {}
1527
1528#[cfg(test)]
1529mod test {
1530 use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub};
1531
1532 use crate::Fixed;
1533 use std::{fmt::Write, str::FromStr};
1534
1535 #[test]
1536 fn from_str() {
1537 for (s, f) in [
1538 ("0", Some(0.0)),
1539 ("0.", Some(0.0)),
1540 (".0", Some(0.0)),
1541 ("-0", Some(-0.0)),
1542 ("+0", Some(-0.0)),
1543 ("--0", None),
1544 ("-+0", None),
1545 ("0x", None),
1546 ("0e5x", None),
1547 ("1.23", Some(1.23)),
1548 ("-1.23", Some(-1.23)),
1549 ("+1.23", Some(1.23)),
1550 ("99999999", Some(9999_9999.0)),
1551 ("999999999", None),
1552 ("999999999E-1", Some(9999_9999.9)),
1553 ("9999999999e-1", None),
1554 ("9999999999E-2", Some(9999_9999.99)),
1555 ("99999999999e-2", None),
1556 ("99999999999e-3", None),
1559 ("99999999991e-3", Some(9999_9999.99)),
1561 (
1565 "111111111111111111111111111111111111111111e-34",
1566 Some(1111_1111.11),
1567 ),
1568 (
1572 "1.23456788901234567890123456789012345678890123456",
1573 Some(1.23),
1574 ),
1575 ("123e5", Some(12_300_000.0)),
1576 ("123E4", Some(1_230_000.0)),
1577 ("123e3", Some(123_000.0)),
1578 ("123e2", Some(12_300.0)),
1579 ("123e1", Some(1_230.0)),
1580 ("123e0", Some(123.0)),
1581 ("123e-1", Some(12.3)),
1582 ("123e-2", Some(1.23)),
1583 (".123", Some(0.12)),
1584 (".124", Some(0.12)),
1585 (".125", Some(0.12)),
1586 (".126", Some(0.13)),
1587 (".133", Some(0.13)),
1588 (".134", Some(0.13)),
1589 (".135", Some(0.14)),
1590 (".136", Some(0.14)),
1591 ] {
1592 println!("{s}: {:?}", s.parse::<F>());
1593 assert_eq!(s.parse::<F>().ok(), f.map(|f| F::try_from(f).unwrap()));
1594 }
1595 }
1596
1597 fn multidisplay<const P: usize, const S: usize>(number: Fixed<P, S>) -> String {
1598 let mut s = String::new();
1599 write!(&mut s, "{number}").unwrap();
1600 for precision in 0..=S + 1 {
1601 write!(&mut s, " {number:.0$}", precision).unwrap();
1602 }
1603 s
1604 }
1605
1606 #[test]
1607 fn display() {
1608 assert_eq!(
1609 multidisplay(Fixed::<20, 7>::try_from(1.682501).unwrap()),
1610 "1.682501 2 1.7 1.68 1.683 1.6825 1.68250 1.682501 1.6825010 1.68250100"
1611 );
1612 assert_eq!(
1613 multidisplay(Fixed::<20, 4>::try_from(1.6825).unwrap()),
1614 "1.6825 2 1.7 1.68 1.682 1.6825 1.68250"
1615 );
1616 assert_eq!(
1617 multidisplay(Fixed::<20, 6>::try_from(1.995670).unwrap()),
1618 "1.99567 2 2.0 2.00 1.996 1.9957 1.99567 1.995670 1.9956700"
1619 );
1620 assert_eq!(
1621 multidisplay(Fixed::<20, 6>::try_from(0.995670).unwrap()),
1622 "0.99567 1 1.0 1.00 0.996 0.9957 0.99567 0.995670 0.9956700"
1623 );
1624 assert_eq!(
1625 multidisplay(Fixed::<6, 6>::try_from(0.995670).unwrap()),
1626 "0.99567 1 1.0 1.00 0.996 0.9957 0.99567 0.995670 0.9956700"
1627 );
1628
1629 assert_eq!(
1630 multidisplay(Fixed::<20, 7>::try_from(-1.682501).unwrap()),
1631 "-1.682501 -2 -1.7 -1.68 -1.683 -1.6825 -1.68250 -1.682501 -1.6825010 -1.68250100"
1632 );
1633 assert_eq!(
1634 multidisplay(Fixed::<20, 4>::try_from(-1.6825).unwrap()),
1635 "-1.6825 -2 -1.7 -1.68 -1.682 -1.6825 -1.68250"
1636 );
1637 assert_eq!(
1638 multidisplay(Fixed::<20, 6>::try_from(-1.995670).unwrap()),
1639 "-1.99567 -2 -2.0 -2.00 -1.996 -1.9957 -1.99567 -1.995670 -1.9956700"
1640 );
1641 assert_eq!(
1642 multidisplay(Fixed::<20, 6>::try_from(-0.995670).unwrap()),
1643 "-0.99567 -1 -1.0 -1.00 -0.996 -0.9957 -0.99567 -0.995670 -0.9956700"
1644 );
1645 }
1646
1647 type F = Fixed<10, 2>;
1648 fn f(n: f64) -> F {
1649 Fixed::try_from(n).unwrap()
1650 }
1651
1652 fn f38_0(n: f64) -> Fixed<38, 0> {
1653 Fixed::try_from(n).unwrap()
1654 }
1655
1656 fn f38_38(s: &str) -> Fixed<38, 38> {
1657 Fixed::from_str(s).unwrap()
1658 }
1659
1660 #[test]
1661 fn mul() {
1662 assert_eq!(f(1.23) * f(2.34), f(2.87));
1664 assert_eq!(f(-1.23) * f(2.34), f(-2.87));
1665 assert_eq!(f(1.23) * f(-2.34), f(-2.87));
1666 assert_eq!(f(-1.23) * f(-2.34), f(2.87));
1667
1668 for a in -999..=999 {
1670 let af: Fixed<10, 2> = Fixed(a);
1671 for b in -999..=999 {
1672 let bf: Fixed<10, 2> = Fixed(b);
1673 assert_eq!(af * bf, Fixed::<10, 2>(a * b / 100));
1674 }
1675 }
1676
1677 for a in -999..=999 {
1679 let af: Fixed<3, 2> = Fixed(a);
1680 for b in -999..=999 {
1681 let bf: Fixed<3, 2> = Fixed(b);
1682 let c = a * b / 100;
1683 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1684 assert_eq!(af.checked_mul(&bf), expected);
1685 }
1686 }
1687 }
1688
1689 #[test]
1690 fn mul_generic() {
1691 for a in -999..=999 {
1692 let af: Fixed<10, 2> = Fixed(a);
1693 for b in -999..=999 {
1694 let bf: Fixed<10, 3> = Fixed(b);
1695 let cf: Fixed<10, 5> = af.checked_mul_generic(bf).unwrap();
1696 assert_eq!(cf, Fixed::<10, 5>(a * b));
1697 let df: Fixed<10, 6> = af.checked_mul_generic(bf).unwrap();
1698 assert_eq!(df, Fixed::<10, 6>(a * b * 10));
1699 let ef: Fixed<10, 0> = af.checked_mul_generic(bf).unwrap();
1700 assert_eq!(ef, Fixed::<10, 0>(a * b / 100_000));
1701 }
1702 }
1703 }
1704
1705 #[test]
1706 fn div() {
1707 assert_eq!(f(1.23) / f(2.34), f(0.52));
1709 assert_eq!(f(-1.23) / f(2.34), f(-0.52));
1710 assert_eq!(f(1.23) / f(-2.34), f(-0.52));
1711 assert_eq!(f(-1.23) / f(-2.34), f(0.52));
1712 assert_eq!(
1713 f38_0(1.0)
1714 .checked_div_generic::<38, 0, 38, 38>(f38_0(7.0))
1715 .unwrap(),
1716 f38_38("0.14285714285714285714285714285714285714")
1717 );
1718
1719 assert_eq!(
1720 f38_0(123.0).checked_div_generic::<38, 38, 38, 38>(f38_38("0.456")),
1721 None
1722 );
1723
1724 for a in -999..=999 {
1726 let af: Fixed<10, 2> = Fixed(a);
1727 for b in -999..=999 {
1728 let bf: Fixed<10, 2> = Fixed(b);
1729 assert_eq!(af.checked_div(&bf), (b != 0).then(|| Fixed(a * 100 / b)));
1730 }
1731 }
1732
1733 for a in -999..=999 {
1735 let af: Fixed<3, 2> = Fixed(a);
1736 for b in -999..=999 {
1737 let bf: Fixed<3, 2> = Fixed(b);
1738 let expected = if b != 0 {
1739 let result = a * 100 / b;
1740 (result.unsigned_abs() <= 999).then_some(Fixed(result))
1741 } else {
1742 None
1743 };
1744 assert_eq!(af.checked_div(&bf), expected);
1745 }
1746 }
1747 }
1748
1749 #[test]
1750 fn div_generic() {
1751 for a in -999..=999 {
1752 let af: Fixed<10, 2> = Fixed(a);
1753 for b in -999..=999 {
1754 if b != 0 {
1755 let bf: Fixed<10, 3> = Fixed(b);
1756 let cf: Fixed<10, 5> = af.checked_div_generic(bf).unwrap();
1757 assert_eq!(cf, Fixed::<10, 5>(a * 1_000_000 / b));
1758 let df: Fixed<10, 6> = af.checked_div_generic(bf).unwrap();
1759 assert_eq!(df, Fixed::<10, 6>(a * 10_000_000 / b));
1760 let ef: Fixed<10, 0> = af.checked_div_generic(bf).unwrap();
1761 assert_eq!(ef, Fixed::<10, 0>(a * 10 / b));
1762 }
1763 }
1764 }
1765 }
1766
1767 #[test]
1768 fn add() {
1769 assert_eq!(f(1.23) + f(2.34), f(3.57));
1771 assert_eq!(f(-1.23) + f(2.34), f(1.11));
1772 assert_eq!(f(1.23) + f(-2.34), f(-1.11));
1773 assert_eq!(f(-1.23) + f(-2.34), f(-3.57));
1774
1775 for a in -999..=999 {
1777 let af: Fixed<10, 2> = Fixed(a);
1778 for b in -999..=999 {
1779 let bf: Fixed<10, 2> = Fixed(b);
1780 assert_eq!(af + bf, Fixed::<10, 2>(a + b));
1781 }
1782 }
1783
1784 for a in -999..=999 {
1786 let af: Fixed<3, 2> = Fixed(a);
1787 for b in -999..=999 {
1788 let bf: Fixed<3, 2> = Fixed(b);
1789 let c = a + b;
1790 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1791 assert_eq!(af.checked_add(&bf), expected);
1792 }
1793 }
1794
1795 for a in -999..=999 {
1797 let af: Fixed<10, 2> = Fixed(a);
1798 for b in -999..=999 {
1799 let bf: Fixed<10, 3> = Fixed(b);
1800 let cf: Fixed<10, 5> = af.checked_add_generic(bf).unwrap();
1801 assert_eq!(
1802 cf,
1803 Fixed::<10, 5>(a * 1000 + b * 100),
1804 "{af} + {bf} ?= {cf}"
1805 );
1806 let cf: Fixed<10, 5> = bf.checked_add_generic(af).unwrap();
1807 assert_eq!(
1808 cf,
1809 Fixed::<10, 5>(a * 1000 + b * 100),
1810 "{bf} + {af} ?= {cf}"
1811 );
1812 let df: Fixed<10, 6> = af.checked_add_generic(bf).unwrap();
1813 assert_eq!(
1814 df,
1815 Fixed::<10, 6>(a * 10_000 + b * 1000),
1816 "{af} + {bf} ?= {df}"
1817 );
1818 let ef: Fixed<10, 0> = af.checked_add_generic(bf).unwrap();
1819 assert_eq!(
1820 ef,
1821 Fixed::<10, 0>((a * 10 + b) / 1000),
1822 "{af} + {bf} ?= {ef}"
1823 );
1824 }
1825 }
1826 }
1827
1828 #[test]
1829 fn sub() {
1830 assert_eq!(f(1.23) - f(2.34), f(-1.11));
1832 assert_eq!(f(-1.23) - f(2.34), f(-3.57));
1833 assert_eq!(f(1.23) - f(-2.34), f(3.57));
1834 assert_eq!(f(-1.23) - f(-2.34), f(1.11));
1835
1836 for a in -999..=999 {
1838 let af: Fixed<10, 2> = Fixed(a);
1839 for b in -999..=999 {
1840 let bf: Fixed<10, 2> = Fixed(b);
1841 assert_eq!(af - bf, Fixed::<10, 2>(a - b));
1842 }
1843 }
1844
1845 for a in -999..=999 {
1847 let af: Fixed<3, 2> = Fixed(a);
1848 for b in -999..=999 {
1849 let bf: Fixed<3, 2> = Fixed(b);
1850 let c = a - b;
1851 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1852 assert_eq!(af.checked_sub(&bf), expected);
1853 }
1854 }
1855
1856 for a in -999..=999 {
1858 let af: Fixed<10, 2> = Fixed(a);
1859 for b in -999..=999 {
1860 let bf: Fixed<10, 3> = Fixed(b);
1861 let cf: Fixed<10, 5> = af.checked_sub_generic(bf).unwrap();
1862 assert_eq!(
1863 cf,
1864 Fixed::<10, 5>(a * 1000 - b * 100),
1865 "{af} - {bf} ?= {cf}"
1866 );
1867 let cf: Fixed<10, 5> = bf.checked_sub_generic(af).unwrap();
1868 assert_eq!(
1869 cf,
1870 Fixed::<10, 5>(b * 100 - a * 1000),
1871 "{bf} - {af} ?= {cf}"
1872 );
1873 let df: Fixed<10, 6> = af.checked_sub_generic(bf).unwrap();
1874 assert_eq!(df, Fixed::<10, 6>(a * 10_000 - b * 1000));
1875 }
1876 }
1877 }
1878
1879 #[test]
1880 fn powi() {
1881 assert_eq!(
1882 Fixed::<10, 8>::from_str("1.12345678")
1883 .unwrap()
1884 .powi(8)
1885 .to_string()
1886 .as_str(),
1887 "2.53776238"
1888 );
1889 assert_eq!(f(2.0).powi(3), f(8.0));
1890 assert_eq!(f(-2.0).powi(3), f(-8.0));
1891 assert_eq!(f(1.7).powi(8), f(69.75));
1892 assert_eq!(f(1.7).powi(-8), f(0.01));
1893 assert_eq!(f(0.0).powi(1), f(0.0));
1894 assert_eq!(f(0.0).checked_powi(0), None);
1895 assert_eq!(f(0.0).checked_powi(-1), None);
1896 }
1897
1898 #[test]
1899 fn convert() {
1900 let a = Fixed::<10, 10>::from_str("0.0123456789").unwrap();
1901 assert_eq!(&a.convert::<10, 0>().unwrap().to_string(), "0");
1902 assert_eq!(&a.convert::<10, 1>().unwrap().to_string(), "0");
1903 assert_eq!(&a.convert::<10, 2>().unwrap().to_string(), "0.01");
1904 assert_eq!(&a.convert::<10, 3>().unwrap().to_string(), "0.012");
1905 assert_eq!(&a.convert::<10, 4>().unwrap().to_string(), "0.0123");
1906 assert_eq!(&a.convert::<10, 5>().unwrap().to_string(), "0.01234");
1907 assert_eq!(&a.convert::<10, 6>().unwrap().to_string(), "0.012345");
1908 assert_eq!(&a.convert::<10, 7>().unwrap().to_string(), "0.0123456");
1909 assert_eq!(&a.convert::<10, 8>().unwrap().to_string(), "0.01234567");
1910 assert_eq!(&a.convert::<10, 9>().unwrap().to_string(), "0.012345678");
1911 assert_eq!(&a.convert::<10, 10>().unwrap().to_string(), "0.0123456789");
1912 assert_eq!(&a.convert_round_even::<10, 0>().unwrap().to_string(), "0");
1913 assert_eq!(&a.convert_round_even::<10, 1>().unwrap().to_string(), "0");
1914 assert_eq!(
1915 &a.convert_round_even::<10, 2>().unwrap().to_string(),
1916 "0.01"
1917 );
1918 assert_eq!(
1919 &a.convert_round_even::<10, 3>().unwrap().to_string(),
1920 "0.012"
1921 );
1922 assert_eq!(
1923 &a.convert_round_even::<10, 4>().unwrap().to_string(),
1924 "0.0123"
1925 );
1926 assert_eq!(
1927 &a.convert_round_even::<10, 5>().unwrap().to_string(),
1928 "0.01235"
1929 );
1930 assert_eq!(
1931 &a.convert_round_even::<10, 6>().unwrap().to_string(),
1932 "0.012346"
1933 );
1934 assert_eq!(
1935 &a.convert_round_even::<10, 7>().unwrap().to_string(),
1936 "0.0123457"
1937 );
1938 assert_eq!(
1939 &a.convert_round_even::<10, 8>().unwrap().to_string(),
1940 "0.01234568"
1941 );
1942 assert_eq!(
1943 &a.convert_round_even::<10, 9>().unwrap().to_string(),
1944 "0.012345679"
1945 );
1946 assert_eq!(
1947 &a.convert_round_even::<10, 10>().unwrap().to_string(),
1948 "0.0123456789"
1949 );
1950
1951 let b = Fixed::<10, 5>::from_str("12345.67895").unwrap();
1952 assert_eq!(&b.convert::<10, 0>().unwrap().to_string(), "12345");
1953 assert_eq!(&b.convert::<10, 1>().unwrap().to_string(), "12345.6");
1954 assert_eq!(&b.convert::<10, 2>().unwrap().to_string(), "12345.67");
1955 assert_eq!(&b.convert::<10, 3>().unwrap().to_string(), "12345.678");
1956 assert_eq!(&b.convert::<10, 4>().unwrap().to_string(), "12345.6789");
1957 assert_eq!(&b.convert::<10, 5>().unwrap().to_string(), "12345.67895");
1958 assert_eq!(b.convert::<10, 6>(), None);
1959 assert_eq!(b.convert::<10, 7>(), None);
1960 assert_eq!(b.convert::<10, 8>(), None);
1961 assert_eq!(b.convert::<10, 9>(), None);
1962 assert_eq!(b.convert::<10, 10>(), None);
1963 assert_eq!(
1964 &b.convert_round_even::<10, 0>().unwrap().to_string(),
1965 "12346"
1966 );
1967 assert_eq!(
1968 &b.convert_round_even::<10, 1>().unwrap().to_string(),
1969 "12345.7"
1970 );
1971 assert_eq!(
1972 &b.convert_round_even::<10, 2>().unwrap().to_string(),
1973 "12345.68"
1974 );
1975 assert_eq!(
1976 &b.convert_round_even::<10, 3>().unwrap().to_string(),
1977 "12345.679"
1978 );
1979 assert_eq!(
1980 &b.convert_round_even::<10, 4>().unwrap().to_string(),
1981 "12345.679"
1982 );
1983 assert_eq!(
1984 &b.convert_round_even::<10, 5>().unwrap().to_string(),
1985 "12345.67895"
1986 );
1987 assert_eq!(b.convert_round_even::<10, 6>(), None);
1988 assert_eq!(b.convert_round_even::<10, 7>(), None);
1989 assert_eq!(b.convert_round_even::<10, 8>(), None);
1990 assert_eq!(b.convert_round_even::<10, 9>(), None);
1991 assert_eq!(b.convert_round_even::<10, 10>(), None);
1992 }
1993
1994 #[test]
1995 fn constants() {
1996 assert_eq!(Fixed::<5, 0>::MAX, Fixed::<5, 0>(99999));
1997 assert_eq!(Fixed::<5, 0>::MIN, Fixed::<5, 0>(-99999));
1998 assert_eq!(Fixed::<5, 0>::ZERO, Fixed::<5, 0>(0));
1999 assert_eq!(Fixed::<5, 0>::ONE, Fixed::<5, 0>(1));
2000
2001 assert_eq!(Fixed::<5, 1>::MAX, Fixed::<5, 1>(99999));
2002 assert_eq!(Fixed::<5, 1>::MIN, Fixed::<5, 1>(-99999));
2003 assert_eq!(Fixed::<5, 1>::ZERO, Fixed::<5, 1>(0));
2004 assert_eq!(Fixed::<5, 1>::ONE, Fixed::<5, 1>(10));
2005
2006 assert_eq!(Fixed::<5, 2>::MAX, Fixed::<5, 2>(99999));
2007 assert_eq!(Fixed::<5, 2>::MIN, Fixed::<5, 2>(-99999));
2008 assert_eq!(Fixed::<5, 2>::ZERO, Fixed::<5, 2>(0));
2009 assert_eq!(Fixed::<5, 2>::ONE, Fixed::<5, 2>(100));
2010
2011 assert_eq!(Fixed::<5, 3>::MAX, Fixed::<5, 3>(99999));
2012 assert_eq!(Fixed::<5, 3>::MIN, Fixed::<5, 3>(-99999));
2013 assert_eq!(Fixed::<5, 3>::ZERO, Fixed::<5, 3>(0));
2014 assert_eq!(Fixed::<5, 3>::ONE, Fixed::<5, 3>(1000));
2015
2016 assert_eq!(Fixed::<5, 4>::MAX, Fixed::<5, 4>(99999));
2017 assert_eq!(Fixed::<5, 4>::MIN, Fixed::<5, 4>(-99999));
2018 assert_eq!(Fixed::<5, 4>::ZERO, Fixed::<5, 4>(0));
2019 assert_eq!(Fixed::<5, 4>::ONE, Fixed::<5, 4>(10000));
2020
2021 assert_eq!(Fixed::<5, 5>::MAX, Fixed::<5, 5>(99999));
2022 assert_eq!(Fixed::<5, 5>::MIN, Fixed::<5, 5>(-99999));
2023 assert_eq!(Fixed::<5, 5>::ZERO, Fixed::<5, 5>(0));
2024 }
2027
2028 #[test]
2029 fn floor() {
2030 assert_eq!(f(5.0).floor(), f(5.0));
2031 assert_eq!(f(5.1).floor(), f(5.0));
2032 assert_eq!(f(5.5).floor(), f(5.0));
2033 assert_eq!(f(5.9).floor(), f(5.0));
2034 assert_eq!(f(-5.0).floor(), f(-5.0));
2035 assert_eq!(f(-5.1).floor(), f(-6.0));
2036 assert_eq!(f(-5.5).floor(), f(-6.0));
2037 assert_eq!(f(-5.6).floor(), f(-6.0));
2038 assert_eq!(f(4.0).floor(), f(4.0));
2039 assert_eq!(f(4.1).floor(), f(4.0));
2040 assert_eq!(f(4.5).floor(), f(4.0));
2041 assert_eq!(f(4.9).floor(), f(4.0));
2042 assert_eq!(f(-4.0).floor(), f(-4.0));
2043 assert_eq!(f(-4.1).floor(), f(-5.0));
2044 assert_eq!(f(-4.5).floor(), f(-5.0));
2045 assert_eq!(f(-4.6).floor(), f(-5.0));
2046 assert_eq!(f(-99_999_999.0).floor(), f(-99_999_999.0));
2047 assert_eq!(f(-99_999_999.1).checked_floor(), None);
2048 assert_eq!(f(-99_999_999.5).checked_floor(), None);
2049 assert_eq!(f(-99_999_999.6).checked_floor(), None);
2050 }
2051
2052 #[test]
2053 fn ceil() {
2054 assert_eq!(f(5.0).ceil(), f(5.0));
2055 assert_eq!(f(5.1).ceil(), f(6.0));
2056 assert_eq!(f(5.5).ceil(), f(6.0));
2057 assert_eq!(f(5.9).ceil(), f(6.0));
2058 assert_eq!(f(-5.0).ceil(), f(-5.0));
2059 assert_eq!(f(-5.1).ceil(), f(-5.0));
2060 assert_eq!(f(-5.5).ceil(), f(-5.0));
2061 assert_eq!(f(-5.6).ceil(), f(-5.0));
2062 assert_eq!(f(4.0).ceil(), f(4.0));
2063 assert_eq!(f(4.1).ceil(), f(5.0));
2064 assert_eq!(f(4.5).ceil(), f(5.0));
2065 assert_eq!(f(4.9).ceil(), f(5.0));
2066 assert_eq!(f(-4.0).ceil(), f(-4.0));
2067 assert_eq!(f(-4.1).ceil(), f(-4.0));
2068 assert_eq!(f(-4.5).ceil(), f(-4.0));
2069 assert_eq!(f(-4.6).ceil(), f(-4.0));
2070 assert_eq!(f(99_999_999.0).ceil(), f(99_999_999.0));
2071 assert_eq!(f(99_999_999.1).checked_ceil(), None);
2072 assert_eq!(f(99_999_999.5).checked_ceil(), None);
2073 assert_eq!(f(99_999_999.6).checked_ceil(), None);
2074 }
2075
2076 #[test]
2077 fn truncate() {
2078 assert_eq!(f(5.0).truncate(), f(5.0));
2079 assert_eq!(f(5.1).truncate(), f(5.0));
2080 assert_eq!(f(5.5).truncate(), f(5.0));
2081 assert_eq!(f(5.9).truncate(), f(5.0));
2082 assert_eq!(f(-5.0).truncate(), f(-5.0));
2083 assert_eq!(f(-5.1).truncate(), f(-5.0));
2084 assert_eq!(f(-5.5).truncate(), f(-5.0));
2085 assert_eq!(f(-5.6).truncate(), f(-5.0));
2086 assert_eq!(f(4.0).truncate(), f(4.0));
2087 assert_eq!(f(4.1).truncate(), f(4.0));
2088 assert_eq!(f(4.5).truncate(), f(4.0));
2089 assert_eq!(f(4.9).truncate(), f(4.0));
2090 assert_eq!(f(-4.0).truncate(), f(-4.0));
2091 assert_eq!(f(-4.1).truncate(), f(-4.0));
2092 assert_eq!(f(-4.5).truncate(), f(-4.0));
2093 assert_eq!(f(-4.6).truncate(), f(-4.0));
2094 assert_eq!(f(99_999_999.0).truncate(), f(99_999_999.0));
2095 assert_eq!(f(99_999_999.1).truncate(), f(99_999_999.0));
2096 assert_eq!(f(99_999_999.5).truncate(), f(99_999_999.0));
2097 assert_eq!(f(99_999_999.6).truncate(), f(99_999_999.0));
2098 assert_eq!(f(-99_999_999.0).truncate(), f(-99_999_999.0));
2099 assert_eq!(f(-99_999_999.1).truncate(), f(-99_999_999.0));
2100 assert_eq!(f(-99_999_999.5).truncate(), f(-99_999_999.0));
2101 assert_eq!(f(-99_999_999.6).truncate(), f(-99_999_999.0));
2102 }
2103
2104 #[test]
2105 fn sign() {
2106 assert_eq!(f(-0.1).sign(), Fixed::<1, 0>::try_from(-1).unwrap());
2107 assert_eq!(f(0.0).sign(), Fixed::<1, 0>::try_from(0).unwrap());
2108 assert_eq!(f(0.5).sign(), Fixed::<1, 0>::try_from(1).unwrap());
2109 }
2110
2111 #[test]
2112 fn sqrt() {
2113 assert_eq!(f(0.0).sqrt(), f(0.0));
2115 assert_eq!(f(1.0).sqrt(), f(1.0));
2116 assert_eq!(f(2.0).sqrt(), f(1.41));
2117 assert_eq!(f(3.0).sqrt(), f(1.73));
2118 assert_eq!(f(4.0).sqrt(), f(2.0));
2119 assert_eq!(f(-1.0).checked_sqrt(), None);
2120
2121 for a in 0..=999 {
2123 let af: Fixed<10, 2> = Fixed(a);
2124 assert_eq!(af.sqrt(), Fixed::<10, 2>((a * 100).isqrt()));
2125 }
2126 }
2127
2128 #[test]
2129 fn nullable() {
2130 fn nullable_checked_add_generic<
2133 const PA: usize,
2134 const SA: usize,
2135 const PB: usize,
2136 const SB: usize,
2137 const PC: usize,
2138 const SC: usize,
2139 >(
2140 a: Option<Fixed<PA, SA>>,
2141 b: Option<Fixed<PB, SB>>,
2142 ) -> Option<Fixed<PC, SC>> {
2143 a.zip(b).and_then(|(a, b)| a.checked_add_generic(b))
2144 }
2145
2146 let a: Option<Fixed<10, 2>> = Some("1.23".parse().unwrap());
2147 let b: Option<Fixed<5, 4>> = Some("4.5678".parse().unwrap());
2148 let c: Option<Fixed<10, 4>> = nullable_checked_add_generic(a, b);
2149 assert_eq!(c, Some("5.7978".parse().unwrap()));
2150 }
2151}