1use std::{
2 cmp::Ordering,
3 fmt::{Debug, Display},
4 ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
5 str::FromStr,
6};
7
8use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, Zero, cast};
9
10use crate::{
11 Halfway, OutOfRange, ParseDecimalError, checked_pow10, debug_decimal, display_decimal,
12 div_ceil, div_floor, i128_mul_pow10_round_even, parse_decimal, pow10, round_inner, u256::I256,
13};
14
15#[derive(Copy, Clone, Default, Eq, Ord, Hash)]
41#[cfg_attr(feature = "size_of", derive(size_of::SizeOf))]
42pub struct Fixed<const P: usize, const S: usize>(pub(super) i128);
43
44impl<const P0: usize, const S0: usize, const P1: usize, const S1: usize> PartialEq<Fixed<P1, S1>>
45 for Fixed<P0, S0>
46{
47 fn eq(&self, other: &Fixed<P1, S1>) -> bool {
48 match S0.cmp(&S1) {
49 Ordering::Less => I256::from_product(self.0, pow10(S1 - S0)) == I256::from(other.0),
50 Ordering::Equal => self.0 == other.0,
51 Ordering::Greater => I256::from(self.0) == I256::from_product(other.0, pow10(S0 - S1)),
52 }
53 }
54}
55
56macro_rules! partial_eq_int {
57 ($type_name:ty) => {
58 impl<const P0: usize, const S0: usize> PartialEq<$type_name> for Fixed<P0, S0> {
59 fn eq(&self, other: &$type_name) -> bool {
60 self.0 % Self::scale() == 0 && self.0 / Self::scale() == *other as i128
61 }
62 }
63 };
64}
65partial_eq_int!(i8);
66partial_eq_int!(i16);
67partial_eq_int!(i32);
68partial_eq_int!(i64);
69partial_eq_int!(i128);
70partial_eq_int!(isize);
71partial_eq_int!(u8);
72partial_eq_int!(u16);
73partial_eq_int!(u32);
74partial_eq_int!(u64);
75
76impl<const P0: usize, const S0: usize> PartialEq<u128> for Fixed<P0, S0> {
77 fn eq(&self, other: &u128) -> bool {
78 self.0 >= 0
79 && self.0 % Self::scale() == 0
80 && (self.0 / Self::scale()).cast_unsigned() == *other
81 }
82}
83
84impl<const P0: usize, const S0: usize> PartialEq<usize> for Fixed<P0, S0> {
85 fn eq(&self, other: &usize) -> bool {
86 self.0 >= 0
87 && self.0 % Self::scale() == 0
88 && (self.0 / Self::scale()).cast_unsigned() == *other as u128
89 }
90}
91
92impl<const P0: usize, const S0: usize, const P1: usize, const S1: usize> PartialOrd<Fixed<P1, S1>>
93 for Fixed<P0, S0>
94{
95 fn partial_cmp(&self, other: &Fixed<P1, S1>) -> Option<Ordering> {
96 match S0.cmp(&S1) {
97 Ordering::Less => {
98 I256::from_product(self.0, pow10(S1 - S0)).partial_cmp(&I256::from(other.0))
99 }
100 Ordering::Equal => self.0.partial_cmp(&other.0),
101 Ordering::Greater => {
102 I256::from(self.0).partial_cmp(&I256::from_product(other.0, pow10(S0 - S1)))
103 }
104 }
105 }
106}
107
108impl<const P: usize, const S: usize> Fixed<P, S> {
109 pub const MAX: Self = Self(pow10(P) - 1);
111
112 pub const MIN: Self = Self(-Self::MAX.0);
116
117 pub const ZERO: Self = Self(0);
119
120 pub const ONE: Self = {
127 if S < P {
128 Self(pow10(S))
129 } else {
130 panic!("all values of Fixed::<S,P>::one() for S >= P have magnitude less than one");
131 }
132 };
133
134 pub fn mantissa(&self) -> i128 {
140 self.0
141 }
142
143 pub const fn for_i64(value: i64) -> Self {
149 assert!(P.saturating_sub(S) >= 19);
150 Self(value as i128 * Self::scale())
151 }
152
153 pub const fn for_u64(value: u64) -> Self {
159 assert!(P.saturating_sub(S) >= 19);
160 Self(value as i128 * Self::scale())
161 }
162
163 pub const fn for_i32(value: i32) -> Self {
169 assert!(P.saturating_sub(S) >= 10);
170 Self(value as i128 * Self::scale())
171 }
172
173 pub const fn for_u32(value: u32) -> Self {
179 assert!(P.saturating_sub(S) >= 10);
180 Self(value as i128 * Self::scale())
181 }
182
183 pub const fn for_i16(value: i16) -> Self {
189 assert!(P.saturating_sub(S) >= 5);
190 Self(value as i128 * Self::scale())
191 }
192
193 pub const fn for_u16(value: u16) -> Self {
199 assert!(P.saturating_sub(S) >= 5);
200 Self(value as i128 * Self::scale())
201 }
202
203 pub const fn for_i8(value: i8) -> Self {
209 assert!(P.saturating_sub(S) >= 3);
210 Self(value as i128 * Self::scale())
211 }
212
213 pub const fn for_u8(value: u8) -> Self {
219 assert!(P.saturating_sub(S) >= 3);
220 Self(value as i128 * Self::scale())
221 }
222
223 pub const fn for_isize(value: isize) -> Self {
229 match isize::BITS {
230 64 => Self::for_i64(value as i64),
231 32 => Self::for_i32(value as i32),
232 16 => Self::for_i16(value as i16),
233 _ => panic!(),
234 }
235 }
236
237 pub const fn for_usize(value: usize) -> Self {
243 match usize::BITS {
244 64 => Self::for_u64(value as u64),
245 32 => Self::for_u32(value as u32),
246 16 => Self::for_u16(value as u16),
247 _ => panic!(),
248 }
249 }
250
251 pub fn new(value: i128, scale: i32) -> Option<Self> {
266 Self::try_new_with_exponent(value, (S as i32).saturating_sub(scale))
267 }
268
269 pub fn new_round_even(value: i128, scale: i32) -> Option<Self> {
284 Self::try_new_with_exponent_round_even(value, (S as i32).saturating_sub(scale))
285 }
286
287 fn try_new(value: i128) -> Option<Self> {
289 const { Self::check_constraints() };
290 (Self::MIN.0..=Self::MAX.0)
291 .contains(&value)
292 .then_some(Self(value))
293 }
294
295 pub fn internal_representation(self) -> i128 {
298 self.0
299 }
300
301 fn try_new_with_exponent_round_even(value: i128, exponent: i32) -> Option<Self> {
304 i128_mul_pow10_round_even(value, exponent).and_then(Self::try_new)
305 }
306
307 pub(super) fn try_new_with_exponent(value: i128, exponent: i32) -> Option<Self> {
310 fn inner(value: i128, exponent: i32) -> Option<i128> {
312 Some(match exponent.cmp(&0) {
313 Ordering::Less => {
314 if let Some(divisor) = checked_pow10(exponent.unsigned_abs()) {
316 value / divisor
317 } else {
318 0
321 }
322 }
323 Ordering::Equal => value,
324 Ordering::Greater => {
325 value.checked_mul(checked_pow10(exponent.cast_unsigned())?)?
327 }
328 })
329 }
330 inner(value, exponent).and_then(Self::try_new)
331 }
332
333 const fn check_constraints() {
335 assert!(P >= 1 && P <= 38, "Fixed<S,P> must have 1 <= S <= 38");
336 assert!(S <= P, "Fixed<S,P> must have S <= P");
337 }
338
339 const fn scale() -> i128 {
341 Self::check_constraints();
342 pow10(S)
343 }
344
345 pub const fn checked_div_integer(self, other: Self) -> Option<i128> {
351 self.0.checked_div(other.0)
352 }
353
354 pub const fn strict_div_integer(self, other: Self) -> i128 {
361 self.checked_div_integer(other).unwrap()
362 }
363
364 pub fn checked_rem<const P0: usize, const S0: usize, const P1: usize, const S1: usize>(
369 self,
370 other: Fixed<P0, S0>,
371 ) -> Option<Fixed<P1, S1>> {
372 let neg = self.is_negative();
373 let left = self.abs();
374 let right = other.abs();
375 let div: Self = left.checked_div_generic(right)?;
376 let trunc: Self = div.trunc();
377 let mul: Self = right.checked_mul_generic(trunc)?;
378 let rem: Fixed<P1, S1> = left.checked_sub_generic(mul)?;
379 Some(if neg { rem.neg() } else { rem })
380 }
381
382 pub const fn abs(self) -> Self {
385 Self(self.0.abs())
386 }
387
388 pub const fn is_negative(self) -> bool {
390 self.0.is_negative()
391 }
392
393 pub fn checked_sqrt(self) -> Option<Self> {
399 Some(Self(
400 I256::from_product(self.0, Self::scale()).checked_isqrt()?,
401 ))
402 }
403
404 pub fn sqrt(self) -> Self {
413 self.checked_sqrt().unwrap()
414 }
415
416 pub fn checked_round(&self, n: i32) -> Option<Self> {
421 round_inner(self.0, S as i32, n, Halfway::AwayFromZero).and_then(Self::try_new)
422 }
423
424 pub fn round(&self, n: i32) -> Self {
433 self.checked_round(n)
434 .unwrap_or_else(|| panic!("Could not round value {} to {} digits", self, n))
435 }
436
437 pub fn checked_round_ties_even(&self, n: i32) -> Option<Self> {
442 round_inner(self.0, S as i32, n, Halfway::Even).and_then(Self::try_new)
443 }
444
445 pub fn round_ties_even(&self, n: i32) -> Self {
455 self.checked_round_ties_even(n).unwrap()
456 }
457
458 pub fn checked_floor(&self) -> Option<Self> {
461 if S > 0 {
462 Self::try_new(div_floor(self.0, Self::scale()) * Self::scale())
463 } else {
464 Some(*self)
465 }
466 }
467
468 pub fn floor(&self) -> Self {
476 self.checked_floor().unwrap()
477 }
478
479 pub fn int_floor(&self) -> Fixed<P, 0> {
481 if S > 0 {
482 Fixed::<P, 0>::new(div_floor(self.0, Self::scale()), 0i32).unwrap()
483 } else {
484 Fixed::<P, 0>::new(self.0, S as i32).unwrap()
485 }
486 }
487
488 pub fn trunc(&self) -> Self {
494 Self(self.0 / Self::scale() * Self::scale())
495 }
496
497 pub fn trunc_digits(&self, digits: i32) -> Self {
500 let exponent = (S as i32).saturating_sub(digits);
501 if exponent <= 0 {
502 *self
503 } else if let Some(divisor) = checked_pow10(exponent.cast_unsigned()) {
504 Self(self.0 / divisor * divisor)
505 } else {
506 Self::ZERO
507 }
508 }
509
510 pub fn checked_ceil(&self) -> Option<Self> {
513 if S > 0 {
514 Self::try_new(div_ceil(self.0, Self::scale()) * Self::scale())
515 } else {
516 Some(*self)
517 }
518 }
519
520 pub fn ceil(&self) -> Self {
528 self.checked_ceil().unwrap()
529 }
530
531 pub fn int_ceil(&self) -> Fixed<P, 0> {
534 if S > 0 {
535 Fixed::<P, 0>::new(div_ceil(self.0, Self::scale()), 0i32).unwrap()
536 } else {
537 Fixed::<P, 0>::new(self.0, S as i32).unwrap()
538 }
539 }
540
541 pub fn sign(&self) -> Fixed<1, 0> {
544 self.checked_sign_generic().unwrap()
545 }
546
547 pub fn checked_recip(&self) -> Option<Self> {
550 if S < P {
551 Self(Self::scale()).checked_div(self)
552 } else {
553 None
557 }
558 }
559
560 pub fn recip(&self) -> Self {
567 self.checked_recip().unwrap()
568 }
569
570 pub fn checked_powi(&self, exp: i32) -> Option<Self> {
580 if self.is_zero() {
581 (exp > 0).then_some(Self::ZERO)
582 } else if exp == 0 {
583 if S < P {
584 Some(Self::ONE)
585 } else {
586 None
588 }
589 } else if exp > 0 {
590 let mut exp = exp.unsigned_abs();
591 let mut base = self.0;
592 let mut base_scale = S as i32;
593 let mut acc = None;
594 loop {
595 if (exp & 1) == 1 {
596 acc = if let Some((acc, acc_scale)) = acc {
597 let (acc, shift) = I256::from_product(acc, base).reduce_to_i128();
598 Some((acc, (acc_scale + base_scale) - shift as i32))
599 } else {
600 Some((base, base_scale))
601 };
602 }
603 exp /= 2;
604 if exp == 0 {
605 let (acc, acc_scale) = acc.unwrap();
606 return Self::try_new_with_exponent(acc, S as i32 - acc_scale);
607 }
608
609 let (next_base, shift) = I256::from_product(base, base).reduce_to_i128();
610 base = next_base;
611 base_scale = base_scale * 2 - shift as i32;
612 }
613 } else {
614 let mut exp = exp.unsigned_abs();
615 let mut base = *self;
616 let mut acc: Option<Fixed<P, S>> = None;
617 loop {
618 if (exp & 1) == 1 {
619 acc = Some(if let Some(acc) = acc {
620 acc.checked_div(&base)
621 } else {
622 base.checked_recip()
623 }?)
624 }
625 exp /= 2;
626 if exp == 0 {
627 return acc;
628 }
629 base *= base;
630 }
631 }
632 }
633
634 pub fn powi(&self, exp: i32) -> Self {
645 self.checked_powi(exp).unwrap()
646 }
647
648 pub fn next_up(&self) -> Option<Self> {
651 if *self < Self::MAX {
652 Some(Self(self.0 + 1))
653 } else {
654 None
655 }
656 }
657
658 pub fn next_down(&self) -> Option<Self> {
661 if *self > Self::MIN {
662 Some(Self(self.0 - 1))
663 } else {
664 None
665 }
666 }
667}
668
669impl<const P0: usize, const S0: usize> Fixed<P0, S0> {
670 pub fn convert<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
679 Fixed::try_new_with_exponent(self.0, S1 as i32 - S0 as i32)
680 }
681
682 pub fn convert_round_even<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
687 Fixed::try_new_with_exponent_round_even(self.0, S1 as i32 - S0 as i32)
688 }
689
690 pub fn checked_sign_generic<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
694 let one = Fixed::<P1, S1>::scale();
695 match self.0.cmp(&0) {
696 Ordering::Less if S1 < P1 => Some(Fixed(-one)),
697 Ordering::Equal => Some(Fixed::ZERO),
698 Ordering::Greater if S1 < P1 => Some(Fixed(one)),
699 _ => None,
700 }
701 }
702
703 pub fn checked_add_generic<
709 const P1: usize,
710 const S1: usize,
711 const P2: usize,
712 const S2: usize,
713 >(
714 self,
715 other: Fixed<P1, S1>,
716 ) -> Option<Fixed<P2, S2>> {
717 match S0.cmp(&S1) {
718 Ordering::Less => {
719 let factor = pow10(S1 - S0);
720 if self.0 <= i128::MAX / factor / 10 {
721 Fixed::try_new_with_exponent(
722 other.0.checked_add(self.0 * factor)?,
723 S2 as i32 - S1 as i32,
724 )
725 } else {
726 let result = (I256::from_product(self.0, factor) + I256::from(other.0))
727 .narrowing_div(pow10(S2.saturating_sub(S1)))?;
728 Fixed::try_new_with_exponent(result, S1.saturating_sub(S2) as i32)
729 }
730 }
731 Ordering::Equal => {
732 Fixed::try_new_with_exponent(self.0.checked_add(other.0)?, S2 as i32 - S0 as i32)
733 }
734 Ordering::Greater => {
735 let factor = pow10(S0 - S1);
736 if other.0 <= i128::MAX / factor / 10 {
737 Fixed::try_new_with_exponent(
738 self.0.checked_add(other.0 * factor)?,
739 S2 as i32 - S0 as i32,
740 )
741 } else {
742 let result = (I256::from_product(other.0, factor) + I256::from(self.0))
743 .narrowing_div(pow10(S2.saturating_sub(S0)))?;
744 Fixed::try_new_with_exponent(result, S0.saturating_sub(S2) as i32)
745 }
746 }
747 }
748 }
749
750 pub fn checked_sub_generic<
756 const P1: usize,
757 const S1: usize,
758 const P2: usize,
759 const S2: usize,
760 >(
761 self,
762 other: Fixed<P1, S1>,
763 ) -> Option<Fixed<P2, S2>> {
764 self.checked_add_generic(-other)
765 }
766
767 pub fn checked_mul_generic<
773 const P1: usize,
774 const S1: usize,
775 const P2: usize,
776 const S2: usize,
777 >(
778 self,
779 other: Fixed<P1, S1>,
780 ) -> Option<Fixed<P2, S2>> {
781 Fixed::<P2, S2>::try_new_with_exponent(
782 I256::from_product(self.0, other.0)
783 .narrowing_div(pow10((S0 + S1).saturating_sub(S2)))?,
784 S2.saturating_sub(S0 + S1) as i32,
785 )
786 }
787
788 pub fn checked_div_generic<
794 const P1: usize,
795 const S1: usize,
796 const P2: usize,
797 const S2: usize,
798 >(
799 self,
800 other: Fixed<P1, S1>,
801 ) -> Option<Fixed<P2, S2>> {
802 if other == 0 {
803 None
804 } else {
805 let shift_left = (S1 + S2).saturating_sub(S0);
806 if shift_left > 38 {
807 None
811 } else {
812 Fixed::try_new_with_exponent(
813 I256::from_product(self.0, pow10(shift_left)).narrowing_div(other.0)?,
814 S0.saturating_sub(S1 + S2) as i32,
815 )
816 }
817 }
818 }
819
820 pub fn strict_add_generic<
823 const P1: usize,
824 const S1: usize,
825 const P2: usize,
826 const S2: usize,
827 >(
828 self,
829 other: Fixed<P1, S1>,
830 ) -> Fixed<P2, S2> {
831 self.checked_add_generic(other).unwrap()
832 }
833
834 pub fn strict_sub_generic<
837 const P1: usize,
838 const S1: usize,
839 const P2: usize,
840 const S2: usize,
841 >(
842 self,
843 other: Fixed<P1, S1>,
844 ) -> Fixed<P2, S2> {
845 self.checked_sub_generic(other).unwrap()
846 }
847
848 pub fn strict_mul_generic<
851 const P1: usize,
852 const S1: usize,
853 const P2: usize,
854 const S2: usize,
855 >(
856 self,
857 other: Fixed<P1, S1>,
858 ) -> Fixed<P2, S2> {
859 self.checked_mul_generic(other).unwrap()
860 }
861
862 pub fn strict_div_generic<
865 const P1: usize,
866 const S1: usize,
867 const P2: usize,
868 const S2: usize,
869 >(
870 self,
871 other: Fixed<P1, S1>,
872 ) -> Fixed<P2, S2> {
873 self.checked_div_generic(other).unwrap()
874 }
875}
876
877impl<const P: usize, const S: usize> Zero for Fixed<P, S> {
878 fn zero() -> Self {
879 Self::ZERO
880 }
881
882 fn is_zero(&self) -> bool {
883 *self == Self::ZERO
884 }
885}
886
887impl<const P: usize, const S: usize> One for Fixed<P, S> {
888 fn one() -> Self {
890 Self::ONE
891 }
892}
893
894impl<const P: usize, const S: usize> TryFrom<f64> for Fixed<P, S> {
895 type Error = OutOfRange;
896
897 fn try_from(value: f64) -> Result<Self, Self::Error> {
900 cast(value * Self::scale() as f64)
901 .and_then(Self::try_new)
902 .ok_or(OutOfRange)
903 }
904}
905
906impl<const P: usize, const S: usize> TryFrom<f32> for Fixed<P, S> {
907 type Error = OutOfRange;
908
909 fn try_from(value: f32) -> Result<Self, Self::Error> {
912 cast(value as f64 * Self::scale() as f64)
913 .and_then(Self::try_new)
914 .ok_or(OutOfRange)
915 }
916}
917
918impl<const P: usize, const S: usize> From<Fixed<P, S>> for f64 {
919 fn from(value: Fixed<P, S>) -> Self {
920 value.0 as f64 / Fixed::<P, S>::scale() as f64
921 }
922}
923
924impl<const P: usize, const S: usize> TryFrom<i128> for Fixed<P, S> {
925 type Error = OutOfRange;
926
927 fn try_from(value: i128) -> Result<Self, Self::Error> {
931 if value.unsigned_abs() <= Self::max_u128() {
932 Ok(Self(value * Self::scale()))
933 } else {
934 Err(OutOfRange)
935 }
936 }
937}
938
939macro_rules! try_from_signed_int {
940 ($type_name:ty) => {
941 impl<const P: usize, const S: usize> TryFrom<$type_name> for Fixed<P, S> {
942 type Error = OutOfRange;
943
944 fn try_from(value: $type_name) -> Result<Self, Self::Error> {
947 (value as i128).try_into()
948 }
949 }
950 };
951}
952
953try_from_signed_int!(isize);
954try_from_signed_int!(i64);
955try_from_signed_int!(i32);
956try_from_signed_int!(i16);
957try_from_signed_int!(i8);
958
959impl<const P: usize, const S: usize> TryFrom<u128> for Fixed<P, S> {
960 type Error = OutOfRange;
961
962 fn try_from(value: u128) -> Result<Self, Self::Error> {
966 if value <= Self::max_i128() as u128 {
967 Ok(Self(value as i128 * Self::scale()))
968 } else {
969 Err(OutOfRange)
970 }
971 }
972}
973
974macro_rules! try_from_unsigned_int {
975 ($type_name:ty) => {
976 impl<const P: usize, const S: usize> TryFrom<$type_name> for Fixed<P, S> {
977 type Error = OutOfRange;
978
979 fn try_from(value: $type_name) -> Result<Self, Self::Error> {
983 (value as u128).try_into()
984 }
985 }
986 };
987}
988
989try_from_unsigned_int!(usize);
990try_from_unsigned_int!(u64);
991try_from_unsigned_int!(u32);
992try_from_unsigned_int!(u16);
993try_from_unsigned_int!(u8);
994
995macro_rules! min_max_int {
996 ($signed_type:ty, $max_signed:ident, $min_signed:ident, $unsigned_type:ty, $max_unsigned:ident) => {
997 #[doc = "Returns the maximum `"]
998 #[doc = stringify!($signed_type)]
999 #[doc = "` that can be converted to this type."]
1000 pub const fn $max_signed() -> $signed_type {
1001 if Self::max_i128() > <$signed_type>::MAX as i128 {
1002 <$signed_type>::MAX
1003 } else {
1004 Self::max_i128() as $signed_type
1005 }
1006 }
1007
1008 #[doc = "Returns the minimum `"]
1009 #[doc = stringify!($signed_type)]
1010 #[doc = "` that can be converted to this type."]
1011 pub const fn $min_signed() -> $signed_type {
1012 -Self::$max_signed()
1013 }
1014
1015 #[doc = "Returns the maximum `"]
1016 #[doc = stringify!($unsigned_type)]
1017 #[doc = "` that can be converted to this type.\n\nThe minimum is 0."]
1018 pub const fn $max_unsigned() -> $unsigned_type {
1019 if Self::max_u128() > <$unsigned_type>::MAX as u128 {
1020 <$unsigned_type>::MAX
1021 } else {
1022 Self::max_u128() as $unsigned_type
1023 }
1024 }
1025 };
1026}
1027
1028impl<const P: usize, const S: usize> Fixed<P, S> {
1029 pub const fn max_i128() -> i128 {
1031 if P > S { pow10(P - S) - 1 } else { 0 }
1032 }
1033
1034 pub const fn min_i128() -> i128 {
1036 -Self::max_i128()
1037 }
1038
1039 pub const fn max_u128() -> u128 {
1043 Self::max_i128().cast_unsigned()
1044 }
1045
1046 min_max_int!(isize, max_isize, min_isize, usize, max_usize);
1047 min_max_int!(i64, max_i64, min_i64, u64, max_u64);
1048 min_max_int!(i32, max_i32, min_i32, u32, max_u32);
1049 min_max_int!(i16, max_i16, min_i16, u16, max_u16);
1050 min_max_int!(i8, max_i8, min_i8, u8, max_u8);
1051}
1052
1053impl<const P: usize, const S: usize> From<Fixed<P, S>> for i128 {
1054 fn from(value: Fixed<P, S>) -> Self {
1057 value.0 / <Fixed<P, S>>::scale()
1059 }
1060}
1061
1062macro_rules! try_to_signed_int {
1063 ($type_name:ty) => {
1064 impl<const P: usize, const S: usize> TryFrom<Fixed<P, S>> for $type_name {
1065 type Error = OutOfRange;
1066
1067 fn try_from(value: Fixed<P, S>) -> Result<Self, Self::Error> {
1070 i128::from(value).try_into().map_err(|_| OutOfRange)
1071 }
1072 }
1073 };
1074}
1075
1076try_to_signed_int!(i64);
1077try_to_signed_int!(i32);
1078try_to_signed_int!(i16);
1079try_to_signed_int!(i8);
1080try_to_signed_int!(isize);
1081
1082macro_rules! try_to_unsigned_int {
1085 ($type_name:ty) => {
1086 impl<const P: usize, const S: usize> TryFrom<Fixed<P, S>> for $type_name {
1087 type Error = OutOfRange;
1088
1089 fn try_from(value: Fixed<P, S>) -> Result<Self, Self::Error> {
1095 i128::from(value).try_into().map_err(|_| OutOfRange)
1096 }
1097 }
1098 };
1099}
1100
1101try_to_unsigned_int!(u128);
1102try_to_unsigned_int!(u64);
1103try_to_unsigned_int!(u32);
1104try_to_unsigned_int!(u16);
1105try_to_unsigned_int!(u8);
1106try_to_unsigned_int!(usize);
1107
1108impl<const P: usize, const S: usize> Add for Fixed<P, S> {
1109 type Output = Self;
1110
1111 fn add(self, other: Self) -> Self::Output {
1117 self.checked_add(&other).unwrap()
1118 }
1119}
1120
1121impl<const P: usize, const S: usize> Add for &Fixed<P, S> {
1122 type Output = Fixed<P, S>;
1123
1124 fn add(self, other: Self) -> Self::Output {
1130 self.checked_add(other).unwrap()
1131 }
1132}
1133
1134impl<const P: usize, const S: usize> CheckedAdd for Fixed<P, S> {
1135 fn checked_add(&self, other: &Self) -> Option<Self> {
1138 self.checked_add_generic(*other)
1139 }
1140}
1141
1142impl<const P: usize, const S: usize> AddAssign for Fixed<P, S> {
1143 fn add_assign(&mut self, other: Self) {
1149 *self = *self + other;
1150 }
1151}
1152
1153impl<const P: usize, const S: usize> AddAssign<&Fixed<P, S>> for Fixed<P, S> {
1154 fn add_assign(&mut self, other: &Fixed<P, S>) {
1160 *self = *self + *other;
1161 }
1162}
1163
1164impl<const P: usize, const S: usize> Sub for Fixed<P, S> {
1165 type Output = Self;
1166
1167 fn sub(self, other: Self) -> Self::Output {
1173 self.checked_sub(&other).unwrap()
1174 }
1175}
1176
1177impl<const P: usize, const S: usize> Sub for &Fixed<P, S> {
1178 type Output = Fixed<P, S>;
1179
1180 fn sub(self, other: Self) -> Self::Output {
1186 self.checked_sub(other).unwrap()
1187 }
1188}
1189
1190impl<const P: usize, const S: usize> CheckedSub for Fixed<P, S> {
1191 fn checked_sub(&self, other: &Self) -> Option<Self> {
1194 self.checked_sub_generic(*other)
1195 }
1196}
1197
1198impl<const P: usize, const S: usize> SubAssign for Fixed<P, S> {
1199 fn sub_assign(&mut self, other: Self) {
1205 *self = *self - other;
1206 }
1207}
1208
1209impl<const P: usize, const S: usize> Mul for Fixed<P, S> {
1210 type Output = Self;
1211
1212 fn mul(self, other: Self) -> Self::Output {
1218 self.checked_mul(&other).unwrap()
1219 }
1220}
1221
1222impl<const P: usize, const S: usize> Mul for &Fixed<P, S> {
1223 type Output = Fixed<P, S>;
1224
1225 fn mul(self, other: Self) -> Self::Output {
1231 self.checked_mul(other).unwrap()
1232 }
1233}
1234
1235impl<const P: usize, const S: usize> CheckedMul for Fixed<P, S> {
1236 fn checked_mul(&self, other: &Self) -> Option<Self> {
1239 Self::checked_mul_generic(*self, *other)
1240 }
1241}
1242
1243impl<const P: usize, const S: usize> MulAssign for Fixed<P, S> {
1244 fn mul_assign(&mut self, other: Self) {
1250 *self = *self * other;
1251 }
1252}
1253
1254impl<const P: usize, const S: usize> Div for Fixed<P, S> {
1255 type Output = Self;
1256
1257 fn div(self, other: Self) -> Self::Output {
1263 self.checked_div(&other).unwrap()
1264 }
1265}
1266
1267impl<const P: usize, const S: usize> Div for &Fixed<P, S> {
1268 type Output = Fixed<P, S>;
1269
1270 fn div(self, other: Self) -> Self::Output {
1276 self.checked_div(other).unwrap()
1277 }
1278}
1279
1280impl<const P: usize, const S: usize> CheckedDiv for Fixed<P, S> {
1281 fn checked_div(&self, other: &Self) -> Option<Self> {
1284 Self::checked_div_generic(*self, *other)
1285 }
1286}
1287
1288impl<const P: usize, const S: usize> DivAssign for Fixed<P, S> {
1289 fn div_assign(&mut self, other: Self) {
1295 *self = *self / other;
1296 }
1297}
1298
1299impl<const P: usize, const S: usize> Neg for Fixed<P, S> {
1300 type Output = Self;
1301
1302 fn neg(self) -> Self::Output {
1304 Self(-self.0)
1305 }
1306}
1307
1308impl<const P: usize, const S: usize> Neg for &Fixed<P, S> {
1309 type Output = Fixed<P, S>;
1310
1311 fn neg(self) -> Self::Output {
1313 Fixed(-self.0)
1314 }
1315}
1316
1317impl<const P: usize, const S: usize> FromStr for Fixed<P, S> {
1318 type Err = ParseDecimalError;
1319
1320 fn from_str(s: &str) -> Result<Self, Self::Err> {
1327 let (value, exponent) = parse_decimal(s, S as i32)?;
1328 Self::try_new_with_exponent_round_even(value, exponent).ok_or(ParseDecimalError::OutOfRange)
1329 }
1330}
1331
1332impl<const P: usize, const S: usize> Debug for Fixed<P, S> {
1333 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1334 debug_decimal(self.0, S, f)
1335 }
1336}
1337
1338impl<const P: usize, const S: usize> Display for Fixed<P, S> {
1339 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1340 display_decimal(self.0, S, f)
1341 }
1342}
1343
1344impl<const P: usize, const S: usize> Fixed<P, S> {
1345 pub const UNSIGNED_MIN: u128 = 0;
1349
1350 pub const UNSIGNED_ZERO: u128 = pow10(P).cast_unsigned() - 1;
1352
1353 pub const UNSIGNED_MAX: u128 = pow10(P).cast_unsigned() * 2 - 2;
1355
1356 pub fn to_unsigned_encoding(self) -> u128 {
1370 Self::UNSIGNED_ZERO.checked_add_signed(self.0).unwrap()
1371 }
1372
1373 pub fn from_unsigned_encoding(encoding: u128) -> Option<Self> {
1388 if encoding < Self::UNSIGNED_ZERO {
1389 Some(Self(-(Self::UNSIGNED_ZERO - encoding).cast_signed()))
1390 } else if encoding <= Self::UNSIGNED_MAX {
1391 Some(Self((encoding - Self::UNSIGNED_ZERO).cast_signed()))
1392 } else {
1393 None
1394 }
1395 }
1396}
1397
1398#[cfg(test)]
1399mod test {
1400 use std::str::FromStr;
1401
1402 use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub};
1403
1404 use crate::Fixed;
1405
1406 type F = Fixed<10, 2>;
1407 fn f(n: f64) -> F {
1408 Fixed::try_from(n).unwrap()
1409 }
1410
1411 fn f38_0(n: f64) -> Fixed<38, 0> {
1412 Fixed::try_from(n).unwrap()
1413 }
1414
1415 fn f38_38(s: &str) -> Fixed<38, 38> {
1416 Fixed::from_str(s).unwrap()
1417 }
1418
1419 #[test]
1420 fn mul() {
1421 assert_eq!(f(1.23) * f(2.34), f(2.87));
1423 assert_eq!(f(-1.23) * f(2.34), f(-2.87));
1424 assert_eq!(f(1.23) * f(-2.34), f(-2.87));
1425 assert_eq!(f(-1.23) * f(-2.34), f(2.87));
1426
1427 for a in -999..=999 {
1429 let af: Fixed<10, 2> = Fixed(a);
1430 for b in -999..=999 {
1431 let bf: Fixed<10, 2> = Fixed(b);
1432 assert_eq!(af * bf, Fixed::<10, 2>(a * b / 100));
1433 }
1434 }
1435
1436 for a in -999..=999 {
1438 let af: Fixed<3, 2> = Fixed(a);
1439 for b in -999..=999 {
1440 let bf: Fixed<3, 2> = Fixed(b);
1441 let c = a * b / 100;
1442 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1443 assert_eq!(af.checked_mul(&bf), expected);
1444 }
1445 }
1446 }
1447
1448 #[test]
1449 fn mul_generic() {
1450 for a in -999..=999 {
1451 let af: Fixed<10, 2> = Fixed(a);
1452 for b in -999..=999 {
1453 let bf: Fixed<10, 3> = Fixed(b);
1454 let cf: Fixed<10, 5> = af.checked_mul_generic(bf).unwrap();
1455 assert_eq!(cf, Fixed::<10, 5>(a * b));
1456 let df: Fixed<10, 6> = af.checked_mul_generic(bf).unwrap();
1457 assert_eq!(df, Fixed::<10, 6>(a * b * 10));
1458 let ef: Fixed<10, 0> = af.checked_mul_generic(bf).unwrap();
1459 assert_eq!(ef, Fixed::<10, 0>(a * b / 100_000));
1460 }
1461 }
1462 }
1463
1464 #[test]
1465 fn div() {
1466 assert_eq!(f(1.23) / f(2.34), f(0.52));
1468 assert_eq!(f(-1.23) / f(2.34), f(-0.52));
1469 assert_eq!(f(1.23) / f(-2.34), f(-0.52));
1470 assert_eq!(f(-1.23) / f(-2.34), f(0.52));
1471 assert_eq!(
1472 f38_0(1.0)
1473 .checked_div_generic::<38, 0, 38, 38>(f38_0(7.0))
1474 .unwrap(),
1475 f38_38("0.14285714285714285714285714285714285714")
1476 );
1477
1478 assert_eq!(
1479 f38_0(123.0).checked_div_generic::<38, 38, 38, 38>(f38_38("0.456")),
1480 None
1481 );
1482
1483 for a in -999..=999 {
1485 let af: Fixed<10, 2> = Fixed(a);
1486 for b in -999..=999 {
1487 let bf: Fixed<10, 2> = Fixed(b);
1488 assert_eq!(af.checked_div(&bf), (b != 0).then(|| Fixed(a * 100 / b)));
1489 }
1490 }
1491
1492 for a in -999..=999 {
1494 let af: Fixed<3, 2> = Fixed(a);
1495 for b in -999..=999 {
1496 let bf: Fixed<3, 2> = Fixed(b);
1497 let expected = if b != 0 {
1498 let result = a * 100 / b;
1499 (result.unsigned_abs() <= 999).then_some(Fixed(result))
1500 } else {
1501 None
1502 };
1503 assert_eq!(af.checked_div(&bf), expected);
1504 }
1505 }
1506 }
1507
1508 #[test]
1509 fn div_generic() {
1510 for a in -999..=999 {
1511 let af: Fixed<10, 2> = Fixed(a);
1512 for b in -999..=999 {
1513 if b != 0 {
1514 let bf: Fixed<10, 3> = Fixed(b);
1515 let cf: Fixed<10, 5> = af.checked_div_generic(bf).unwrap();
1516 assert_eq!(cf, Fixed::<10, 5>(a * 1_000_000 / b));
1517 let df: Fixed<10, 6> = af.checked_div_generic(bf).unwrap();
1518 assert_eq!(df, Fixed::<10, 6>(a * 10_000_000 / b));
1519 let ef: Fixed<10, 0> = af.checked_div_generic(bf).unwrap();
1520 assert_eq!(ef, Fixed::<10, 0>(a * 10 / b));
1521 }
1522 }
1523 }
1524 }
1525
1526 #[test]
1527 fn add() {
1528 assert_eq!(f(1.23) + f(2.34), f(3.57));
1530 assert_eq!(f(-1.23) + f(2.34), f(1.11));
1531 assert_eq!(f(1.23) + f(-2.34), f(-1.11));
1532 assert_eq!(f(-1.23) + f(-2.34), f(-3.57));
1533
1534 for a in -999..=999 {
1536 let af: Fixed<10, 2> = Fixed(a);
1537 for b in -999..=999 {
1538 let bf: Fixed<10, 2> = Fixed(b);
1539 assert_eq!(af + bf, Fixed::<10, 2>(a + b));
1540 }
1541 }
1542
1543 for a in -999..=999 {
1545 let af: Fixed<3, 2> = Fixed(a);
1546 for b in -999..=999 {
1547 let bf: Fixed<3, 2> = Fixed(b);
1548 let c = a + b;
1549 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1550 assert_eq!(af.checked_add(&bf), expected);
1551 }
1552 }
1553
1554 for a in -999..=999 {
1556 let af: Fixed<10, 2> = Fixed(a);
1557 for b in -999..=999 {
1558 let bf: Fixed<10, 3> = Fixed(b);
1559 let cf: Fixed<10, 5> = af.checked_add_generic(bf).unwrap();
1560 assert_eq!(
1561 cf,
1562 Fixed::<10, 5>(a * 1000 + b * 100),
1563 "{af} + {bf} ?= {cf}"
1564 );
1565 let cf: Fixed<10, 5> = bf.checked_add_generic(af).unwrap();
1566 assert_eq!(
1567 cf,
1568 Fixed::<10, 5>(a * 1000 + b * 100),
1569 "{bf} + {af} ?= {cf}"
1570 );
1571 let df: Fixed<10, 6> = af.checked_add_generic(bf).unwrap();
1572 assert_eq!(
1573 df,
1574 Fixed::<10, 6>(a * 10_000 + b * 1000),
1575 "{af} + {bf} ?= {df}"
1576 );
1577 let ef: Fixed<10, 0> = af.checked_add_generic(bf).unwrap();
1578 assert_eq!(
1579 ef,
1580 Fixed::<10, 0>((a * 10 + b) / 1000),
1581 "{af} + {bf} ?= {ef}"
1582 );
1583
1584 let ff: Fixed<10, 2> = Fixed(b);
1585 let gf: Fixed<10, 1> = af.checked_add_generic(ff).unwrap();
1586 assert_eq!(gf, Fixed::<10, 1>((a + b) / 10), "{af} + {ff} ?= {gf}");
1587 let hf: Fixed<10, 3> = af.checked_add_generic(ff).unwrap();
1588 assert_eq!(hf, Fixed::<10, 3>((a + b) * 10), "{af} + {ff} ?= {hf}");
1589 }
1590 }
1591 }
1592
1593 #[test]
1594 fn sub() {
1595 assert_eq!(f(1.23) - f(2.34), f(-1.11));
1597 assert_eq!(f(-1.23) - f(2.34), f(-3.57));
1598 assert_eq!(f(1.23) - f(-2.34), f(3.57));
1599 assert_eq!(f(-1.23) - f(-2.34), f(1.11));
1600
1601 for a in -999..=999 {
1603 let af: Fixed<10, 2> = Fixed(a);
1604 for b in -999..=999 {
1605 let bf: Fixed<10, 2> = Fixed(b);
1606 assert_eq!(af - bf, Fixed::<10, 2>(a - b));
1607 }
1608 }
1609
1610 for a in -999..=999 {
1612 let af: Fixed<3, 2> = Fixed(a);
1613 for b in -999..=999 {
1614 let bf: Fixed<3, 2> = Fixed(b);
1615 let c = a - b;
1616 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1617 assert_eq!(af.checked_sub(&bf), expected);
1618 }
1619 }
1620
1621 for a in -999..=999 {
1623 let af: Fixed<10, 2> = Fixed(a);
1624 for b in -999..=999 {
1625 let bf: Fixed<10, 3> = Fixed(b);
1626 let cf: Fixed<10, 5> = af.checked_sub_generic(bf).unwrap();
1627 assert_eq!(
1628 cf,
1629 Fixed::<10, 5>(a * 1000 - b * 100),
1630 "{af} - {bf} ?= {cf}"
1631 );
1632 let cf: Fixed<10, 5> = bf.checked_sub_generic(af).unwrap();
1633 assert_eq!(
1634 cf,
1635 Fixed::<10, 5>(b * 100 - a * 1000),
1636 "{bf} - {af} ?= {cf}"
1637 );
1638 let df: Fixed<10, 6> = af.checked_sub_generic(bf).unwrap();
1639 assert_eq!(df, Fixed::<10, 6>(a * 10_000 - b * 1000));
1640 }
1641 }
1642 }
1643
1644 #[test]
1645 fn powi() {
1646 assert_eq!(
1647 Fixed::<10, 8>::from_str("1.12345678")
1648 .unwrap()
1649 .powi(8)
1650 .to_string()
1651 .as_str(),
1652 "2.53776238"
1653 );
1654 assert_eq!(f(2.0).powi(3), f(8.0));
1655 assert_eq!(f(-2.0).powi(3), f(-8.0));
1656 assert_eq!(f(1.7).powi(8), f(69.75));
1657 assert_eq!(f(1.7).powi(-8), f(0.01));
1658 assert_eq!(f(0.0).powi(1), f(0.0));
1659 assert_eq!(f(0.0).checked_powi(0), None);
1660 assert_eq!(f(0.0).checked_powi(-1), None);
1661 }
1662
1663 #[test]
1664 fn convert() {
1665 let a = Fixed::<10, 10>::from_str("0.0123456789").unwrap();
1666 assert_eq!(&a.convert::<10, 0>().unwrap().to_string(), "0");
1667 assert_eq!(&a.convert::<10, 1>().unwrap().to_string(), "0");
1668 assert_eq!(&a.convert::<10, 2>().unwrap().to_string(), "0.01");
1669 assert_eq!(&a.convert::<10, 3>().unwrap().to_string(), "0.012");
1670 assert_eq!(&a.convert::<10, 4>().unwrap().to_string(), "0.0123");
1671 assert_eq!(&a.convert::<10, 5>().unwrap().to_string(), "0.01234");
1672 assert_eq!(&a.convert::<10, 6>().unwrap().to_string(), "0.012345");
1673 assert_eq!(&a.convert::<10, 7>().unwrap().to_string(), "0.0123456");
1674 assert_eq!(&a.convert::<10, 8>().unwrap().to_string(), "0.01234567");
1675 assert_eq!(&a.convert::<10, 9>().unwrap().to_string(), "0.012345678");
1676 assert_eq!(&a.convert::<10, 10>().unwrap().to_string(), "0.0123456789");
1677 assert_eq!(&a.convert_round_even::<10, 0>().unwrap().to_string(), "0");
1678 assert_eq!(&a.convert_round_even::<10, 1>().unwrap().to_string(), "0");
1679 assert_eq!(
1680 &a.convert_round_even::<10, 2>().unwrap().to_string(),
1681 "0.01"
1682 );
1683 assert_eq!(
1684 &a.convert_round_even::<10, 3>().unwrap().to_string(),
1685 "0.012"
1686 );
1687 assert_eq!(
1688 &a.convert_round_even::<10, 4>().unwrap().to_string(),
1689 "0.0123"
1690 );
1691 assert_eq!(
1692 &a.convert_round_even::<10, 5>().unwrap().to_string(),
1693 "0.01235"
1694 );
1695 assert_eq!(
1696 &a.convert_round_even::<10, 6>().unwrap().to_string(),
1697 "0.012346"
1698 );
1699 assert_eq!(
1700 &a.convert_round_even::<10, 7>().unwrap().to_string(),
1701 "0.0123457"
1702 );
1703 assert_eq!(
1704 &a.convert_round_even::<10, 8>().unwrap().to_string(),
1705 "0.01234568"
1706 );
1707 assert_eq!(
1708 &a.convert_round_even::<10, 9>().unwrap().to_string(),
1709 "0.012345679"
1710 );
1711 assert_eq!(
1712 &a.convert_round_even::<10, 10>().unwrap().to_string(),
1713 "0.0123456789"
1714 );
1715
1716 let b = Fixed::<10, 5>::from_str("12345.67895").unwrap();
1717 assert_eq!(&b.convert::<10, 0>().unwrap().to_string(), "12345");
1718 assert_eq!(&b.convert::<10, 1>().unwrap().to_string(), "12345.6");
1719 assert_eq!(&b.convert::<10, 2>().unwrap().to_string(), "12345.67");
1720 assert_eq!(&b.convert::<10, 3>().unwrap().to_string(), "12345.678");
1721 assert_eq!(&b.convert::<10, 4>().unwrap().to_string(), "12345.6789");
1722 assert_eq!(&b.convert::<10, 5>().unwrap().to_string(), "12345.67895");
1723 assert_eq!(b.convert::<10, 6>(), None);
1724 assert_eq!(b.convert::<10, 7>(), None);
1725 assert_eq!(b.convert::<10, 8>(), None);
1726 assert_eq!(b.convert::<10, 9>(), None);
1727 assert_eq!(b.convert::<10, 10>(), None);
1728 assert_eq!(
1729 &b.convert_round_even::<10, 0>().unwrap().to_string(),
1730 "12346"
1731 );
1732 assert_eq!(
1733 &b.convert_round_even::<10, 1>().unwrap().to_string(),
1734 "12345.7"
1735 );
1736 assert_eq!(
1737 &b.convert_round_even::<10, 2>().unwrap().to_string(),
1738 "12345.68"
1739 );
1740 assert_eq!(
1741 &b.convert_round_even::<10, 3>().unwrap().to_string(),
1742 "12345.679"
1743 );
1744 assert_eq!(
1745 &b.convert_round_even::<10, 4>().unwrap().to_string(),
1746 "12345.679"
1747 );
1748 assert_eq!(
1749 &b.convert_round_even::<10, 5>().unwrap().to_string(),
1750 "12345.67895"
1751 );
1752 assert_eq!(b.convert_round_even::<10, 6>(), None);
1753 assert_eq!(b.convert_round_even::<10, 7>(), None);
1754 assert_eq!(b.convert_round_even::<10, 8>(), None);
1755 assert_eq!(b.convert_round_even::<10, 9>(), None);
1756 assert_eq!(b.convert_round_even::<10, 10>(), None);
1757 }
1758
1759 #[test]
1760 fn constants() {
1761 assert_eq!(Fixed::<5, 0>::MAX, Fixed::<5, 0>(99999));
1762 assert_eq!(Fixed::<5, 0>::MIN, Fixed::<5, 0>(-99999));
1763 assert_eq!(Fixed::<5, 0>::ZERO, Fixed::<5, 0>(0));
1764 assert_eq!(Fixed::<5, 0>::ONE, Fixed::<5, 0>(1));
1765
1766 assert_eq!(Fixed::<5, 1>::MAX, Fixed::<5, 1>(99999));
1767 assert_eq!(Fixed::<5, 1>::MIN, Fixed::<5, 1>(-99999));
1768 assert_eq!(Fixed::<5, 1>::ZERO, Fixed::<5, 1>(0));
1769 assert_eq!(Fixed::<5, 1>::ONE, Fixed::<5, 1>(10));
1770
1771 assert_eq!(Fixed::<5, 2>::MAX, Fixed::<5, 2>(99999));
1772 assert_eq!(Fixed::<5, 2>::MIN, Fixed::<5, 2>(-99999));
1773 assert_eq!(Fixed::<5, 2>::ZERO, Fixed::<5, 2>(0));
1774 assert_eq!(Fixed::<5, 2>::ONE, Fixed::<5, 2>(100));
1775
1776 assert_eq!(Fixed::<5, 3>::MAX, Fixed::<5, 3>(99999));
1777 assert_eq!(Fixed::<5, 3>::MIN, Fixed::<5, 3>(-99999));
1778 assert_eq!(Fixed::<5, 3>::ZERO, Fixed::<5, 3>(0));
1779 assert_eq!(Fixed::<5, 3>::ONE, Fixed::<5, 3>(1000));
1780
1781 assert_eq!(Fixed::<5, 4>::MAX, Fixed::<5, 4>(99999));
1782 assert_eq!(Fixed::<5, 4>::MIN, Fixed::<5, 4>(-99999));
1783 assert_eq!(Fixed::<5, 4>::ZERO, Fixed::<5, 4>(0));
1784 assert_eq!(Fixed::<5, 4>::ONE, Fixed::<5, 4>(10000));
1785
1786 assert_eq!(Fixed::<5, 5>::MAX, Fixed::<5, 5>(99999));
1787 assert_eq!(Fixed::<5, 5>::MIN, Fixed::<5, 5>(-99999));
1788 assert_eq!(Fixed::<5, 5>::ZERO, Fixed::<5, 5>(0));
1789 }
1792
1793 #[test]
1794 fn floor() {
1795 assert_eq!(f(5.0).floor(), f(5.0));
1796 assert_eq!(f(5.1).floor(), f(5.0));
1797 assert_eq!(f(5.5).floor(), f(5.0));
1798 assert_eq!(f(5.9).floor(), f(5.0));
1799 assert_eq!(f(-5.0).floor(), f(-5.0));
1800 assert_eq!(f(-5.1).floor(), f(-6.0));
1801 assert_eq!(f(-5.5).floor(), f(-6.0));
1802 assert_eq!(f(-5.6).floor(), f(-6.0));
1803 assert_eq!(f(4.0).floor(), f(4.0));
1804 assert_eq!(f(4.1).floor(), f(4.0));
1805 assert_eq!(f(4.5).floor(), f(4.0));
1806 assert_eq!(f(4.9).floor(), f(4.0));
1807 assert_eq!(f(-4.0).floor(), f(-4.0));
1808 assert_eq!(f(-4.1).floor(), f(-5.0));
1809 assert_eq!(f(-4.5).floor(), f(-5.0));
1810 assert_eq!(f(-4.6).floor(), f(-5.0));
1811 assert_eq!(f(-99_999_999.0).floor(), f(-99_999_999.0));
1812 assert_eq!(f(-99_999_999.1).checked_floor(), None);
1813 assert_eq!(f(-99_999_999.5).checked_floor(), None);
1814 assert_eq!(f(-99_999_999.6).checked_floor(), None);
1815 }
1816
1817 #[test]
1818 fn ceil() {
1819 assert_eq!(f(5.0).ceil(), f(5.0));
1820 assert_eq!(f(5.1).ceil(), f(6.0));
1821 assert_eq!(f(5.5).ceil(), f(6.0));
1822 assert_eq!(f(5.9).ceil(), f(6.0));
1823 assert_eq!(f(-5.0).ceil(), f(-5.0));
1824 assert_eq!(f(-5.1).ceil(), f(-5.0));
1825 assert_eq!(f(-5.5).ceil(), f(-5.0));
1826 assert_eq!(f(-5.6).ceil(), f(-5.0));
1827 assert_eq!(f(4.0).ceil(), f(4.0));
1828 assert_eq!(f(4.1).ceil(), f(5.0));
1829 assert_eq!(f(4.5).ceil(), f(5.0));
1830 assert_eq!(f(4.9).ceil(), f(5.0));
1831 assert_eq!(f(-4.0).ceil(), f(-4.0));
1832 assert_eq!(f(-4.1).ceil(), f(-4.0));
1833 assert_eq!(f(-4.5).ceil(), f(-4.0));
1834 assert_eq!(f(-4.6).ceil(), f(-4.0));
1835 assert_eq!(f(99_999_999.0).ceil(), f(99_999_999.0));
1836 assert_eq!(f(99_999_999.1).checked_ceil(), None);
1837 assert_eq!(f(99_999_999.5).checked_ceil(), None);
1838 assert_eq!(f(99_999_999.6).checked_ceil(), None);
1839 }
1840
1841 #[test]
1842 fn trunc() {
1843 fn test(x: f64, expected: f64) {
1844 assert_eq!(f(x).trunc(), f(expected));
1845 assert_eq!(f(x).trunc_digits(0), f(expected));
1846 }
1847
1848 test(5.0, 5.0);
1849 test(5.1, 5.0);
1850 test(5.5, 5.0);
1851 test(5.9, 5.0);
1852 test(-5.0, -5.0);
1853 test(-5.1, -5.0);
1854 test(-5.5, -5.0);
1855 test(-5.6, -5.0);
1856 test(4.0, 4.0);
1857 test(4.1, 4.0);
1858 test(4.5, 4.0);
1859 test(4.9, 4.0);
1860 test(-4.0, -4.0);
1861 test(-4.1, -4.0);
1862 test(-4.5, -4.0);
1863 test(-4.6, -4.0);
1864 test(99_999_999.0, 99_999_999.0);
1865 test(99_999_999.1, 99_999_999.0);
1866 test(99_999_999.5, 99_999_999.0);
1867 test(99_999_999.6, 99_999_999.0);
1868 test(-99_999_999.0, -99_999_999.0);
1869 test(-99_999_999.1, -99_999_999.0);
1870 test(-99_999_999.5, -99_999_999.0);
1871 test(-99_999_999.6, -99_999_999.0);
1872 }
1873
1874 #[test]
1875 fn round() {
1876 fn test(x: f64, expected: Option<f64>) {
1877 assert_eq!(f(x).checked_round(0), expected.map(f));
1878 }
1879 type F = Fixed<10, 2>;
1880 fn test1((x, s): (i128, i32), d: i32, expected: Option<(i128, i32)>) {
1881 assert_eq!(
1882 F::new(x, s).unwrap().checked_round(d),
1883 expected.map(|x| F::new(x.0, x.1).unwrap())
1884 );
1885 }
1886
1887 test1((51, 1), 2, Some((51, 1)));
1889 test1((51, 1), 1, Some((51, 1)));
1891 test1((51, 1), 0, Some((50, 1)));
1893 test1((51, 1), -1, Some((10, 0)));
1895
1896 test1((21, 1), 2, Some((21, 1)));
1898 test1((21, 1), 1, Some((21, 1)));
1900 test1((21, 1), 0, Some((20, 1)));
1902 test1((21, 1), -1, Some((0, 0)));
1904
1905 test1((999_999_991, 1), 2, Some((999_999_991, 1)));
1907 test1((999_999_991, 1), 1, Some((999_999_991, 1)));
1909 test1((999_999_991, 1), 0, Some((999_999_990, 1)));
1911 test1((999_999_991, 1), -1, None);
1913
1914 test(5.0, Some(5.0));
1915 test(5.1, Some(5.0));
1916 test(5.5, Some(6.0));
1917 test(5.9, Some(6.0));
1918 test(-5.0, Some(-5.0));
1919 test(-5.1, Some(-5.0));
1920 test(-5.5, Some(-6.0));
1921 test(-5.6, Some(-6.0));
1922 test(4.0, Some(4.0));
1923 test(4.1, Some(4.0));
1924 test(4.5, Some(5.0));
1925 test(4.9, Some(5.0));
1926 test(-4.0, Some(-4.0));
1927 test(-4.1, Some(-4.0));
1928 test(-4.5, Some(-5.0));
1929 test(-4.6, Some(-5.0));
1930 test(99_999_999.0, Some(99_999_999.0));
1931 test(99_999_999.1, Some(99_999_999.0));
1932 test(99_999_999.5, None);
1933 test(99_999_999.6, None);
1934 test(-99_999_999.0, Some(-99_999_999.0));
1935 test(-99_999_999.1, Some(-99_999_999.0));
1936 test(-99_999_999.5, None);
1937 test(-99_999_999.6, None);
1938 }
1939
1940 #[test]
1941 fn trunc_digits() {
1942 let x = Fixed::<10, 4>(245368746);
1943 assert_eq!(x.trunc_digits(5).to_string(), "24536.8746");
1944 assert_eq!(x.trunc_digits(4).to_string(), "24536.8746");
1945 assert_eq!(x.trunc_digits(3).to_string(), "24536.874");
1946 assert_eq!(x.trunc_digits(2).to_string(), "24536.87");
1947 assert_eq!(x.trunc_digits(1).to_string(), "24536.8");
1948 assert_eq!(x.trunc_digits(0).to_string(), "24536");
1949 assert_eq!(x.trunc_digits(-1).to_string(), "24530");
1950 assert_eq!(x.trunc_digits(-2).to_string(), "24500");
1951 assert_eq!(x.trunc_digits(-3).to_string(), "24000");
1952 assert_eq!(x.trunc_digits(-4).to_string(), "20000");
1953 assert_eq!(x.trunc_digits(-5).to_string(), "0");
1954 assert_eq!(x.trunc_digits(-50).to_string(), "0");
1955
1956 let x = -x;
1957 assert_eq!(x.trunc_digits(5).to_string(), "-24536.8746");
1958 assert_eq!(x.trunc_digits(4).to_string(), "-24536.8746");
1959 assert_eq!(x.trunc_digits(3).to_string(), "-24536.874");
1960 assert_eq!(x.trunc_digits(2).to_string(), "-24536.87");
1961 assert_eq!(x.trunc_digits(1).to_string(), "-24536.8");
1962 assert_eq!(x.trunc_digits(0).to_string(), "-24536");
1963 assert_eq!(x.trunc_digits(-1).to_string(), "-24530");
1964 assert_eq!(x.trunc_digits(-2).to_string(), "-24500");
1965 assert_eq!(x.trunc_digits(-3).to_string(), "-24000");
1966 assert_eq!(x.trunc_digits(-4).to_string(), "-20000");
1967 assert_eq!(x.trunc_digits(-5).to_string(), "0");
1968 assert_eq!(x.trunc_digits(-50).to_string(), "0");
1969 }
1970
1971 #[test]
1972 fn sign() {
1973 assert_eq!(f(-0.1).sign(), Fixed::<1, 0>::try_from(-1).unwrap());
1974 assert_eq!(f(0.0).sign(), Fixed::<1, 0>::try_from(0).unwrap());
1975 assert_eq!(f(0.5).sign(), Fixed::<1, 0>::try_from(1).unwrap());
1976 }
1977
1978 #[test]
1979 fn sqrt() {
1980 assert_eq!(f(0.0).sqrt(), f(0.0));
1982 assert_eq!(f(1.0).sqrt(), f(1.0));
1983 assert_eq!(f(2.0).sqrt(), f(1.41));
1984 assert_eq!(f(3.0).sqrt(), f(1.73));
1985 assert_eq!(f(4.0).sqrt(), f(2.0));
1986 assert_eq!(f(-1.0).checked_sqrt(), None);
1987
1988 for a in 0..=999 {
1990 let af: Fixed<10, 2> = Fixed(a);
1991 assert_eq!(af.sqrt(), Fixed::<10, 2>((a * 100).isqrt()));
1992 }
1993 }
1994
1995 #[test]
1996 fn nullable() {
1997 fn nullable_checked_add_generic<
2000 const PA: usize,
2001 const SA: usize,
2002 const PB: usize,
2003 const SB: usize,
2004 const PC: usize,
2005 const SC: usize,
2006 >(
2007 a: Option<Fixed<PA, SA>>,
2008 b: Option<Fixed<PB, SB>>,
2009 ) -> Option<Fixed<PC, SC>> {
2010 a.zip(b).and_then(|(a, b)| a.checked_add_generic(b))
2011 }
2012
2013 let a: Option<Fixed<10, 2>> = Some("1.23".parse().unwrap());
2014 let b: Option<Fixed<5, 4>> = Some("4.5678".parse().unwrap());
2015 let c: Option<Fixed<10, 4>> = nullable_checked_add_generic(a, b);
2016 assert_eq!(c, Some("5.7978".parse().unwrap()));
2017 }
2018
2019 #[test]
2020 fn to_integer() {
2021 for x in -9999..=9999 {
2022 let f = Fixed::<4, 1>(x);
2023 assert_eq!(i128::from(f), x / 10);
2024 assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
2025 assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
2026 assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
2027 assert_eq!(
2028 i8::try_from(f).ok(),
2029 (-1289..=1279).contains(&x).then_some((x / 10) as i8)
2030 );
2031 assert_eq!(
2032 u128::try_from(f).ok(),
2033 (x > -10).then_some((x / 10) as u128)
2034 );
2035 assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
2036 assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
2037 assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
2038 assert_eq!(
2039 u8::try_from(f).ok(),
2040 (-9..=2559).contains(&x).then_some((x / 10) as u8)
2041 );
2042 }
2043 }
2044
2045 #[test]
2046 fn compare_against_fixed() {
2047 fn check_comparisons<const PA: usize, const SA: usize, const PB: usize, const SB: usize>(
2048 fx: Fixed<PA, SA>,
2049 fy: Fixed<PB, SB>,
2050 x: i128,
2051 y: i128,
2052 ) {
2053 assert_eq!(fx == fy, x == y);
2054 assert_eq!(fx != fy, x != y);
2055 assert_eq!(fx > fy, x > y);
2056 assert_eq!(fx >= fy, x >= y);
2057 assert_eq!(fx < fy, x < y);
2058 assert_eq!(fx <= fy, x <= y);
2059 }
2060
2061 for x in -999..=999 {
2062 let fx = Fixed::<3, 1>(x);
2063 for y in -999..=999 {
2064 check_comparisons(fx, Fixed::<3, 0>(y), x, y * 10);
2065 check_comparisons(fx, Fixed::<3, 1>(y), x, y);
2066 check_comparisons(fx, Fixed::<3, 2>(y), x * 10, y);
2067 }
2068 }
2069 }
2070
2071 #[test]
2072 fn compare_against_integers() {
2073 for x in -999..=999 {
2074 let f = Fixed::<3, 1>(x);
2075 for y in -100..=100 {
2076 let expect = x == y * 10;
2077 assert_eq!(f == y as i8, expect);
2078 assert_eq!(f == y as i16, expect);
2079 assert_eq!(f == y as i32, expect);
2080 assert_eq!(f == y as i64, expect);
2081 assert_eq!(f == y, expect);
2082 assert_eq!(f == y as isize, expect);
2083 if y >= 0 {
2084 assert_eq!(f == y as u8, expect);
2085 assert_eq!(f == y as u16, expect);
2086 assert_eq!(f == y as u32, expect);
2087 assert_eq!(f == y as u64, expect);
2088 assert_eq!(f == y as u128, expect);
2089 assert_eq!(f == y as usize, expect);
2090 }
2091 }
2092 }
2093 }
2094
2095 #[test]
2096 fn unsigned_encoding() {
2097 type F = Fixed<3, 1>;
2098 for x in -999..=999 {
2099 let f = Fixed::<3, 1>(x);
2100 assert_eq!(F::from_unsigned_encoding(f.to_unsigned_encoding()), Some(f));
2101 }
2102 assert_eq!(F::MIN.to_unsigned_encoding(), 0);
2103 assert_eq!(F::ZERO.to_unsigned_encoding(), 999);
2104 assert_eq!(F::MAX.to_unsigned_encoding(), 999 * 2);
2105 assert_eq!(F::from_unsigned_encoding(0), Some(F::MIN));
2106 assert_eq!(F::from_unsigned_encoding(999), Some(F::ZERO));
2107 assert_eq!(F::from_unsigned_encoding(999 * 2), Some(F::MAX));
2108 assert_eq!(F::from_unsigned_encoding(999 * 2 + 1), None);
2109 }
2110
2111 #[test]
2112 fn new() {
2113 type F1 = Fixed<11, 1>;
2114 assert_eq!(F1::new(435, -8), None);
2115 assert_eq!(F1::new(435, -7).unwrap().to_string(), "4350000000");
2116 assert_eq!(F1::new(435, -6).unwrap().to_string(), "435000000");
2117 assert_eq!(F1::new(435, -5).unwrap().to_string(), "43500000");
2118 assert_eq!(F1::new(435, -4).unwrap().to_string(), "4350000");
2119 assert_eq!(F1::new(435, -3).unwrap().to_string(), "435000");
2120 assert_eq!(F1::new(435, -2).unwrap().to_string(), "43500");
2121 assert_eq!(F1::new(435, -1).unwrap().to_string(), "4350");
2122 assert_eq!(F1::new(435, 0).unwrap().to_string(), "435");
2123 assert_eq!(F1::new(435, 1).unwrap().to_string(), "43.5");
2124 assert_eq!(F1::new(435, 2).unwrap().to_string(), "4.3");
2125 assert_eq!(F1::new(435, 3).unwrap().to_string(), "0.4");
2126 assert_eq!(F1::new(435, 4).unwrap().to_string(), "0");
2127
2128 type F2 = Fixed<11, 2>;
2129 assert_eq!(F2::new(435, -7), None);
2130 assert_eq!(F2::new(435, -6).unwrap().to_string(), "435000000");
2131 assert_eq!(F2::new(435, -5).unwrap().to_string(), "43500000");
2132 assert_eq!(F2::new(435, -4).unwrap().to_string(), "4350000");
2133 assert_eq!(F2::new(435, -3).unwrap().to_string(), "435000");
2134 assert_eq!(F2::new(435, -2).unwrap().to_string(), "43500");
2135 assert_eq!(F2::new(435, -1).unwrap().to_string(), "4350");
2136 assert_eq!(F2::new(435, 0).unwrap().to_string(), "435");
2137 assert_eq!(F2::new(435, 1).unwrap().to_string(), "43.5");
2138 assert_eq!(F2::new(435, 2).unwrap().to_string(), "4.35");
2139 assert_eq!(F2::new(435, 3).unwrap().to_string(), "0.43");
2140 assert_eq!(F2::new(435, 4).unwrap().to_string(), "0.04");
2141 assert_eq!(F2::new(435, 5).unwrap().to_string(), "0");
2142 }
2143
2144 #[test]
2145 fn new_round_even() {
2146 type F1 = Fixed<11, 1>;
2147 assert_eq!(F1::new_round_even(435, -8), None);
2148 assert_eq!(
2149 F1::new_round_even(435, -7).unwrap().to_string(),
2150 "4350000000"
2151 );
2152 assert_eq!(
2153 F1::new_round_even(435, -6).unwrap().to_string(),
2154 "435000000"
2155 );
2156 assert_eq!(F1::new_round_even(435, -5).unwrap().to_string(), "43500000");
2157 assert_eq!(F1::new_round_even(435, -4).unwrap().to_string(), "4350000");
2158 assert_eq!(F1::new_round_even(435, -3).unwrap().to_string(), "435000");
2159 assert_eq!(F1::new_round_even(435, -2).unwrap().to_string(), "43500");
2160 assert_eq!(F1::new_round_even(435, -1).unwrap().to_string(), "4350");
2161 assert_eq!(F1::new_round_even(435, 0).unwrap().to_string(), "435");
2162 assert_eq!(F1::new_round_even(435, 1).unwrap().to_string(), "43.5");
2163 assert_eq!(F1::new_round_even(435, 2).unwrap().to_string(), "4.4");
2164 assert_eq!(F1::new_round_even(435, 3).unwrap().to_string(), "0.4");
2165 assert_eq!(F1::new_round_even(435, 4).unwrap().to_string(), "0");
2166
2167 type F2 = Fixed<11, 2>;
2168 assert_eq!(F2::new_round_even(435, -7), None);
2169 assert_eq!(
2170 F2::new_round_even(435, -6).unwrap().to_string(),
2171 "435000000"
2172 );
2173 assert_eq!(F2::new_round_even(435, -5).unwrap().to_string(), "43500000");
2174 assert_eq!(F2::new_round_even(435, -4).unwrap().to_string(), "4350000");
2175 assert_eq!(F2::new_round_even(435, -3).unwrap().to_string(), "435000");
2176 assert_eq!(F2::new_round_even(435, -2).unwrap().to_string(), "43500");
2177 assert_eq!(F2::new_round_even(435, -1).unwrap().to_string(), "4350");
2178 assert_eq!(F2::new_round_even(435, 0).unwrap().to_string(), "435");
2179 assert_eq!(F2::new_round_even(435, 1).unwrap().to_string(), "43.5");
2180 assert_eq!(F2::new_round_even(435, 2).unwrap().to_string(), "4.35");
2181 assert_eq!(F2::new_round_even(435, 3).unwrap().to_string(), "0.44");
2182 assert_eq!(F2::new_round_even(435, 4).unwrap().to_string(), "0.04");
2183 assert_eq!(F2::new_round_even(435, 5).unwrap().to_string(), "0");
2184 }
2185}