1use std::{
2 cmp::Ordering,
3 fmt::{Debug, Display},
4 io::Write,
5 num::IntErrorKind,
6 ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
7 str::FromStr,
8};
9
10use num_traits::{cast, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, Zero};
11use smallvec::{Array, SmallVec};
12
13use crate::u256::I256;
14
15#[cfg(feature = "dbsp")]
16mod dbsp_impl;
17
18#[cfg(feature = "serde")]
19mod serde_impl;
20mod u256;
21
22#[cfg(feature = "rkyv")]
23mod rkyv_impl;
24
25#[derive(Copy, Clone, Default, Eq, Ord, Hash)]
51#[cfg_attr(feature = "size_of", derive(size_of::SizeOf))]
52pub struct Fixed<const P: usize, const S: usize>(i128);
53
54impl<const P0: usize, const S0: usize, const P1: usize, const S1: usize> PartialEq<Fixed<P1, S1>>
55 for Fixed<P0, S0>
56{
57 fn eq(&self, other: &Fixed<P1, S1>) -> bool {
58 match S0.cmp(&S1) {
59 Ordering::Less => I256::from_product(self.0, pow10(S1 - S0)) == I256::from(other.0),
60 Ordering::Equal => self.0 == other.0,
61 Ordering::Greater => I256::from(self.0) == I256::from_product(other.0, pow10(S0 - S1)),
62 }
63 }
64}
65
66macro_rules! partial_eq_int {
67 ($type_name:ty) => {
68 impl<const P0: usize, const S0: usize> PartialEq<$type_name> for Fixed<P0, S0> {
69 fn eq(&self, other: &$type_name) -> bool {
70 self.0 % Self::scale() == 0 && self.0 / Self::scale() == *other as i128
71 }
72 }
73 };
74}
75partial_eq_int!(i8);
76partial_eq_int!(i16);
77partial_eq_int!(i32);
78partial_eq_int!(i64);
79partial_eq_int!(i128);
80partial_eq_int!(isize);
81partial_eq_int!(u8);
82partial_eq_int!(u16);
83partial_eq_int!(u32);
84partial_eq_int!(u64);
85
86impl<const P0: usize, const S0: usize> PartialEq<u128> for Fixed<P0, S0> {
87 fn eq(&self, other: &u128) -> bool {
88 self.0 >= 0
89 && self.0 % Self::scale() == 0
90 && (self.0 / Self::scale()).cast_unsigned() == *other
91 }
92}
93
94impl<const P0: usize, const S0: usize> PartialEq<usize> for Fixed<P0, S0> {
95 fn eq(&self, other: &usize) -> bool {
96 self.0 >= 0
97 && self.0 % Self::scale() == 0
98 && (self.0 / Self::scale()).cast_unsigned() == *other as u128
99 }
100}
101
102impl<const P0: usize, const S0: usize, const P1: usize, const S1: usize> PartialOrd<Fixed<P1, S1>>
103 for Fixed<P0, S0>
104{
105 fn partial_cmp(&self, other: &Fixed<P1, S1>) -> Option<Ordering> {
106 match S0.cmp(&S1) {
107 Ordering::Less => {
108 I256::from_product(self.0, pow10(S1 - S0)).partial_cmp(&I256::from(other.0))
109 }
110 Ordering::Equal => self.0.partial_cmp(&other.0),
111 Ordering::Greater => {
112 I256::from(self.0).partial_cmp(&I256::from_product(other.0, pow10(S0 - S1)))
113 }
114 }
115 }
116}
117
118pub type FixedInteger = Fixed<38, 0>;
120
121impl<const P: usize, const S: usize> Debug for Fixed<P, S> {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 if self.0 % Self::scale() == 0 {
124 write!(f, "{}", self.0 / Self::scale())
125 } else {
126 let mut buf = SmallVec::<[u8; 64]>::new();
127 write!(&mut buf, "{:01$}", self.0.unsigned_abs(), S + 1).unwrap();
128 let d = buf.len() - S;
129 while buf.ends_with(b"0") {
130 buf.pop();
131 }
132 let s = unsafe { str::from_utf8_unchecked(&buf) };
134 let (integer, fraction) = s.split_at(d);
135 let sign = if self.0 < 0 { "-" } else { "" };
136 write!(f, "{sign}{integer}.{fraction}")
137 }
138 }
139}
140
141impl<const P: usize, const S: usize> Display for Fixed<P, S> {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 let mut buf = SmallVec::<[u8; 64]>::new();
144 write!(&mut buf, "{:01$}", self.0.abs(), S + 1).unwrap();
145 debug_assert!(buf.len() > S);
146 let decimals = if let Some(precision) = f.precision() {
147 match precision.cmp(&S) {
148 Ordering::Less => {
149 let new_len = buf.len() - (S - precision);
150 let mut discard = buf[new_len..].iter();
151 enum Rounding {
152 Up,
153 Down,
154 Even,
155 }
156 impl Rounding {
157 fn round<A>(&self, s: &mut SmallVec<A>)
158 where
159 A: Array<Item = u8>,
160 {
161 let round_up = match self {
162 Rounding::Down => false,
163 Rounding::Up => true,
164 Rounding::Even => s.last().unwrap() % 2 == 1,
165 };
166 if round_up {
167 let mut nines = 0;
168 let c = loop {
169 match s.pop() {
170 Some(b'9') => nines += 1,
171 Some(c) => break c,
172 None => break b'0',
173 }
174 };
175 s.push(c + 1);
176 for _ in 0..nines {
177 s.push(b'0');
178 }
179 }
180 }
181 }
182 let rounding = match discard.next().unwrap() {
183 b'0'..=b'4' => Rounding::Down,
184 b'5' => loop {
185 match discard.next() {
186 Some(b'0') => (),
187 Some(_) => break Rounding::Up,
188 None => break Rounding::Even,
189 }
190 },
191 b'6'..=b'9' => Rounding::Up,
192 _ => unreachable!(),
193 };
194 buf.truncate(new_len);
195 rounding.round(&mut buf);
196 }
197 Ordering::Equal => (),
198 Ordering::Greater => {
199 for _ in S..precision {
200 buf.push(b'0');
201 }
202 }
203 }
204 precision
205 } else {
206 let mut decimals = S;
207 while decimals > 0 && buf.ends_with(b"0") {
208 buf.pop();
209 decimals -= 1;
210 }
211 decimals
212 };
213 if decimals > 0 {
214 buf.insert(buf.len() - decimals, b'.');
215 }
216
217 f.pad_integral(self.0 >= 0, "", unsafe { str::from_utf8_unchecked(&buf) })
219 }
220}
221
222#[derive(Copy, Clone, Debug)]
224pub struct OutOfRange;
225
226const fn checked_pow10(exponent: u32) -> Option<i128> {
229 10i128.checked_pow(exponent)
230}
231
232const fn pow10(exponent: usize) -> i128 {
239 10i128.checked_pow(exponent as u32).unwrap()
240}
241
242#[derive(Copy, Clone, PartialEq, Eq)]
244enum Halfway {
245 AwayFromZero,
247
248 Even,
250}
251
252fn round_inner(value: i128, scale: i32, n: i32, halfway: Halfway) -> Option<i128> {
253 let position = scale.saturating_sub(n);
254 if position <= 0 {
255 Some(value)
256 } else if position < scale {
257 let divisor = pow10(position as usize);
258 let quotient = value / divisor;
259 let remainder = value % divisor;
260 let round_away_from_zero = match remainder.abs().cmp(&(divisor / 2)) {
261 Ordering::Less => false,
262 Ordering::Equal => match halfway {
263 Halfway::AwayFromZero => true,
264 Halfway::Even => (quotient % 2) != 0,
265 },
266 Ordering::Greater => true,
267 };
268 let rounded_quotient = if round_away_from_zero {
269 quotient + quotient.signum()
270 } else {
271 quotient
272 };
273 Some(divisor * rounded_quotient)
274 } else if position > scale || value.abs() >= 5 * pow10(scale as usize - 1) {
275 Some(0)
276 } else {
277 None
278 }
279}
280
281const fn div_floor(x: i128, y: i128) -> i128 {
284 let d = x / y;
285 let r = x % y;
286
287 let correction = (x ^ y) >> (i128::BITS - 1);
294 if r != 0 {
295 d + correction
296 } else {
297 d
298 }
299}
300
301const fn div_ceil(x: i128, y: i128) -> i128 {
304 let d = x / y;
305 let r = x % y;
306
307 let correction = 1 + ((x ^ y) >> (i128::BITS - 1));
310 if r != 0 {
311 d + correction
312 } else {
313 d
314 }
315}
316
317impl<const P: usize, const S: usize> Fixed<P, S> {
318 pub const MAX: Self = Self(pow10(P) - 1);
320
321 pub const MIN: Self = Self(-Self::MAX.0);
325
326 pub const ZERO: Self = Self(0);
328
329 pub const ONE: Self = {
336 if S < P {
337 Self(pow10(S))
338 } else {
339 panic!("all values of Fixed::<S,P>::one() for S >= P have magnitude less than one");
340 }
341 };
342
343 pub const fn for_i64(value: i64) -> Self {
349 assert!(P.saturating_sub(S) >= 19);
350 Self(value as i128 * Self::scale())
351 }
352
353 pub const fn for_u64(value: u64) -> Self {
359 assert!(P.saturating_sub(S) >= 19);
360 Self(value as i128 * Self::scale())
361 }
362
363 pub const fn for_i32(value: i32) -> Self {
369 assert!(P.saturating_sub(S) >= 10);
370 Self(value as i128 * Self::scale())
371 }
372
373 pub const fn for_u32(value: u32) -> Self {
379 assert!(P.saturating_sub(S) >= 10);
380 Self(value as i128 * Self::scale())
381 }
382
383 pub const fn for_i16(value: i16) -> Self {
389 assert!(P.saturating_sub(S) >= 5);
390 Self(value as i128 * Self::scale())
391 }
392
393 pub const fn for_u16(value: u16) -> Self {
399 assert!(P.saturating_sub(S) >= 5);
400 Self(value as i128 * Self::scale())
401 }
402
403 pub const fn for_i8(value: i8) -> Self {
409 assert!(P.saturating_sub(S) >= 3);
410 Self(value as i128 * Self::scale())
411 }
412
413 pub const fn for_u8(value: u8) -> Self {
419 assert!(P.saturating_sub(S) >= 3);
420 Self(value as i128 * Self::scale())
421 }
422
423 pub const fn for_isize(value: isize) -> Self {
429 match isize::BITS {
430 64 => Self::for_i64(value as i64),
431 32 => Self::for_i32(value as i32),
432 16 => Self::for_i16(value as i16),
433 _ => panic!(),
434 }
435 }
436
437 pub const fn for_usize(value: usize) -> Self {
443 match usize::BITS {
444 64 => Self::for_u64(value as u64),
445 32 => Self::for_u32(value as u32),
446 16 => Self::for_u16(value as u16),
447 _ => panic!(),
448 }
449 }
450
451 fn try_new(value: i128) -> Option<Self> {
453 const { Self::check_constraints() };
454 (Self::MIN.0..=Self::MAX.0)
455 .contains(&value)
456 .then_some(Self(value))
457 }
458
459 fn try_new_with_exponent_round_even(value: i128, exponent: i32) -> Option<Self> {
462 fn inner(value: i128, exponent: i32) -> Option<i128> {
464 Some(match exponent.cmp(&0) {
465 Ordering::Less => {
466 if let Some(divisor) = checked_pow10(exponent.unsigned_abs()) {
468 debug_assert!(divisor >= 2);
473 let quotient = value / divisor;
474 let remainder = value % divisor;
475 let round_away_from_zero = match remainder.abs().cmp(&(divisor / 2)) {
476 Ordering::Less => false,
477 Ordering::Equal => (quotient % 2) != 0,
478 Ordering::Greater => true,
479 };
480 if round_away_from_zero {
481 quotient + quotient.signum()
482 } else {
483 quotient
484 }
485 } else {
486 0
489 }
490 }
491 Ordering::Equal => value,
492 Ordering::Greater => {
493 value.checked_mul(checked_pow10(exponent.cast_unsigned())?)?
495 }
496 })
497 }
498 inner(value, exponent).and_then(Self::try_new)
499 }
500
501 fn try_new_with_exponent(value: i128, exponent: i32) -> Option<Self> {
504 fn inner(value: i128, exponent: i32) -> Option<i128> {
506 Some(match exponent.cmp(&0) {
507 Ordering::Less => {
508 if let Some(divisor) = checked_pow10(exponent.unsigned_abs()) {
510 value / divisor
511 } else {
512 0
515 }
516 }
517 Ordering::Equal => value,
518 Ordering::Greater => {
519 value.checked_mul(checked_pow10(exponent.cast_unsigned())?)?
521 }
522 })
523 }
524 inner(value, exponent).and_then(Self::try_new)
525 }
526
527 const fn check_constraints() {
529 assert!(P >= 1 && P <= 38, "Fixed<S,P> must have 1 <= S <= 38");
530 assert!(S <= P, "Fixed<S,P> must have S <= P");
531 }
532
533 const fn scale() -> i128 {
535 Self::check_constraints();
536 pow10(S)
537 }
538
539 pub const fn checked_div_integer(self, other: Self) -> Option<i128> {
545 self.0.checked_div(other.0)
546 }
547
548 pub const fn strict_div_integer(self, other: Self) -> i128 {
555 self.checked_div_integer(other).unwrap()
556 }
557
558 pub const fn checked_rem_integer(self, _other: Self) -> Option<Self> {
563 todo!()
564 }
565
566 pub const fn strict_rem_integer(self, other: Self) -> Self {
573 self.checked_rem_integer(other).unwrap()
574 }
575
576 pub const fn abs(self) -> Self {
579 Self(self.0.abs())
580 }
581
582 pub const fn is_negative(self) -> bool {
584 self.0.is_negative()
585 }
586
587 pub fn checked_sqrt(self) -> Option<Self> {
593 Some(Self(
594 I256::from_product(self.0, Self::scale()).checked_isqrt()?,
595 ))
596 }
597
598 pub fn sqrt(self) -> Self {
607 self.checked_sqrt().unwrap()
608 }
609
610 pub fn checked_round(&self, n: i32) -> Option<Self> {
615 round_inner(self.0, S as i32, n, Halfway::AwayFromZero).and_then(Self::try_new)
616 }
617
618 pub fn round(&self, n: i32) -> Self {
627 self.checked_round(n).unwrap()
628 }
629
630 pub fn checked_round_ties_even(&self, n: i32) -> Option<Self> {
635 round_inner(self.0, S as i32, n, Halfway::Even).and_then(Self::try_new)
636 }
637
638 pub fn round_ties_even(&self, n: i32) -> Self {
648 self.checked_round_ties_even(n).unwrap()
649 }
650
651 pub fn checked_floor(&self) -> Option<Self> {
654 if S > 0 {
655 Self::try_new(div_floor(self.0, Self::scale()) * Self::scale())
656 } else {
657 Some(*self)
658 }
659 }
660
661 pub fn floor(&self) -> Self {
669 self.checked_floor().unwrap()
670 }
671
672 pub fn truncate(&self) -> Self {
675 Self(self.0 / Self::scale() * Self::scale())
676 }
677
678 pub fn checked_ceil(&self) -> Option<Self> {
681 if S > 0 {
682 Self::try_new(div_ceil(self.0, Self::scale()) * Self::scale())
683 } else {
684 Some(*self)
685 }
686 }
687
688 pub fn ceil(&self) -> Self {
696 self.checked_ceil().unwrap()
697 }
698
699 pub fn sign(&self) -> Fixed<1, 0> {
702 self.checked_sign_generic().unwrap()
703 }
704
705 pub fn checked_recip(&self) -> Option<Self> {
708 if S < P {
709 Self(Self::scale()).checked_div(self)
710 } else {
711 None
715 }
716 }
717
718 pub fn recip(&self) -> Self {
725 self.checked_recip().unwrap()
726 }
727
728 pub fn checked_powi(&self, exp: i32) -> Option<Self> {
738 if self.is_zero() {
739 (exp > 0).then_some(Self::ZERO)
740 } else if exp == 0 {
741 if S < P {
742 Some(Self::ONE)
743 } else {
744 None
746 }
747 } else if exp > 0 {
748 let mut exp = exp.unsigned_abs();
749 let mut base = self.0;
750 let mut base_scale = S as i32;
751 let mut acc = None;
752 loop {
753 if (exp & 1) == 1 {
754 acc = if let Some((acc, acc_scale)) = acc {
755 let (acc, shift) = I256::from_product(acc, base).reduce_to_i128();
756 Some((acc, (acc_scale + base_scale) - shift as i32))
757 } else {
758 Some((base, base_scale))
759 };
760 }
761 exp /= 2;
762 if exp == 0 {
763 let (acc, acc_scale) = acc.unwrap();
764 return Self::try_new_with_exponent(acc, S as i32 - acc_scale);
765 }
766
767 let (next_base, shift) = I256::from_product(base, base).reduce_to_i128();
768 base = next_base;
769 base_scale = base_scale * 2 - shift as i32;
770 }
771 } else {
772 let mut exp = exp.unsigned_abs();
773 let mut base = *self;
774 let mut acc: Option<Fixed<P, S>> = None;
775 loop {
776 if (exp & 1) == 1 {
777 acc = Some(if let Some(acc) = acc {
778 acc.checked_div(&base)
779 } else {
780 base.checked_recip()
781 }?)
782 }
783 exp /= 2;
784 if exp == 0 {
785 return acc;
786 }
787 base *= base;
788 }
789 }
790 }
791
792 pub fn powi(&self, exp: i32) -> Self {
803 self.checked_powi(exp).unwrap()
804 }
805
806 pub fn next_up(&self) -> Option<Self> {
809 if *self < Self::MAX {
810 Some(Self(self.0 + 1))
811 } else {
812 None
813 }
814 }
815
816 pub fn next_down(&self) -> Option<Self> {
819 if *self > Self::MIN {
820 Some(Self(self.0 - 1))
821 } else {
822 None
823 }
824 }
825
826 pub fn encode(&self) -> (i128, u8) {
829 (self.0, S as u8)
830 }
831
832 pub fn decode(value: i128, scale: u8) -> Option<Self> {
839 Self::try_new_with_exponent(value, S as i32 - scale as i32)
840 }
841}
842
843impl<const P0: usize, const S0: usize> Fixed<P0, S0> {
844 pub fn convert<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
853 Fixed::try_new_with_exponent(self.0, S1 as i32 - S0 as i32)
854 }
855
856 pub fn convert_round_even<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
861 Fixed::try_new_with_exponent_round_even(self.0, S1 as i32 - S0 as i32)
862 }
863
864 pub fn checked_sign_generic<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
868 let one = Fixed::<P1, S1>::scale();
869 match self.0.cmp(&0) {
870 Ordering::Less if S1 < P1 => Some(Fixed(-one)),
871 Ordering::Equal => Some(Fixed::ZERO),
872 Ordering::Greater if S1 < P1 => Some(Fixed(one)),
873 _ => None,
874 }
875 }
876
877 pub fn checked_add_generic<
883 const P1: usize,
884 const S1: usize,
885 const P2: usize,
886 const S2: usize,
887 >(
888 self,
889 other: Fixed<P1, S1>,
890 ) -> Option<Fixed<P2, S2>> {
891 match S0.cmp(&S1) {
892 Ordering::Less => {
893 let factor = pow10(S1 - S0);
894 if self.0 <= i128::MAX / factor / 10 {
895 Fixed::try_new_with_exponent(
896 other.0.checked_add(self.0 * factor)?,
897 S2 as i32 - S1 as i32,
898 )
899 } else {
900 let result = (I256::from_product(self.0, factor) + I256::from(other.0))
901 .narrowing_div(pow10(S2.saturating_sub(S1)))?;
902 Fixed::try_new_with_exponent(result, S1.saturating_sub(S2) as i32)
903 }
904 }
905 Ordering::Equal => {
906 Fixed::try_new_with_exponent(self.0.checked_add(other.0)?, (S2 - S0) as i32)
907 }
908 Ordering::Greater => {
909 let factor = pow10(S0 - S1);
910 if other.0 <= i128::MAX / factor / 10 {
911 Fixed::try_new_with_exponent(
912 self.0.checked_add(other.0 * factor)?,
913 S2 as i32 - S0 as i32,
914 )
915 } else {
916 let result = (I256::from_product(other.0, factor) + I256::from(self.0))
917 .narrowing_div(pow10(S2.saturating_sub(S0)))?;
918 Fixed::try_new_with_exponent(result, S0.saturating_sub(S2) as i32)
919 }
920 }
921 }
922 }
923
924 pub fn checked_sub_generic<
930 const P1: usize,
931 const S1: usize,
932 const P2: usize,
933 const S2: usize,
934 >(
935 self,
936 other: Fixed<P1, S1>,
937 ) -> Option<Fixed<P2, S2>> {
938 self.checked_add_generic(-other)
939 }
940
941 pub fn checked_mul_generic<
947 const P1: usize,
948 const S1: usize,
949 const P2: usize,
950 const S2: usize,
951 >(
952 self,
953 other: Fixed<P1, S1>,
954 ) -> Option<Fixed<P2, S2>> {
955 Fixed::<P2, S2>::try_new_with_exponent(
956 I256::from_product(self.0, other.0)
957 .narrowing_div(pow10((S0 + S1).saturating_sub(S2)))?,
958 S2.saturating_sub(S0 + S1) as i32,
959 )
960 }
961
962 pub fn checked_div_generic<
968 const P1: usize,
969 const S1: usize,
970 const P2: usize,
971 const S2: usize,
972 >(
973 self,
974 other: Fixed<P1, S1>,
975 ) -> Option<Fixed<P2, S2>> {
976 if other == 0 {
977 None
978 } else {
979 let shift_left = (S1 + S2).saturating_sub(S0);
980 if shift_left > 38 {
981 None
985 } else {
986 Fixed::try_new_with_exponent(
987 I256::from_product(self.0, pow10(shift_left)).narrowing_div(other.0)?,
988 S0.saturating_sub(S1 + S2) as i32,
989 )
990 }
991 }
992 }
993
994 pub fn strict_add_generic<
997 const P1: usize,
998 const S1: usize,
999 const P2: usize,
1000 const S2: usize,
1001 >(
1002 self,
1003 other: Fixed<P1, S1>,
1004 ) -> Fixed<P2, S2> {
1005 self.checked_add_generic(other).unwrap()
1006 }
1007
1008 pub fn strict_sub_generic<
1011 const P1: usize,
1012 const S1: usize,
1013 const P2: usize,
1014 const S2: usize,
1015 >(
1016 self,
1017 other: Fixed<P1, S1>,
1018 ) -> Fixed<P2, S2> {
1019 self.checked_sub_generic(other).unwrap()
1020 }
1021
1022 pub fn strict_mul_generic<
1025 const P1: usize,
1026 const S1: usize,
1027 const P2: usize,
1028 const S2: usize,
1029 >(
1030 self,
1031 other: Fixed<P1, S1>,
1032 ) -> Fixed<P2, S2> {
1033 self.checked_mul_generic(other).unwrap()
1034 }
1035
1036 pub fn strict_div_generic<
1039 const P1: usize,
1040 const S1: usize,
1041 const P2: usize,
1042 const S2: usize,
1043 >(
1044 self,
1045 other: Fixed<P1, S1>,
1046 ) -> Fixed<P2, S2> {
1047 self.checked_div_generic(other).unwrap()
1048 }
1049}
1050
1051impl<const P: usize, const S: usize> Zero for Fixed<P, S> {
1052 fn zero() -> Self {
1053 Self::ZERO
1054 }
1055
1056 fn is_zero(&self) -> bool {
1057 *self == Self::ZERO
1058 }
1059}
1060
1061impl<const P: usize, const S: usize> One for Fixed<P, S> {
1062 fn one() -> Self {
1064 Self::ONE
1065 }
1066}
1067
1068impl<const P: usize, const S: usize> TryFrom<f64> for Fixed<P, S> {
1069 type Error = OutOfRange;
1070
1071 fn try_from(value: f64) -> Result<Self, Self::Error> {
1074 cast(value * Self::scale() as f64)
1075 .and_then(Self::try_new)
1076 .ok_or(OutOfRange)
1077 }
1078}
1079
1080impl<const P: usize, const S: usize> From<Fixed<P, S>> for f64 {
1081 fn from(value: Fixed<P, S>) -> Self {
1082 value.0 as f64 / Fixed::<P, S>::scale() as f64
1083 }
1084}
1085
1086impl<const P: usize, const S: usize> TryFrom<i128> for Fixed<P, S> {
1087 type Error = OutOfRange;
1088
1089 fn try_from(value: i128) -> Result<Self, Self::Error> {
1093 if value.unsigned_abs() <= Self::max_u128() {
1094 Ok(Self(value * Self::scale()))
1095 } else {
1096 Err(OutOfRange)
1097 }
1098 }
1099}
1100
1101macro_rules! try_from_signed_int {
1102 ($type_name:ty) => {
1103 impl<const P: usize, const S: usize> TryFrom<$type_name> for Fixed<P, S> {
1104 type Error = OutOfRange;
1105
1106 fn try_from(value: $type_name) -> Result<Self, Self::Error> {
1109 (value as i128).try_into()
1110 }
1111 }
1112 };
1113}
1114
1115try_from_signed_int!(isize);
1116try_from_signed_int!(i64);
1117try_from_signed_int!(i32);
1118try_from_signed_int!(i16);
1119try_from_signed_int!(i8);
1120
1121impl<const P: usize, const S: usize> TryFrom<u128> for Fixed<P, S> {
1122 type Error = OutOfRange;
1123
1124 fn try_from(value: u128) -> Result<Self, Self::Error> {
1128 if value <= Self::max_i128() as u128 {
1129 Ok(Self(value as i128 * Self::scale()))
1130 } else {
1131 Err(OutOfRange)
1132 }
1133 }
1134}
1135
1136macro_rules! try_from_unsigned_int {
1137 ($type_name:ty) => {
1138 impl<const P: usize, const S: usize> TryFrom<$type_name> for Fixed<P, S> {
1139 type Error = OutOfRange;
1140
1141 fn try_from(value: $type_name) -> Result<Self, Self::Error> {
1145 (value as u128).try_into()
1146 }
1147 }
1148 };
1149}
1150
1151try_from_unsigned_int!(usize);
1152try_from_unsigned_int!(u64);
1153try_from_unsigned_int!(u32);
1154try_from_unsigned_int!(u16);
1155try_from_unsigned_int!(u8);
1156
1157macro_rules! min_max_int {
1158 ($signed_type:ty, $max_signed:ident, $min_signed:ident, $unsigned_type:ty, $max_unsigned:ident) => {
1159 #[doc = "Returns the maximum `"]
1160 #[doc = stringify!($signed_type)]
1161 #[doc = "` that can be converted to this type."]
1162 pub const fn $max_signed() -> $signed_type {
1163 if Self::max_i128() > <$signed_type>::MAX as i128 {
1164 <$signed_type>::MAX
1165 } else {
1166 Self::max_i128() as $signed_type
1167 }
1168 }
1169
1170 #[doc = "Returns the minimum `"]
1171 #[doc = stringify!($signed_type)]
1172 #[doc = "` that can be converted to this type."]
1173 pub const fn $min_signed() -> $signed_type {
1174 -Self::$max_signed()
1175 }
1176
1177 #[doc = "Returns the maximum `"]
1178 #[doc = stringify!($unsigned_type)]
1179 #[doc = "` that can be converted to this type.\n\nThe minimum is 0."]
1180 pub const fn $max_unsigned() -> $unsigned_type {
1181 if Self::max_u128() > <$unsigned_type>::MAX as u128 {
1182 <$unsigned_type>::MAX
1183 } else {
1184 Self::max_u128() as $unsigned_type
1185 }
1186 }
1187 };
1188}
1189
1190impl<const P: usize, const S: usize> Fixed<P, S> {
1191 pub const fn max_i128() -> i128 {
1193 if P > S {
1194 pow10(P - S) - 1
1195 } else {
1196 0
1197 }
1198 }
1199
1200 pub const fn min_i128() -> i128 {
1202 -Self::max_i128()
1203 }
1204
1205 pub const fn max_u128() -> u128 {
1209 Self::max_i128().cast_unsigned()
1210 }
1211
1212 min_max_int!(isize, max_isize, min_isize, usize, max_usize);
1213 min_max_int!(i64, max_i64, min_i64, u64, max_u64);
1214 min_max_int!(i32, max_i32, min_i32, u32, max_u32);
1215 min_max_int!(i16, max_i16, min_i16, u16, max_u16);
1216 min_max_int!(i8, max_i8, min_i8, u8, max_u8);
1217}
1218
1219impl<const P: usize, const S: usize> From<Fixed<P, S>> for i128 {
1220 fn from(value: Fixed<P, S>) -> Self {
1223 value.0 / <Fixed<P, S>>::scale()
1225 }
1226}
1227
1228macro_rules! try_to_signed_int {
1229 ($type_name:ty) => {
1230 impl<const P: usize, const S: usize> TryFrom<Fixed<P, S>> for $type_name {
1231 type Error = OutOfRange;
1232
1233 fn try_from(value: Fixed<P, S>) -> Result<Self, Self::Error> {
1236 i128::from(value).try_into().map_err(|_| OutOfRange)
1237 }
1238 }
1239 };
1240}
1241
1242try_to_signed_int!(i64);
1243try_to_signed_int!(i32);
1244try_to_signed_int!(i16);
1245try_to_signed_int!(i8);
1246try_to_signed_int!(isize);
1247
1248macro_rules! try_to_unsigned_int {
1251 ($type_name:ty) => {
1252 impl<const P: usize, const S: usize> TryFrom<Fixed<P, S>> for $type_name {
1253 type Error = OutOfRange;
1254
1255 fn try_from(value: Fixed<P, S>) -> Result<Self, Self::Error> {
1261 i128::from(value).try_into().map_err(|_| OutOfRange)
1262 }
1263 }
1264 };
1265}
1266
1267try_to_unsigned_int!(u128);
1268try_to_unsigned_int!(u64);
1269try_to_unsigned_int!(u32);
1270try_to_unsigned_int!(u16);
1271try_to_unsigned_int!(u8);
1272try_to_unsigned_int!(usize);
1273
1274impl<const P: usize, const S: usize> Add for Fixed<P, S> {
1275 type Output = Self;
1276
1277 fn add(self, other: Self) -> Self::Output {
1283 self.checked_add(&other).unwrap()
1284 }
1285}
1286
1287impl<const P: usize, const S: usize> Add for &Fixed<P, S> {
1288 type Output = Fixed<P, S>;
1289
1290 fn add(self, other: Self) -> Self::Output {
1296 self.checked_add(other).unwrap()
1297 }
1298}
1299
1300impl<const P: usize, const S: usize> CheckedAdd for Fixed<P, S> {
1301 fn checked_add(&self, other: &Self) -> Option<Self> {
1304 self.checked_add_generic(*other)
1305 }
1306}
1307
1308impl<const P: usize, const S: usize> AddAssign for Fixed<P, S> {
1309 fn add_assign(&mut self, other: Self) {
1315 *self = *self + other;
1316 }
1317}
1318
1319impl<const P: usize, const S: usize> AddAssign<&Fixed<P, S>> for Fixed<P, S> {
1320 fn add_assign(&mut self, other: &Fixed<P, S>) {
1326 *self = *self + *other;
1327 }
1328}
1329
1330impl<const P: usize, const S: usize> Sub for Fixed<P, S> {
1331 type Output = Self;
1332
1333 fn sub(self, other: Self) -> Self::Output {
1339 self.checked_sub(&other).unwrap()
1340 }
1341}
1342
1343impl<const P: usize, const S: usize> Sub for &Fixed<P, S> {
1344 type Output = Fixed<P, S>;
1345
1346 fn sub(self, other: Self) -> Self::Output {
1352 self.checked_sub(other).unwrap()
1353 }
1354}
1355
1356impl<const P: usize, const S: usize> CheckedSub for Fixed<P, S> {
1357 fn checked_sub(&self, other: &Self) -> Option<Self> {
1360 self.checked_sub_generic(*other)
1361 }
1362}
1363
1364impl<const P: usize, const S: usize> SubAssign for Fixed<P, S> {
1365 fn sub_assign(&mut self, other: Self) {
1371 *self = *self - other;
1372 }
1373}
1374
1375impl<const P: usize, const S: usize> Mul for Fixed<P, S> {
1376 type Output = Self;
1377
1378 fn mul(self, other: Self) -> Self::Output {
1384 self.checked_mul(&other).unwrap()
1385 }
1386}
1387
1388impl<const P: usize, const S: usize> Mul for &Fixed<P, S> {
1389 type Output = Fixed<P, S>;
1390
1391 fn mul(self, other: Self) -> Self::Output {
1397 self.checked_mul(other).unwrap()
1398 }
1399}
1400
1401impl<const P: usize, const S: usize> CheckedMul for Fixed<P, S> {
1402 fn checked_mul(&self, other: &Self) -> Option<Self> {
1405 Self::checked_mul_generic(*self, *other)
1406 }
1407}
1408
1409impl<const P: usize, const S: usize> MulAssign for Fixed<P, S> {
1410 fn mul_assign(&mut self, other: Self) {
1416 *self = *self * other;
1417 }
1418}
1419
1420impl<const P: usize, const S: usize> Div for Fixed<P, S> {
1421 type Output = Self;
1422
1423 fn div(self, other: Self) -> Self::Output {
1429 self.checked_div(&other).unwrap()
1430 }
1431}
1432
1433impl<const P: usize, const S: usize> Div for &Fixed<P, S> {
1434 type Output = Fixed<P, S>;
1435
1436 fn div(self, other: Self) -> Self::Output {
1442 self.checked_div(other).unwrap()
1443 }
1444}
1445
1446impl<const P: usize, const S: usize> CheckedDiv for Fixed<P, S> {
1447 fn checked_div(&self, other: &Self) -> Option<Self> {
1450 Self::checked_div_generic(*self, *other)
1451 }
1452}
1453
1454impl<const P: usize, const S: usize> DivAssign for Fixed<P, S> {
1455 fn div_assign(&mut self, other: Self) {
1461 *self = *self / other;
1462 }
1463}
1464
1465impl<const P: usize, const S: usize> Neg for Fixed<P, S> {
1466 type Output = Self;
1467
1468 fn neg(self) -> Self::Output {
1470 Self(-self.0)
1471 }
1472}
1473
1474impl<const P: usize, const S: usize> Neg for &Fixed<P, S> {
1475 type Output = Fixed<P, S>;
1476
1477 fn neg(self) -> Self::Output {
1479 Fixed(-self.0)
1480 }
1481}
1482
1483#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1485pub enum ParseFixedError {
1486 SyntaxError,
1488
1489 OutOfRange,
1494}
1495
1496impl<const P: usize, const S: usize> FromStr for Fixed<P, S> {
1497 type Err = ParseFixedError;
1498
1499 fn from_str(s: &str) -> Result<Self, Self::Err> {
1506 fn inner(s: &str, scale: i32) -> Result<(i128, i32), ParseFixedError> {
1508 let mut value = 0;
1511 let mut exponent = scale;
1512
1513 let mut saw_dot = false;
1514 let mut saw_digit = false;
1515
1516 let mut sign = None;
1517 enum Sign {
1518 Positive,
1519 Negative,
1520 }
1521
1522 let mut iter = s.chars();
1523 while let Some(c) = iter.next() {
1524 match c {
1525 '-' | '+' if sign.is_some() => return Err(ParseFixedError::SyntaxError),
1526 '-' => {
1527 sign = Some(Sign::Negative);
1528 }
1529 '+' => {
1530 sign = Some(Sign::Positive);
1531 }
1532 '0'..='9' => {
1533 saw_digit = true;
1534 if value < i128::MAX / 10 {
1535 value = value * 10 + (c as u8 - b'0') as i128;
1536 if saw_dot {
1537 exponent -= 1;
1538 }
1539 } else if !saw_dot {
1540 exponent =
1541 exponent.checked_add(1).ok_or(ParseFixedError::OutOfRange)?;
1542 }
1543 }
1544 '.' => {
1545 if saw_dot {
1546 return Err(ParseFixedError::SyntaxError);
1547 }
1548 saw_dot = true;
1549 }
1550 'e' | 'E' => {
1551 if !saw_digit {
1552 return Err(ParseFixedError::SyntaxError);
1553 }
1554 let e: i32 = match iter.as_str().parse() {
1555 Ok(e) => e,
1556 Err(error) => {
1557 return match error.kind() {
1558 IntErrorKind::Zero => unreachable!(),
1559 IntErrorKind::PosOverflow => {
1560 if value != 0 {
1561 Err(ParseFixedError::OutOfRange)
1562 } else {
1563 Ok((0, 0))
1564 }
1565 }
1566 IntErrorKind::NegOverflow => Ok((0, 0)),
1567 _ => Err(ParseFixedError::SyntaxError),
1568 }
1569 }
1570 };
1571 exponent = match exponent.checked_add(e) {
1572 Some(exponent) => exponent,
1573 None => {
1574 if e > 0 {
1575 debug_assert_ne!(value, 0);
1580 return Err(ParseFixedError::OutOfRange);
1581 } else {
1582 return Ok((0, 0));
1583 }
1584 }
1585 };
1586 break;
1587 }
1588 _ => return Err(ParseFixedError::SyntaxError),
1589 }
1590 }
1591 if !saw_digit {
1592 return Err(ParseFixedError::SyntaxError);
1593 }
1594 let value = match sign {
1595 Some(Sign::Negative) => -value,
1596 _ => value,
1597 };
1598 Ok((value, exponent))
1599 }
1600
1601 let (value, exponent) = inner(s, S as i32)?;
1602 Self::try_new_with_exponent_round_even(value, exponent).ok_or(ParseFixedError::OutOfRange)
1603 }
1604}
1605
1606fn _invalid_constant_test() {}
1616
1617#[cfg(test)]
1618mod test {
1619 use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub};
1620
1621 use crate::{Fixed, ParseFixedError};
1622 use std::{fmt::Write, str::FromStr};
1623
1624 #[test]
1625 fn from_str() {
1626 const VAR_NAME: f64 = 0.0;
1627 for (s, expect) in [
1628 ("0", Ok(0.0)),
1629 ("0.", Ok(0.0)),
1630 (".0", Ok(0.0)),
1631 ("-0", Ok(-0.0)),
1632 ("+0", Ok(-0.0)),
1633 ("--0", Err(ParseFixedError::SyntaxError)),
1634 ("-+0", Err(ParseFixedError::SyntaxError)),
1635 ("0x", Err(ParseFixedError::SyntaxError)),
1636 ("0e5x", Err(ParseFixedError::SyntaxError)),
1637 ("1.23", Ok(1.23)),
1638 ("-1.23", Ok(-1.23)),
1639 ("+1.23", Ok(1.23)),
1640 ("99999999", Ok(9999_9999.0)),
1641 ("999999999", Err(ParseFixedError::OutOfRange)),
1642 ("999999999E-1", Ok(9999_9999.9)),
1643 ("9999999999e-1", Err(ParseFixedError::OutOfRange)),
1644 ("9999999999E-2", Ok(9999_9999.99)),
1645 ("99999999999e-2", Err(ParseFixedError::OutOfRange)),
1646 ("99999999999e-3", Err(ParseFixedError::OutOfRange)),
1649 ("99999999991e-3", Ok(9999_9999.99)),
1651 (
1655 "111111111111111111111111111111111111111111e-34",
1656 Ok(1111_1111.11),
1657 ),
1658 (
1662 "1.23456788901234567890123456789012345678890123456",
1663 Ok(1.23),
1664 ),
1665 ("1e999999999999999", Err(ParseFixedError::OutOfRange)),
1667 ("0e999999999999999", Ok(0.0)),
1669 ("1e-999999999999999", Ok(VAR_NAME)),
1671 (
1675 "111111111111111111111111111111111111111111e2147483644",
1676 Err(ParseFixedError::OutOfRange),
1677 ),
1678 (
1681 ".1111111111111111111111111111111111111111e-2147483648",
1682 Ok(0.0),
1683 ),
1684 ("123e5", Ok(12_300_000.0)),
1685 ("123E4", Ok(1_230_000.0)),
1686 ("123e3", Ok(123_000.0)),
1687 ("123e2", Ok(12_300.0)),
1688 ("123e1", Ok(1_230.0)),
1689 ("123e0", Ok(123.0)),
1690 ("123e-1", Ok(12.3)),
1691 ("123e-2", Ok(1.23)),
1692 (".123", Ok(0.12)),
1693 (".124", Ok(0.12)),
1694 (".125", Ok(0.12)),
1695 (".126", Ok(0.13)),
1696 (".133", Ok(0.13)),
1697 (".134", Ok(0.13)),
1698 (".135", Ok(0.14)),
1699 (".136", Ok(0.14)),
1700 ] {
1701 println!("{s}: {:?}", s.parse::<F>());
1702 assert_eq!(s.parse::<F>(), expect.map(f));
1703 }
1704 }
1705
1706 #[test]
1707 fn debug() {
1708 assert_eq!(format!("{:?}", Fixed::<20, 7>::try_from(0).unwrap()), "0");
1709 assert_eq!(
1710 format!("{:?}", Fixed::<20, 7>::try_from(0.0001).unwrap()),
1711 "0.0001"
1712 );
1713 assert_eq!(
1714 format!("{:?}", Fixed::<20, 7>::try_from(-0.0001).unwrap()),
1715 "-0.0001"
1716 );
1717 assert_eq!(
1718 format!("{:?}", Fixed::<20, 7>::try_from(1.0001).unwrap()),
1719 "1.0001"
1720 );
1721 assert_eq!(
1722 format!("{:?}", Fixed::<20, 7>::try_from(-1.0001).unwrap()),
1723 "-1.0001"
1724 );
1725 assert_eq!(
1726 format!("{:?}", Fixed::<20, 7>::try_from(1.682501).unwrap()),
1727 "1.682501"
1728 );
1729 assert_eq!(
1730 format!("{:?}", Fixed::<20, 4>::try_from(1.6825).unwrap()),
1731 "1.6825"
1732 );
1733 assert_eq!(
1734 format!("{:?}", Fixed::<20, 6>::try_from(1.995670).unwrap()),
1735 "1.99567"
1736 );
1737 assert_eq!(
1738 format!("{:?}", Fixed::<20, 6>::try_from(0.995670).unwrap()),
1739 "0.99567"
1740 );
1741 assert_eq!(
1742 format!("{:?}", Fixed::<6, 6>::try_from(0.995670).unwrap()),
1743 "0.99567"
1744 );
1745
1746 assert_eq!(
1747 format!("{:?}", Fixed::<20, 7>::try_from(-1.682501).unwrap()),
1748 "-1.682501"
1749 );
1750 assert_eq!(
1751 format!("{:?}", Fixed::<20, 4>::try_from(-1.6825).unwrap()),
1752 "-1.6825"
1753 );
1754 assert_eq!(
1755 format!("{:?}", Fixed::<20, 6>::try_from(-1.995670).unwrap()),
1756 "-1.99567"
1757 );
1758 assert_eq!(
1759 format!("{:?}", Fixed::<20, 6>::try_from(-0.995670).unwrap()),
1760 "-0.99567"
1761 );
1762 }
1763
1764 fn multidisplay<const P: usize, const S: usize>(number: Fixed<P, S>) -> String {
1765 let mut s = String::new();
1766 write!(&mut s, "{number}").unwrap();
1767 for precision in 0..=S + 1 {
1768 write!(&mut s, " {number:.0$}", precision).unwrap();
1769 }
1770 s
1771 }
1772
1773 #[test]
1774 fn display() {
1775 assert_eq!(
1776 multidisplay(Fixed::<20, 7>::try_from(0.0001).unwrap()),
1777 "0.0001 0 0.0 0.00 0.000 0.0001 0.00010 0.000100 0.0001000 0.00010000"
1778 );
1779 assert_eq!(
1780 multidisplay(Fixed::<20, 7>::try_from(-0.0001).unwrap()),
1781 "-0.0001 -0 -0.0 -0.00 -0.000 -0.0001 -0.00010 -0.000100 -0.0001000 -0.00010000"
1782 );
1783 assert_eq!(
1784 multidisplay(Fixed::<20, 7>::try_from(1.0001).unwrap()),
1785 "1.0001 1 1.0 1.00 1.000 1.0001 1.00010 1.000100 1.0001000 1.00010000"
1786 );
1787 assert_eq!(
1788 multidisplay(Fixed::<20, 7>::try_from(-1.0001).unwrap()),
1789 "-1.0001 -1 -1.0 -1.00 -1.000 -1.0001 -1.00010 -1.000100 -1.0001000 -1.00010000"
1790 );
1791 assert_eq!(
1792 multidisplay(Fixed::<20, 7>::try_from(1.682501).unwrap()),
1793 "1.682501 2 1.7 1.68 1.683 1.6825 1.68250 1.682501 1.6825010 1.68250100"
1794 );
1795 assert_eq!(
1796 multidisplay(Fixed::<20, 4>::try_from(1.6825).unwrap()),
1797 "1.6825 2 1.7 1.68 1.682 1.6825 1.68250"
1798 );
1799 assert_eq!(
1800 multidisplay(Fixed::<20, 6>::try_from(1.995670).unwrap()),
1801 "1.99567 2 2.0 2.00 1.996 1.9957 1.99567 1.995670 1.9956700"
1802 );
1803 assert_eq!(
1804 multidisplay(Fixed::<20, 6>::try_from(0.995670).unwrap()),
1805 "0.99567 1 1.0 1.00 0.996 0.9957 0.99567 0.995670 0.9956700"
1806 );
1807 assert_eq!(
1808 multidisplay(Fixed::<6, 6>::try_from(0.995670).unwrap()),
1809 "0.99567 1 1.0 1.00 0.996 0.9957 0.99567 0.995670 0.9956700"
1810 );
1811
1812 assert_eq!(
1813 multidisplay(Fixed::<20, 7>::try_from(-1.682501).unwrap()),
1814 "-1.682501 -2 -1.7 -1.68 -1.683 -1.6825 -1.68250 -1.682501 -1.6825010 -1.68250100"
1815 );
1816 assert_eq!(
1817 multidisplay(Fixed::<20, 4>::try_from(-1.6825).unwrap()),
1818 "-1.6825 -2 -1.7 -1.68 -1.682 -1.6825 -1.68250"
1819 );
1820 assert_eq!(
1821 multidisplay(Fixed::<20, 6>::try_from(-1.995670).unwrap()),
1822 "-1.99567 -2 -2.0 -2.00 -1.996 -1.9957 -1.99567 -1.995670 -1.9956700"
1823 );
1824 assert_eq!(
1825 multidisplay(Fixed::<20, 6>::try_from(-0.995670).unwrap()),
1826 "-0.99567 -1 -1.0 -1.00 -0.996 -0.9957 -0.99567 -0.995670 -0.9956700"
1827 );
1828 }
1829
1830 type F = Fixed<10, 2>;
1831 fn f(n: f64) -> F {
1832 Fixed::try_from(n).unwrap()
1833 }
1834
1835 fn f38_0(n: f64) -> Fixed<38, 0> {
1836 Fixed::try_from(n).unwrap()
1837 }
1838
1839 fn f38_38(s: &str) -> Fixed<38, 38> {
1840 Fixed::from_str(s).unwrap()
1841 }
1842
1843 #[test]
1844 fn mul() {
1845 assert_eq!(f(1.23) * f(2.34), f(2.87));
1847 assert_eq!(f(-1.23) * f(2.34), f(-2.87));
1848 assert_eq!(f(1.23) * f(-2.34), f(-2.87));
1849 assert_eq!(f(-1.23) * f(-2.34), f(2.87));
1850
1851 for a in -999..=999 {
1853 let af: Fixed<10, 2> = Fixed(a);
1854 for b in -999..=999 {
1855 let bf: Fixed<10, 2> = Fixed(b);
1856 assert_eq!(af * bf, Fixed::<10, 2>(a * b / 100));
1857 }
1858 }
1859
1860 for a in -999..=999 {
1862 let af: Fixed<3, 2> = Fixed(a);
1863 for b in -999..=999 {
1864 let bf: Fixed<3, 2> = Fixed(b);
1865 let c = a * b / 100;
1866 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1867 assert_eq!(af.checked_mul(&bf), expected);
1868 }
1869 }
1870 }
1871
1872 #[test]
1873 fn mul_generic() {
1874 for a in -999..=999 {
1875 let af: Fixed<10, 2> = Fixed(a);
1876 for b in -999..=999 {
1877 let bf: Fixed<10, 3> = Fixed(b);
1878 let cf: Fixed<10, 5> = af.checked_mul_generic(bf).unwrap();
1879 assert_eq!(cf, Fixed::<10, 5>(a * b));
1880 let df: Fixed<10, 6> = af.checked_mul_generic(bf).unwrap();
1881 assert_eq!(df, Fixed::<10, 6>(a * b * 10));
1882 let ef: Fixed<10, 0> = af.checked_mul_generic(bf).unwrap();
1883 assert_eq!(ef, Fixed::<10, 0>(a * b / 100_000));
1884 }
1885 }
1886 }
1887
1888 #[test]
1889 fn div() {
1890 assert_eq!(f(1.23) / f(2.34), f(0.52));
1892 assert_eq!(f(-1.23) / f(2.34), f(-0.52));
1893 assert_eq!(f(1.23) / f(-2.34), f(-0.52));
1894 assert_eq!(f(-1.23) / f(-2.34), f(0.52));
1895 assert_eq!(
1896 f38_0(1.0)
1897 .checked_div_generic::<38, 0, 38, 38>(f38_0(7.0))
1898 .unwrap(),
1899 f38_38("0.14285714285714285714285714285714285714")
1900 );
1901
1902 assert_eq!(
1903 f38_0(123.0).checked_div_generic::<38, 38, 38, 38>(f38_38("0.456")),
1904 None
1905 );
1906
1907 for a in -999..=999 {
1909 let af: Fixed<10, 2> = Fixed(a);
1910 for b in -999..=999 {
1911 let bf: Fixed<10, 2> = Fixed(b);
1912 assert_eq!(af.checked_div(&bf), (b != 0).then(|| Fixed(a * 100 / b)));
1913 }
1914 }
1915
1916 for a in -999..=999 {
1918 let af: Fixed<3, 2> = Fixed(a);
1919 for b in -999..=999 {
1920 let bf: Fixed<3, 2> = Fixed(b);
1921 let expected = if b != 0 {
1922 let result = a * 100 / b;
1923 (result.unsigned_abs() <= 999).then_some(Fixed(result))
1924 } else {
1925 None
1926 };
1927 assert_eq!(af.checked_div(&bf), expected);
1928 }
1929 }
1930 }
1931
1932 #[test]
1933 fn div_generic() {
1934 for a in -999..=999 {
1935 let af: Fixed<10, 2> = Fixed(a);
1936 for b in -999..=999 {
1937 if b != 0 {
1938 let bf: Fixed<10, 3> = Fixed(b);
1939 let cf: Fixed<10, 5> = af.checked_div_generic(bf).unwrap();
1940 assert_eq!(cf, Fixed::<10, 5>(a * 1_000_000 / b));
1941 let df: Fixed<10, 6> = af.checked_div_generic(bf).unwrap();
1942 assert_eq!(df, Fixed::<10, 6>(a * 10_000_000 / b));
1943 let ef: Fixed<10, 0> = af.checked_div_generic(bf).unwrap();
1944 assert_eq!(ef, Fixed::<10, 0>(a * 10 / b));
1945 }
1946 }
1947 }
1948 }
1949
1950 #[test]
1951 fn add() {
1952 assert_eq!(f(1.23) + f(2.34), f(3.57));
1954 assert_eq!(f(-1.23) + f(2.34), f(1.11));
1955 assert_eq!(f(1.23) + f(-2.34), f(-1.11));
1956 assert_eq!(f(-1.23) + f(-2.34), f(-3.57));
1957
1958 for a in -999..=999 {
1960 let af: Fixed<10, 2> = Fixed(a);
1961 for b in -999..=999 {
1962 let bf: Fixed<10, 2> = Fixed(b);
1963 assert_eq!(af + bf, Fixed::<10, 2>(a + b));
1964 }
1965 }
1966
1967 for a in -999..=999 {
1969 let af: Fixed<3, 2> = Fixed(a);
1970 for b in -999..=999 {
1971 let bf: Fixed<3, 2> = Fixed(b);
1972 let c = a + b;
1973 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1974 assert_eq!(af.checked_add(&bf), expected);
1975 }
1976 }
1977
1978 for a in -999..=999 {
1980 let af: Fixed<10, 2> = Fixed(a);
1981 for b in -999..=999 {
1982 let bf: Fixed<10, 3> = Fixed(b);
1983 let cf: Fixed<10, 5> = af.checked_add_generic(bf).unwrap();
1984 assert_eq!(
1985 cf,
1986 Fixed::<10, 5>(a * 1000 + b * 100),
1987 "{af} + {bf} ?= {cf}"
1988 );
1989 let cf: Fixed<10, 5> = bf.checked_add_generic(af).unwrap();
1990 assert_eq!(
1991 cf,
1992 Fixed::<10, 5>(a * 1000 + b * 100),
1993 "{bf} + {af} ?= {cf}"
1994 );
1995 let df: Fixed<10, 6> = af.checked_add_generic(bf).unwrap();
1996 assert_eq!(
1997 df,
1998 Fixed::<10, 6>(a * 10_000 + b * 1000),
1999 "{af} + {bf} ?= {df}"
2000 );
2001 let ef: Fixed<10, 0> = af.checked_add_generic(bf).unwrap();
2002 assert_eq!(
2003 ef,
2004 Fixed::<10, 0>((a * 10 + b) / 1000),
2005 "{af} + {bf} ?= {ef}"
2006 );
2007 }
2008 }
2009 }
2010
2011 #[test]
2012 fn sub() {
2013 assert_eq!(f(1.23) - f(2.34), f(-1.11));
2015 assert_eq!(f(-1.23) - f(2.34), f(-3.57));
2016 assert_eq!(f(1.23) - f(-2.34), f(3.57));
2017 assert_eq!(f(-1.23) - f(-2.34), f(1.11));
2018
2019 for a in -999..=999 {
2021 let af: Fixed<10, 2> = Fixed(a);
2022 for b in -999..=999 {
2023 let bf: Fixed<10, 2> = Fixed(b);
2024 assert_eq!(af - bf, Fixed::<10, 2>(a - b));
2025 }
2026 }
2027
2028 for a in -999..=999 {
2030 let af: Fixed<3, 2> = Fixed(a);
2031 for b in -999..=999 {
2032 let bf: Fixed<3, 2> = Fixed(b);
2033 let c = a - b;
2034 let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
2035 assert_eq!(af.checked_sub(&bf), expected);
2036 }
2037 }
2038
2039 for a in -999..=999 {
2041 let af: Fixed<10, 2> = Fixed(a);
2042 for b in -999..=999 {
2043 let bf: Fixed<10, 3> = Fixed(b);
2044 let cf: Fixed<10, 5> = af.checked_sub_generic(bf).unwrap();
2045 assert_eq!(
2046 cf,
2047 Fixed::<10, 5>(a * 1000 - b * 100),
2048 "{af} - {bf} ?= {cf}"
2049 );
2050 let cf: Fixed<10, 5> = bf.checked_sub_generic(af).unwrap();
2051 assert_eq!(
2052 cf,
2053 Fixed::<10, 5>(b * 100 - a * 1000),
2054 "{bf} - {af} ?= {cf}"
2055 );
2056 let df: Fixed<10, 6> = af.checked_sub_generic(bf).unwrap();
2057 assert_eq!(df, Fixed::<10, 6>(a * 10_000 - b * 1000));
2058 }
2059 }
2060 }
2061
2062 #[test]
2063 fn powi() {
2064 assert_eq!(
2065 Fixed::<10, 8>::from_str("1.12345678")
2066 .unwrap()
2067 .powi(8)
2068 .to_string()
2069 .as_str(),
2070 "2.53776238"
2071 );
2072 assert_eq!(f(2.0).powi(3), f(8.0));
2073 assert_eq!(f(-2.0).powi(3), f(-8.0));
2074 assert_eq!(f(1.7).powi(8), f(69.75));
2075 assert_eq!(f(1.7).powi(-8), f(0.01));
2076 assert_eq!(f(0.0).powi(1), f(0.0));
2077 assert_eq!(f(0.0).checked_powi(0), None);
2078 assert_eq!(f(0.0).checked_powi(-1), None);
2079 }
2080
2081 #[test]
2082 fn convert() {
2083 let a = Fixed::<10, 10>::from_str("0.0123456789").unwrap();
2084 assert_eq!(&a.convert::<10, 0>().unwrap().to_string(), "0");
2085 assert_eq!(&a.convert::<10, 1>().unwrap().to_string(), "0");
2086 assert_eq!(&a.convert::<10, 2>().unwrap().to_string(), "0.01");
2087 assert_eq!(&a.convert::<10, 3>().unwrap().to_string(), "0.012");
2088 assert_eq!(&a.convert::<10, 4>().unwrap().to_string(), "0.0123");
2089 assert_eq!(&a.convert::<10, 5>().unwrap().to_string(), "0.01234");
2090 assert_eq!(&a.convert::<10, 6>().unwrap().to_string(), "0.012345");
2091 assert_eq!(&a.convert::<10, 7>().unwrap().to_string(), "0.0123456");
2092 assert_eq!(&a.convert::<10, 8>().unwrap().to_string(), "0.01234567");
2093 assert_eq!(&a.convert::<10, 9>().unwrap().to_string(), "0.012345678");
2094 assert_eq!(&a.convert::<10, 10>().unwrap().to_string(), "0.0123456789");
2095 assert_eq!(&a.convert_round_even::<10, 0>().unwrap().to_string(), "0");
2096 assert_eq!(&a.convert_round_even::<10, 1>().unwrap().to_string(), "0");
2097 assert_eq!(
2098 &a.convert_round_even::<10, 2>().unwrap().to_string(),
2099 "0.01"
2100 );
2101 assert_eq!(
2102 &a.convert_round_even::<10, 3>().unwrap().to_string(),
2103 "0.012"
2104 );
2105 assert_eq!(
2106 &a.convert_round_even::<10, 4>().unwrap().to_string(),
2107 "0.0123"
2108 );
2109 assert_eq!(
2110 &a.convert_round_even::<10, 5>().unwrap().to_string(),
2111 "0.01235"
2112 );
2113 assert_eq!(
2114 &a.convert_round_even::<10, 6>().unwrap().to_string(),
2115 "0.012346"
2116 );
2117 assert_eq!(
2118 &a.convert_round_even::<10, 7>().unwrap().to_string(),
2119 "0.0123457"
2120 );
2121 assert_eq!(
2122 &a.convert_round_even::<10, 8>().unwrap().to_string(),
2123 "0.01234568"
2124 );
2125 assert_eq!(
2126 &a.convert_round_even::<10, 9>().unwrap().to_string(),
2127 "0.012345679"
2128 );
2129 assert_eq!(
2130 &a.convert_round_even::<10, 10>().unwrap().to_string(),
2131 "0.0123456789"
2132 );
2133
2134 let b = Fixed::<10, 5>::from_str("12345.67895").unwrap();
2135 assert_eq!(&b.convert::<10, 0>().unwrap().to_string(), "12345");
2136 assert_eq!(&b.convert::<10, 1>().unwrap().to_string(), "12345.6");
2137 assert_eq!(&b.convert::<10, 2>().unwrap().to_string(), "12345.67");
2138 assert_eq!(&b.convert::<10, 3>().unwrap().to_string(), "12345.678");
2139 assert_eq!(&b.convert::<10, 4>().unwrap().to_string(), "12345.6789");
2140 assert_eq!(&b.convert::<10, 5>().unwrap().to_string(), "12345.67895");
2141 assert_eq!(b.convert::<10, 6>(), None);
2142 assert_eq!(b.convert::<10, 7>(), None);
2143 assert_eq!(b.convert::<10, 8>(), None);
2144 assert_eq!(b.convert::<10, 9>(), None);
2145 assert_eq!(b.convert::<10, 10>(), None);
2146 assert_eq!(
2147 &b.convert_round_even::<10, 0>().unwrap().to_string(),
2148 "12346"
2149 );
2150 assert_eq!(
2151 &b.convert_round_even::<10, 1>().unwrap().to_string(),
2152 "12345.7"
2153 );
2154 assert_eq!(
2155 &b.convert_round_even::<10, 2>().unwrap().to_string(),
2156 "12345.68"
2157 );
2158 assert_eq!(
2159 &b.convert_round_even::<10, 3>().unwrap().to_string(),
2160 "12345.679"
2161 );
2162 assert_eq!(
2163 &b.convert_round_even::<10, 4>().unwrap().to_string(),
2164 "12345.679"
2165 );
2166 assert_eq!(
2167 &b.convert_round_even::<10, 5>().unwrap().to_string(),
2168 "12345.67895"
2169 );
2170 assert_eq!(b.convert_round_even::<10, 6>(), None);
2171 assert_eq!(b.convert_round_even::<10, 7>(), None);
2172 assert_eq!(b.convert_round_even::<10, 8>(), None);
2173 assert_eq!(b.convert_round_even::<10, 9>(), None);
2174 assert_eq!(b.convert_round_even::<10, 10>(), None);
2175 }
2176
2177 #[test]
2178 fn constants() {
2179 assert_eq!(Fixed::<5, 0>::MAX, Fixed::<5, 0>(99999));
2180 assert_eq!(Fixed::<5, 0>::MIN, Fixed::<5, 0>(-99999));
2181 assert_eq!(Fixed::<5, 0>::ZERO, Fixed::<5, 0>(0));
2182 assert_eq!(Fixed::<5, 0>::ONE, Fixed::<5, 0>(1));
2183
2184 assert_eq!(Fixed::<5, 1>::MAX, Fixed::<5, 1>(99999));
2185 assert_eq!(Fixed::<5, 1>::MIN, Fixed::<5, 1>(-99999));
2186 assert_eq!(Fixed::<5, 1>::ZERO, Fixed::<5, 1>(0));
2187 assert_eq!(Fixed::<5, 1>::ONE, Fixed::<5, 1>(10));
2188
2189 assert_eq!(Fixed::<5, 2>::MAX, Fixed::<5, 2>(99999));
2190 assert_eq!(Fixed::<5, 2>::MIN, Fixed::<5, 2>(-99999));
2191 assert_eq!(Fixed::<5, 2>::ZERO, Fixed::<5, 2>(0));
2192 assert_eq!(Fixed::<5, 2>::ONE, Fixed::<5, 2>(100));
2193
2194 assert_eq!(Fixed::<5, 3>::MAX, Fixed::<5, 3>(99999));
2195 assert_eq!(Fixed::<5, 3>::MIN, Fixed::<5, 3>(-99999));
2196 assert_eq!(Fixed::<5, 3>::ZERO, Fixed::<5, 3>(0));
2197 assert_eq!(Fixed::<5, 3>::ONE, Fixed::<5, 3>(1000));
2198
2199 assert_eq!(Fixed::<5, 4>::MAX, Fixed::<5, 4>(99999));
2200 assert_eq!(Fixed::<5, 4>::MIN, Fixed::<5, 4>(-99999));
2201 assert_eq!(Fixed::<5, 4>::ZERO, Fixed::<5, 4>(0));
2202 assert_eq!(Fixed::<5, 4>::ONE, Fixed::<5, 4>(10000));
2203
2204 assert_eq!(Fixed::<5, 5>::MAX, Fixed::<5, 5>(99999));
2205 assert_eq!(Fixed::<5, 5>::MIN, Fixed::<5, 5>(-99999));
2206 assert_eq!(Fixed::<5, 5>::ZERO, Fixed::<5, 5>(0));
2207 }
2210
2211 #[test]
2212 fn floor() {
2213 assert_eq!(f(5.0).floor(), f(5.0));
2214 assert_eq!(f(5.1).floor(), f(5.0));
2215 assert_eq!(f(5.5).floor(), f(5.0));
2216 assert_eq!(f(5.9).floor(), f(5.0));
2217 assert_eq!(f(-5.0).floor(), f(-5.0));
2218 assert_eq!(f(-5.1).floor(), f(-6.0));
2219 assert_eq!(f(-5.5).floor(), f(-6.0));
2220 assert_eq!(f(-5.6).floor(), f(-6.0));
2221 assert_eq!(f(4.0).floor(), f(4.0));
2222 assert_eq!(f(4.1).floor(), f(4.0));
2223 assert_eq!(f(4.5).floor(), f(4.0));
2224 assert_eq!(f(4.9).floor(), f(4.0));
2225 assert_eq!(f(-4.0).floor(), f(-4.0));
2226 assert_eq!(f(-4.1).floor(), f(-5.0));
2227 assert_eq!(f(-4.5).floor(), f(-5.0));
2228 assert_eq!(f(-4.6).floor(), f(-5.0));
2229 assert_eq!(f(-99_999_999.0).floor(), f(-99_999_999.0));
2230 assert_eq!(f(-99_999_999.1).checked_floor(), None);
2231 assert_eq!(f(-99_999_999.5).checked_floor(), None);
2232 assert_eq!(f(-99_999_999.6).checked_floor(), None);
2233 }
2234
2235 #[test]
2236 fn ceil() {
2237 assert_eq!(f(5.0).ceil(), f(5.0));
2238 assert_eq!(f(5.1).ceil(), f(6.0));
2239 assert_eq!(f(5.5).ceil(), f(6.0));
2240 assert_eq!(f(5.9).ceil(), f(6.0));
2241 assert_eq!(f(-5.0).ceil(), f(-5.0));
2242 assert_eq!(f(-5.1).ceil(), f(-5.0));
2243 assert_eq!(f(-5.5).ceil(), f(-5.0));
2244 assert_eq!(f(-5.6).ceil(), f(-5.0));
2245 assert_eq!(f(4.0).ceil(), f(4.0));
2246 assert_eq!(f(4.1).ceil(), f(5.0));
2247 assert_eq!(f(4.5).ceil(), f(5.0));
2248 assert_eq!(f(4.9).ceil(), f(5.0));
2249 assert_eq!(f(-4.0).ceil(), f(-4.0));
2250 assert_eq!(f(-4.1).ceil(), f(-4.0));
2251 assert_eq!(f(-4.5).ceil(), f(-4.0));
2252 assert_eq!(f(-4.6).ceil(), f(-4.0));
2253 assert_eq!(f(99_999_999.0).ceil(), f(99_999_999.0));
2254 assert_eq!(f(99_999_999.1).checked_ceil(), None);
2255 assert_eq!(f(99_999_999.5).checked_ceil(), None);
2256 assert_eq!(f(99_999_999.6).checked_ceil(), None);
2257 }
2258
2259 #[test]
2260 fn truncate() {
2261 assert_eq!(f(5.0).truncate(), f(5.0));
2262 assert_eq!(f(5.1).truncate(), f(5.0));
2263 assert_eq!(f(5.5).truncate(), f(5.0));
2264 assert_eq!(f(5.9).truncate(), f(5.0));
2265 assert_eq!(f(-5.0).truncate(), f(-5.0));
2266 assert_eq!(f(-5.1).truncate(), f(-5.0));
2267 assert_eq!(f(-5.5).truncate(), f(-5.0));
2268 assert_eq!(f(-5.6).truncate(), f(-5.0));
2269 assert_eq!(f(4.0).truncate(), f(4.0));
2270 assert_eq!(f(4.1).truncate(), f(4.0));
2271 assert_eq!(f(4.5).truncate(), f(4.0));
2272 assert_eq!(f(4.9).truncate(), f(4.0));
2273 assert_eq!(f(-4.0).truncate(), f(-4.0));
2274 assert_eq!(f(-4.1).truncate(), f(-4.0));
2275 assert_eq!(f(-4.5).truncate(), f(-4.0));
2276 assert_eq!(f(-4.6).truncate(), f(-4.0));
2277 assert_eq!(f(99_999_999.0).truncate(), f(99_999_999.0));
2278 assert_eq!(f(99_999_999.1).truncate(), f(99_999_999.0));
2279 assert_eq!(f(99_999_999.5).truncate(), f(99_999_999.0));
2280 assert_eq!(f(99_999_999.6).truncate(), f(99_999_999.0));
2281 assert_eq!(f(-99_999_999.0).truncate(), f(-99_999_999.0));
2282 assert_eq!(f(-99_999_999.1).truncate(), f(-99_999_999.0));
2283 assert_eq!(f(-99_999_999.5).truncate(), f(-99_999_999.0));
2284 assert_eq!(f(-99_999_999.6).truncate(), f(-99_999_999.0));
2285 }
2286
2287 #[test]
2288 fn sign() {
2289 assert_eq!(f(-0.1).sign(), Fixed::<1, 0>::try_from(-1).unwrap());
2290 assert_eq!(f(0.0).sign(), Fixed::<1, 0>::try_from(0).unwrap());
2291 assert_eq!(f(0.5).sign(), Fixed::<1, 0>::try_from(1).unwrap());
2292 }
2293
2294 #[test]
2295 fn sqrt() {
2296 assert_eq!(f(0.0).sqrt(), f(0.0));
2298 assert_eq!(f(1.0).sqrt(), f(1.0));
2299 assert_eq!(f(2.0).sqrt(), f(1.41));
2300 assert_eq!(f(3.0).sqrt(), f(1.73));
2301 assert_eq!(f(4.0).sqrt(), f(2.0));
2302 assert_eq!(f(-1.0).checked_sqrt(), None);
2303
2304 for a in 0..=999 {
2306 let af: Fixed<10, 2> = Fixed(a);
2307 assert_eq!(af.sqrt(), Fixed::<10, 2>((a * 100).isqrt()));
2308 }
2309 }
2310
2311 #[test]
2312 fn nullable() {
2313 fn nullable_checked_add_generic<
2316 const PA: usize,
2317 const SA: usize,
2318 const PB: usize,
2319 const SB: usize,
2320 const PC: usize,
2321 const SC: usize,
2322 >(
2323 a: Option<Fixed<PA, SA>>,
2324 b: Option<Fixed<PB, SB>>,
2325 ) -> Option<Fixed<PC, SC>> {
2326 a.zip(b).and_then(|(a, b)| a.checked_add_generic(b))
2327 }
2328
2329 let a: Option<Fixed<10, 2>> = Some("1.23".parse().unwrap());
2330 let b: Option<Fixed<5, 4>> = Some("4.5678".parse().unwrap());
2331 let c: Option<Fixed<10, 4>> = nullable_checked_add_generic(a, b);
2332 assert_eq!(c, Some("5.7978".parse().unwrap()));
2333 }
2334
2335 #[test]
2336 fn to_integer() {
2337 for x in -9999..=9999 {
2338 let f = Fixed::<4, 1>(x);
2339 assert_eq!(i128::from(f), x / 10);
2340 assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
2341 assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
2342 assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
2343 assert_eq!(
2344 i8::try_from(f).ok(),
2345 (-1289..=1279).contains(&x).then_some((x / 10) as i8)
2346 );
2347 assert_eq!(
2348 u128::try_from(f).ok(),
2349 (x > -10).then_some((x / 10) as u128)
2350 );
2351 assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
2352 assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
2353 assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
2354 assert_eq!(
2355 u8::try_from(f).ok(),
2356 (-9..=2559).contains(&x).then_some((x / 10) as u8)
2357 );
2358 }
2359 }
2360
2361 #[test]
2362 fn compare_against_fixed() {
2363 fn check_comparisons<const PA: usize, const SA: usize, const PB: usize, const SB: usize>(
2364 fx: Fixed<PA, SA>,
2365 fy: Fixed<PB, SB>,
2366 x: i128,
2367 y: i128,
2368 ) {
2369 assert_eq!(fx == fy, x == y);
2370 assert_eq!(fx != fy, x != y);
2371 assert_eq!(fx > fy, x > y);
2372 assert_eq!(fx >= fy, x >= y);
2373 assert_eq!(fx < fy, x < y);
2374 assert_eq!(fx <= fy, x <= y);
2375 }
2376
2377 for x in -999..=999 {
2378 let fx = Fixed::<3, 1>(x);
2379 for y in -999..=999 {
2380 check_comparisons(fx, Fixed::<3, 0>(y), x, y * 10);
2381 check_comparisons(fx, Fixed::<3, 1>(y), x, y);
2382 check_comparisons(fx, Fixed::<3, 2>(y), x * 10, y);
2383 }
2384 }
2385 }
2386
2387 #[test]
2388 fn compare_against_integers() {
2389 for x in -999..=999 {
2390 let f = Fixed::<3, 1>(x);
2391 for y in -100..=100 {
2392 let expect = x == y * 10;
2393 assert_eq!(f == y as i8, expect);
2394 assert_eq!(f == y as i16, expect);
2395 assert_eq!(f == y as i32, expect);
2396 assert_eq!(f == y as i64, expect);
2397 assert_eq!(f == y, expect);
2398 assert_eq!(f == y as isize, expect);
2399 if y >= 0 {
2400 assert_eq!(f == y as u8, expect);
2401 assert_eq!(f == y as u16, expect);
2402 assert_eq!(f == y as u32, expect);
2403 assert_eq!(f == y as u64, expect);
2404 assert_eq!(f == y as u128, expect);
2405 assert_eq!(f == y as usize, expect);
2406 }
2407 }
2408 }
2409 }
2410}