feldera_fxp/
fixed.rs

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::{cast, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, One, Zero};
9
10use crate::{
11    checked_pow10, debug_decimal, display_decimal, div_ceil, div_floor, i128_mul_pow10_round_even,
12    parse_decimal, pow10, round_inner, u256::I256, Halfway, OutOfRange, ParseDecimalError,
13};
14
15/// Decimal real number with fixed precision and scale.
16///
17/// `Fixed<P, S>`, where `P` in `1..=38` is the "precision" and `S` in `0..=P`
18/// is the "scale", represents a signed decimal number in which `S - P` digits
19/// precede the decimal point and `S` digits follow it.  The table below shows
20/// the maximum values for a few combinations of `P` and `S`.  For each type,
21/// the minimum value is the negation of the maximum:
22///
23/// |          Type |                                              Maximum Value |
24/// |:--------------|-----------------------------------------------------------:|
25/// | `Fixed<5,5>`  | `                                                 0.99999` |
26/// | `Fixed<5,4>`  | `                                                 9.9999 ` |
27/// | `Fixed<5,3>`  | `                                                99.999  ` |
28/// | `Fixed<5,2>`  | `                                               999.99   ` |
29/// | `Fixed<5,1>`  | `                                             9,999.9    ` |
30/// | `Fixed<5,0>`  | `                                            99,999      ` |
31/// | `Fixed<38,0>` | `99,999,999,999,999,999,999,999,999,999,999,999,999      ` |
32/// | `Fixed<38,5>` | `       999,999,999,999,999,999,999,999,999,999,999.99999` |
33///
34/// # Implementation
35///
36/// `Fixed<P, S>` internally contains a single `i128` that represents a value
37/// `x` as `x * 10**P`.  This limits `S` to 38 because `10**38 ≤ 2**127 - 1 <
38/// 10**39`.  A single `i64` would be sufficient for `S ≤ 18`, and a single
39/// `i32` for `S ≤ 9`, but the implementation does not optimize for those cases.
40#[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    /// Largest value for this type, e.g. 999.99 for `Fixed<5,2>`.
110    pub const MAX: Self = Self(pow10(P) - 1);
111
112    /// Smallest value for this type, e.g. -999.99 for `Fixed<5,2>`.
113    ///
114    /// `MIN` is always `-MAX`.
115    pub const MIN: Self = Self(-Self::MAX.0);
116
117    /// Zero in this type.
118    pub const ZERO: Self = Self(0);
119
120    /// 1 in this type.
121    ///
122    /// # Panic
123    ///
124    /// If `S == P`, this is undefined because 1 is not a value in this type,
125    /// and referring to it yields a compile-time error.
126    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    /// Returns `value` in this type.
135    ///
136    /// # Panic
137    ///
138    /// Panics if this type cannot hold every `i64` value.
139    pub const fn for_i64(value: i64) -> Self {
140        assert!(P.saturating_sub(S) >= 19);
141        Self(value as i128 * Self::scale())
142    }
143
144    /// Returns `value` in this type.
145    ///
146    /// # Panic
147    ///
148    /// Panics if this type cannot hold every `u64` value.
149    pub const fn for_u64(value: u64) -> Self {
150        assert!(P.saturating_sub(S) >= 19);
151        Self(value as i128 * Self::scale())
152    }
153
154    /// Returns `value` in this type.
155    ///
156    /// # Panic
157    ///
158    /// Panics if this type cannot hold every `i32` value.
159    pub const fn for_i32(value: i32) -> Self {
160        assert!(P.saturating_sub(S) >= 10);
161        Self(value as i128 * Self::scale())
162    }
163
164    /// Returns `value` in this type.
165    ///
166    /// # Panic
167    ///
168    /// Panics if this type cannot hold every `u32` value.
169    pub const fn for_u32(value: u32) -> Self {
170        assert!(P.saturating_sub(S) >= 10);
171        Self(value as i128 * Self::scale())
172    }
173
174    /// Returns `value` in this type.
175    ///
176    /// # Panic
177    ///
178    /// Panics if this type cannot hold every `i16` value.
179    pub const fn for_i16(value: i16) -> Self {
180        assert!(P.saturating_sub(S) >= 5);
181        Self(value as i128 * Self::scale())
182    }
183
184    /// Returns `value` in this type.
185    ///
186    /// # Panic
187    ///
188    /// Panics if this type cannot hold every `u16` value.
189    pub const fn for_u16(value: u16) -> Self {
190        assert!(P.saturating_sub(S) >= 5);
191        Self(value as i128 * Self::scale())
192    }
193
194    /// Returns `value` in this type.
195    ///
196    /// # Panic
197    ///
198    /// Panics if this type cannot hold every `i8` value.
199    pub const fn for_i8(value: i8) -> Self {
200        assert!(P.saturating_sub(S) >= 3);
201        Self(value as i128 * Self::scale())
202    }
203
204    /// Returns `value` in this type.
205    ///
206    /// # Panic
207    ///
208    /// Panics if this type cannot hold every `u8` value.
209    pub const fn for_u8(value: u8) -> Self {
210        assert!(P.saturating_sub(S) >= 3);
211        Self(value as i128 * Self::scale())
212    }
213
214    /// Returns `value` in this type.
215    ///
216    /// # Panic
217    ///
218    /// Panics if this type cannot hold every `isize` value.
219    pub const fn for_isize(value: isize) -> Self {
220        match isize::BITS {
221            64 => Self::for_i64(value as i64),
222            32 => Self::for_i32(value as i32),
223            16 => Self::for_i16(value as i16),
224            _ => panic!(),
225        }
226    }
227
228    /// Returns `value` in this type.
229    ///
230    /// # Panic
231    ///
232    /// Panics if this type cannot hold every `usize` value.
233    pub const fn for_usize(value: usize) -> Self {
234        match usize::BITS {
235            64 => Self::for_u64(value as u64),
236            32 => Self::for_u32(value as u32),
237            16 => Self::for_u16(value as u16),
238            _ => panic!(),
239        }
240    }
241
242    /// Returns the value that represents `value * 10**-scale`, rounding
243    /// toward zero if necessary, or `None` if the rounded value is out of range
244    /// for this type.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// # use feldera_fxp::Fixed;
250    ///
251    /// assert_eq!(Fixed::<11, 1>::new(435, 0).unwrap().to_string(), "435");
252    /// assert_eq!(Fixed::<11, 1>::new(435, 1).unwrap().to_string(), "43.5");
253    /// assert_eq!(Fixed::<11, 1>::new(435, 2).unwrap().to_string(), "4.3");
254    /// assert_eq!(Fixed::<11, 1>::new(435, 3).unwrap().to_string(), "0.4");
255    /// ```
256    pub fn new(value: i128, scale: i32) -> Option<Self> {
257        Self::try_new_with_exponent(value, (S as i32).saturating_sub(scale))
258    }
259
260    /// Returns the value that represents `value * 10**-scale`, rounding to
261    /// nearest if necessary, with ties rounded to even, or `None` if the
262    /// rounded value is out of range for this type.
263    ///
264    /// # Examples
265    ///
266    /// ```
267    /// # use feldera_fxp::Fixed;
268    ///
269    /// assert_eq!(Fixed::<11, 1>::new_round_even(435, 0).unwrap().to_string(), "435");
270    /// assert_eq!(Fixed::<11, 1>::new_round_even(435, 1).unwrap().to_string(), "43.5");
271    /// assert_eq!(Fixed::<11, 1>::new_round_even(435, 2).unwrap().to_string(), "4.4");
272    /// assert_eq!(Fixed::<11, 1>::new_round_even(435, 3).unwrap().to_string(), "0.4");
273    /// ```
274    pub fn new_round_even(value: i128, scale: i32) -> Option<Self> {
275        Self::try_new_with_exponent_round_even(value, (S as i32).saturating_sub(scale))
276    }
277
278    /// Returns `Self(value)`, if `value` is in the correct range for this type.
279    fn try_new(value: i128) -> Option<Self> {
280        const { Self::check_constraints() };
281        (Self::MIN.0..=Self::MAX.0)
282            .contains(&value)
283            .then_some(Self(value))
284    }
285
286    /// Returns `Self(value * 10**exponent)`, rounding to even if `exponent` is
287    /// negative, if the computed value is in the correct range for the type.
288    fn try_new_with_exponent_round_even(value: i128, exponent: i32) -> Option<Self> {
289        i128_mul_pow10_round_even(value, exponent).and_then(Self::try_new)
290    }
291
292    /// Returns `Self(value * 10**exponent)`, rounding toward zero, if the
293    /// computed value is in the correct range for the type.
294    pub(super) fn try_new_with_exponent(value: i128, exponent: i32) -> Option<Self> {
295        // Non-generic inner function to reduce monomorphization cost.
296        fn inner(value: i128, exponent: i32) -> Option<i128> {
297            Some(match exponent.cmp(&0) {
298                Ordering::Less => {
299                    // Divide by a negative exponent.
300                    if let Some(divisor) = checked_pow10(exponent.unsigned_abs()) {
301                        value / divisor
302                    } else {
303                        // `10**-exponent` is greater than `i128::MAX`.  The result
304                        // must be zero.
305                        0
306                    }
307                }
308                Ordering::Equal => value,
309                Ordering::Greater => {
310                    // Multiply by a positive exponent.
311                    value.checked_mul(checked_pow10(exponent.cast_unsigned())?)?
312                }
313            })
314        }
315        inner(value, exponent).and_then(Self::try_new)
316    }
317
318    /// Validates the constraints on `S` and `P`.
319    const fn check_constraints() {
320        assert!(P >= 1 && P <= 38, "Fixed<S,P> must have 1 <= S <= 38");
321        assert!(S <= P, "Fixed<S,P> must have S <= P");
322    }
323
324    /// Returns `pow10(S)`.
325    const fn scale() -> i128 {
326        Self::check_constraints();
327        pow10(S)
328    }
329
330    /// Integer division, as defined for `divide-integer` in [General Decimal
331    /// Arithmetic].  Returns `None` if `other` is zero or the result is greater
332    /// than `i128::MAX`.
333    ///
334    /// [General Decimal Arithmetic]: https://speleotrove.com/decimal/decarith.pdf
335    pub const fn checked_div_integer(self, other: Self) -> Option<i128> {
336        self.0.checked_div(other.0)
337    }
338
339    /// Integer division like [checked_div_integer](Self::checked_div_integer),
340    /// but panic on error.
341    ///
342    /// # Panic
343    ///
344    /// Panics if `other` is zero or the result is greater than `i128::MAX`.
345    pub const fn strict_div_integer(self, other: Self) -> i128 {
346        self.checked_div_integer(other).unwrap()
347    }
348
349    /// Remainder, as defined for `remainder` in [General Decimal Arithmetic].
350    /// Returns `None` if `other` is zero.
351    ///
352    /// [General Decimal Arithmetic]: https://speleotrove.com/decimal/decarith.pdf
353    pub const fn checked_rem_integer(self, _other: Self) -> Option<Self> {
354        todo!()
355    }
356
357    /// Integer remainder like [checked_rem_integer](Self::checked_rem_integer),
358    /// but panic on error.
359    ///
360    /// # Panic
361    ///
362    /// Panics if `other` is zero.
363    pub const fn strict_rem_integer(self, other: Self) -> Self {
364        self.checked_rem_integer(other).unwrap()
365    }
366
367    /// Returns the absolute value.  This is an exact calculation that cannot
368    /// overflow.
369    pub const fn abs(self) -> Self {
370        Self(self.0.abs())
371    }
372
373    /// Returns true if this value is negative, false if it is zero or positive.
374    pub const fn is_negative(self) -> bool {
375        self.0.is_negative()
376    }
377
378    /// Returns the square root of this value, rounded down, or `None` if this
379    /// value is negative.
380    ///
381    /// It probably makes more sense to convert to `f64` and take the
382    /// floating-point square root.
383    pub fn checked_sqrt(self) -> Option<Self> {
384        Some(Self(
385            I256::from_product(self.0, Self::scale()).checked_isqrt()?,
386        ))
387    }
388
389    /// Returns the square root of this value, rounded down.
390    ///
391    /// It probably makes more sense to convert to `f64` and take the
392    /// floating-point square root.
393    ///
394    /// # Panic
395    ///
396    /// Panics if this value is negative.
397    pub fn sqrt(self) -> Self {
398        self.checked_sqrt().unwrap()
399    }
400
401    /// Returns this value rounded to `n` digits after the decimal point, or
402    /// `None` if rounding caused overflow, `n` may be negative.
403    ///
404    /// If the value is halfway between two integers, rounds away from zero.
405    pub fn checked_round(&self, n: i32) -> Option<Self> {
406        round_inner(self.0, S as i32, n, Halfway::AwayFromZero).and_then(Self::try_new)
407    }
408
409    /// Rounds to `n` digits after the decimal point, like [checked_round].
410    /// If the value is halfway between two integers, rounds away from zero.
411    ///
412    /// # Panic
413    ///
414    /// Panics if rounding causes overflow.
415    ///
416    /// [checked_round]: Self::checked_round
417    pub fn round(&self, n: i32) -> Self {
418        self.checked_round(n).unwrap()
419    }
420
421    /// Returns this value rounded to `n` digits after the decimal point, or
422    /// `None` if rounding caused overflow, `n` may be negative.  If the value
423    /// is halfway between two integers, rounds toward an even least significant
424    /// digit.
425    pub fn checked_round_ties_even(&self, n: i32) -> Option<Self> {
426        round_inner(self.0, S as i32, n, Halfway::Even).and_then(Self::try_new)
427    }
428
429    /// Rounds to `n` digits after the decimal point, like
430    /// [checked_round_ties_even].  If the value is halfway between two
431    /// integers, rounds toward an even least significant digit.
432    ///
433    /// # Panic
434    ///
435    /// Panics if rounding causes overflow.
436    ///
437    /// [checked_round_ties_even]: Self::checked_round_ties_even
438    pub fn round_ties_even(&self, n: i32) -> Self {
439        self.checked_round_ties_even(n).unwrap()
440    }
441
442    /// Returns this value rounded down to the nearest integer, or `None` if
443    /// rounding caused overflow.
444    pub fn checked_floor(&self) -> Option<Self> {
445        if S > 0 {
446            Self::try_new(div_floor(self.0, Self::scale()) * Self::scale())
447        } else {
448            Some(*self)
449        }
450    }
451
452    /// Rounds down to the nearest integer, like [checked_floor].
453    ///
454    /// # Panic
455    ///
456    /// Panics if rounding causes overflow.
457    ///
458    /// [checked_floor]: Self::checked_floor
459    pub fn floor(&self) -> Self {
460        self.checked_floor().unwrap()
461    }
462
463    /// Returns the integer part of this value, truncating non-integers toward
464    /// zero.  This is an exact calculation that cannot overflow.
465    ///
466    /// `trunc()` is equivalent to `trunc_digits(0)`, but it might be more
467    /// efficient due to constant folding.
468    pub fn trunc(&self) -> Self {
469        Self(self.0 / Self::scale() * Self::scale())
470    }
471
472    /// Returns this value, truncated toward zero at `digits` after the decimal
473    /// point. This is an exact calculation that cannot overflow.
474    pub fn trunc_digits(&self, digits: i32) -> Self {
475        let exponent = (S as i32).saturating_sub(digits);
476        if exponent <= 0 {
477            *self
478        } else if let Some(divisor) = checked_pow10(exponent.cast_unsigned()) {
479            Self(self.0 / divisor * divisor)
480        } else {
481            Self::ZERO
482        }
483    }
484
485    /// Returns this value rounded up to the nearest integer, or `None` if
486    /// rounding caused overflow.
487    pub fn checked_ceil(&self) -> Option<Self> {
488        if S > 0 {
489            Self::try_new(div_ceil(self.0, Self::scale()) * Self::scale())
490        } else {
491            Some(*self)
492        }
493    }
494
495    /// Rounds up to the nearest integer, like [checked_ceil].
496    ///
497    /// # Panic
498    ///
499    /// Panics if rounding causes overflow.
500    ///
501    /// [checked_ceil]: Self::checked_ceil
502    pub fn ceil(&self) -> Self {
503        self.checked_ceil().unwrap()
504    }
505
506    /// Returns -1 if this value is less than zero, 0 if this value is zero, and
507    /// 1 if this value is greater than zero, as `Fixed<1,0>`.
508    pub fn sign(&self) -> Fixed<1, 0> {
509        self.checked_sign_generic().unwrap()
510    }
511
512    /// Returns the reciprocal (inverse) of this value, `1/x`, or `None` if `x`
513    /// is zero or `1/x` is out of range.
514    pub fn checked_recip(&self) -> Option<Self> {
515        if S < P {
516            Self(Self::scale()).checked_div(self)
517        } else {
518            // `1` is out of range for this type, therefore `abs(self) < 1`,
519            // therefore `abs(1/self) > 1`, therefore the result is out of
520            // range.
521            None
522        }
523    }
524
525    /// Returns the reciprocal (inverse) of this value, `1/x`.  This works even
526    /// if `1` is out of range for this type, as long as `1/x` is in range.
527    ///
528    /// # Panic
529    ///
530    /// Panics if `x` is zero or `1/x` is out of range.
531    pub fn recip(&self) -> Self {
532        self.checked_recip().unwrap()
533    }
534
535    /// Returns this value raised to `exp` power, rounding toward zero, or
536    /// `None` if the result is out of range or if this value is 0 and `exp` is
537    /// nonpositive.
538    ///
539    /// # Accuracy
540    ///
541    /// For `exp > 0`, this computes intermediate results with more than `S`
542    /// digits of precision, if possible, to allow to better accuracy in the
543    /// result.  For `exp < 0`, this isn't implemented yet.
544    pub fn checked_powi(&self, exp: i32) -> Option<Self> {
545        if self.is_zero() {
546            (exp > 0).then_some(Self::ZERO)
547        } else if exp == 0 {
548            if S < P {
549                Some(Self::ONE)
550            } else {
551                // 1 is not representable.
552                None
553            }
554        } else if exp > 0 {
555            let mut exp = exp.unsigned_abs();
556            let mut base = self.0;
557            let mut base_scale = S as i32;
558            let mut acc = None;
559            loop {
560                if (exp & 1) == 1 {
561                    acc = if let Some((acc, acc_scale)) = acc {
562                        let (acc, shift) = I256::from_product(acc, base).reduce_to_i128();
563                        Some((acc, (acc_scale + base_scale) - shift as i32))
564                    } else {
565                        Some((base, base_scale))
566                    };
567                }
568                exp /= 2;
569                if exp == 0 {
570                    let (acc, acc_scale) = acc.unwrap();
571                    return Self::try_new_with_exponent(acc, S as i32 - acc_scale);
572                }
573
574                let (next_base, shift) = I256::from_product(base, base).reduce_to_i128();
575                base = next_base;
576                base_scale = base_scale * 2 - shift as i32;
577            }
578        } else {
579            let mut exp = exp.unsigned_abs();
580            let mut base = *self;
581            let mut acc: Option<Fixed<P, S>> = None;
582            loop {
583                if (exp & 1) == 1 {
584                    acc = Some(if let Some(acc) = acc {
585                        acc.checked_div(&base)
586                    } else {
587                        base.checked_recip()
588                    }?)
589                }
590                exp /= 2;
591                if exp == 0 {
592                    return acc;
593                }
594                base *= base;
595            }
596        }
597    }
598
599    /// Returns this value raised to `exp` power, rounding toward zero.
600    ///
601    /// For `exp > 0`, this computes intermediate results with more than `S`
602    /// digits of precision, if possible, to allow to better accuracy in the
603    /// result.  For `exp < 0`, this isn't implemented yet.
604    ///
605    /// # Panics
606    ///
607    /// Panics if the result is out of range or if this value is 0 and `exp` is
608    /// nonpositive.
609    pub fn powi(&self, exp: i32) -> Self {
610        self.checked_powi(exp).unwrap()
611    }
612
613    /// Returns the least number greater than `self`, or `None` if this is
614    /// `Self::MAX`.
615    pub fn next_up(&self) -> Option<Self> {
616        if *self < Self::MAX {
617            Some(Self(self.0 + 1))
618        } else {
619            None
620        }
621    }
622
623    /// Returns the greatest number less than `self`, or `None` if this is
624    /// `Self::MAX`.
625    pub fn next_down(&self) -> Option<Self> {
626        if *self > Self::MIN {
627            Some(Self(self.0 - 1))
628        } else {
629            None
630        }
631    }
632}
633
634impl<const P0: usize, const S0: usize> Fixed<P0, S0> {
635    /// Returns this value converted into another type `Fixed<P1, S1>`, or
636    /// `None` if this value is outside the range of the target type.  If the
637    /// conversion is successful, then the result is exactly the same as the
638    /// original value if `S1 >= S0`, and rounded down otherwise.
639    ///
640    /// This should be implemented as `TryFrom` but that [conflicts with the
641    /// standard library
642    /// implementation](https://users.rust-lang.org/t/conflicting-implementations-of-trait-from/92994).
643    pub fn convert<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
644        Fixed::try_new_with_exponent(self.0, S1 as i32 - S0 as i32)
645    }
646
647    /// Returns this value converted into another type `Fixed<P1, S1>`, or
648    /// `None` if this value is outside the range of the target type.  If the
649    /// conversion is successful, then the result is exactly the same as the
650    /// original value if `S1 >= S0`, and rounded to even otherwise.
651    pub fn convert_round_even<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
652        Fixed::try_new_with_exponent_round_even(self.0, S1 as i32 - S0 as i32)
653    }
654
655    /// Returns -1 if this value is less than zero, 0 if this value is zero, and
656    /// 1 if this value is greater than zero, in an arbitrary `Fixed` type.
657    /// Returns `None` on overflow (if this value is nonzero and `S1 >= P1`).
658    pub fn checked_sign_generic<const P1: usize, const S1: usize>(&self) -> Option<Fixed<P1, S1>> {
659        let one = Fixed::<P1, S1>::scale();
660        match self.0.cmp(&0) {
661            Ordering::Less if S1 < P1 => Some(Fixed(-one)),
662            Ordering::Equal => Some(Fixed::ZERO),
663            Ordering::Greater if S1 < P1 => Some(Fixed(one)),
664            _ => None,
665        }
666    }
667
668    /// Calculates `self + other`, for operands with scale and precision `(S0,P0)` and
669    /// `(S1,P1)`, respectively, producing a result with scale and precision
670    /// `(S2,P2)`.  The result is calculated exactly if possible and otherwise
671    /// rounded toward zero.  Returns `None` if the result is not representable
672    /// in the result type.
673    pub fn checked_add_generic<
674        const P1: usize,
675        const S1: usize,
676        const P2: usize,
677        const S2: usize,
678    >(
679        self,
680        other: Fixed<P1, S1>,
681    ) -> Option<Fixed<P2, S2>> {
682        match S0.cmp(&S1) {
683            Ordering::Less => {
684                let factor = pow10(S1 - S0);
685                if self.0 <= i128::MAX / factor / 10 {
686                    Fixed::try_new_with_exponent(
687                        other.0.checked_add(self.0 * factor)?,
688                        S2 as i32 - S1 as i32,
689                    )
690                } else {
691                    let result = (I256::from_product(self.0, factor) + I256::from(other.0))
692                        .narrowing_div(pow10(S2.saturating_sub(S1)))?;
693                    Fixed::try_new_with_exponent(result, S1.saturating_sub(S2) as i32)
694                }
695            }
696            Ordering::Equal => {
697                Fixed::try_new_with_exponent(self.0.checked_add(other.0)?, (S2 - S0) as i32)
698            }
699            Ordering::Greater => {
700                let factor = pow10(S0 - S1);
701                if other.0 <= i128::MAX / factor / 10 {
702                    Fixed::try_new_with_exponent(
703                        self.0.checked_add(other.0 * factor)?,
704                        S2 as i32 - S0 as i32,
705                    )
706                } else {
707                    let result = (I256::from_product(other.0, factor) + I256::from(self.0))
708                        .narrowing_div(pow10(S2.saturating_sub(S0)))?;
709                    Fixed::try_new_with_exponent(result, S0.saturating_sub(S2) as i32)
710                }
711            }
712        }
713    }
714
715    /// Calculates `self - other`, for operands with scale and precision
716    /// `(S0,P0)` and `(S1,P1)`, respectively, producing a result with scale and
717    /// precision `(S2,P2)`.  The result is calculated exactly if possible and
718    /// otherwise rounded toward zero.  Returns `None` if the result is not
719    /// representable in the result type.
720    pub fn checked_sub_generic<
721        const P1: usize,
722        const S1: usize,
723        const P2: usize,
724        const S2: usize,
725    >(
726        self,
727        other: Fixed<P1, S1>,
728    ) -> Option<Fixed<P2, S2>> {
729        self.checked_add_generic(-other)
730    }
731
732    /// Calculates `self * other`, for operands with scale and precision
733    /// `(S0,P0)` and `(S1,P1)`, respectively, producing a result with scale and
734    /// precision `(S2,P2)`.  The result is calculated exactly if possible and
735    /// otherwise rounded toward zero.  Returns `None` if the result is not
736    /// representable in the result type.
737    pub fn checked_mul_generic<
738        const P1: usize,
739        const S1: usize,
740        const P2: usize,
741        const S2: usize,
742    >(
743        self,
744        other: Fixed<P1, S1>,
745    ) -> Option<Fixed<P2, S2>> {
746        Fixed::<P2, S2>::try_new_with_exponent(
747            I256::from_product(self.0, other.0)
748                .narrowing_div(pow10((S0 + S1).saturating_sub(S2)))?,
749            S2.saturating_sub(S0 + S1) as i32,
750        )
751    }
752
753    /// Calculate `self / other`, for operands with scale and precision
754    /// `(S0,P0)` and `(S1,P1)`, respectively, producing a result with scale and
755    /// precision `(S2,P2)`.  The result is calculated exactly if possible and
756    /// otherwise rounded toward zero.  Returns `None` if the result is not
757    /// representable in the result type, or if `other` is zero.
758    pub fn checked_div_generic<
759        const P1: usize,
760        const S1: usize,
761        const P2: usize,
762        const S2: usize,
763    >(
764        self,
765        other: Fixed<P1, S1>,
766    ) -> Option<Fixed<P2, S2>> {
767        if other == 0 {
768            None
769        } else {
770            let shift_left = (S1 + S2).saturating_sub(S0);
771            if shift_left > 38 {
772                // A shift this big would exceed the range of I256, so we can't
773                // calculate it, but the ultimate result would also overflow, so
774                // we don't have to.
775                None
776            } else {
777                Fixed::try_new_with_exponent(
778                    I256::from_product(self.0, pow10(shift_left)).narrowing_div(other.0)?,
779                    S0.saturating_sub(S1 + S2) as i32,
780                )
781            }
782        }
783    }
784
785    /// Compute `self + other`, rounding toward zero, panicking if overflow
786    /// occurs.
787    pub fn strict_add_generic<
788        const P1: usize,
789        const S1: usize,
790        const P2: usize,
791        const S2: usize,
792    >(
793        self,
794        other: Fixed<P1, S1>,
795    ) -> Fixed<P2, S2> {
796        self.checked_add_generic(other).unwrap()
797    }
798
799    /// Compute `self - other`, rounding toward zero, panicking if overflow
800    /// occurs.
801    pub fn strict_sub_generic<
802        const P1: usize,
803        const S1: usize,
804        const P2: usize,
805        const S2: usize,
806    >(
807        self,
808        other: Fixed<P1, S1>,
809    ) -> Fixed<P2, S2> {
810        self.checked_sub_generic(other).unwrap()
811    }
812
813    /// Compute `self * other`, rounding toward zero, panicking if overflow
814    /// occurs.
815    pub fn strict_mul_generic<
816        const P1: usize,
817        const S1: usize,
818        const P2: usize,
819        const S2: usize,
820    >(
821        self,
822        other: Fixed<P1, S1>,
823    ) -> Fixed<P2, S2> {
824        self.checked_mul_generic(other).unwrap()
825    }
826
827    /// Compute `self / other`, rounding toward zero, panicking if overflow
828    /// occurs or if `other` is zero.
829    pub fn strict_div_generic<
830        const P1: usize,
831        const S1: usize,
832        const P2: usize,
833        const S2: usize,
834    >(
835        self,
836        other: Fixed<P1, S1>,
837    ) -> Fixed<P2, S2> {
838        self.checked_div_generic(other).unwrap()
839    }
840}
841
842impl<const P: usize, const S: usize> Zero for Fixed<P, S> {
843    fn zero() -> Self {
844        Self::ZERO
845    }
846
847    fn is_zero(&self) -> bool {
848        *self == Self::ZERO
849    }
850}
851
852impl<const P: usize, const S: usize> One for Fixed<P, S> {
853    /// This will panic at compile time if 1 isn't in the range of this type.
854    fn one() -> Self {
855        Self::ONE
856    }
857}
858
859impl<const P: usize, const S: usize> TryFrom<f64> for Fixed<P, S> {
860    type Error = OutOfRange;
861
862    /// Convert `value` to `Fixed`, rounding toward zero, reporting an error if
863    /// `value` is out of range.
864    fn try_from(value: f64) -> Result<Self, Self::Error> {
865        cast(value * Self::scale() as f64)
866            .and_then(Self::try_new)
867            .ok_or(OutOfRange)
868    }
869}
870
871impl<const P: usize, const S: usize> From<Fixed<P, S>> for f64 {
872    fn from(value: Fixed<P, S>) -> Self {
873        value.0 as f64 / Fixed::<P, S>::scale() as f64
874    }
875}
876
877impl<const P: usize, const S: usize> TryFrom<i128> for Fixed<P, S> {
878    type Error = OutOfRange;
879
880    /// Convert `value` to `Fixed`, reporting an error if `value` is out of
881    /// range.  This is an exact conversion that cannot lose precision if it
882    /// succeeds.
883    fn try_from(value: i128) -> Result<Self, Self::Error> {
884        if value.unsigned_abs() <= Self::max_u128() {
885            Ok(Self(value * Self::scale()))
886        } else {
887            Err(OutOfRange)
888        }
889    }
890}
891
892macro_rules! try_from_signed_int {
893    ($type_name:ty) => {
894        impl<const P: usize, const S: usize> TryFrom<$type_name> for Fixed<P, S> {
895            type Error = OutOfRange;
896
897            /// Convert `value` to `Fixed`, rounding toward zero, reporting an
898            /// error if `value` is out of range.
899            fn try_from(value: $type_name) -> Result<Self, Self::Error> {
900                (value as i128).try_into()
901            }
902        }
903    };
904}
905
906try_from_signed_int!(isize);
907try_from_signed_int!(i64);
908try_from_signed_int!(i32);
909try_from_signed_int!(i16);
910try_from_signed_int!(i8);
911
912impl<const P: usize, const S: usize> TryFrom<u128> for Fixed<P, S> {
913    type Error = OutOfRange;
914
915    /// Convert `value` to `Fixed`, reporting an error if `value` is out of
916    /// range.  This is an exact conversion that cannot lose precision if it
917    /// succeeds.
918    fn try_from(value: u128) -> Result<Self, Self::Error> {
919        if value <= Self::max_i128() as u128 {
920            Ok(Self(value as i128 * Self::scale()))
921        } else {
922            Err(OutOfRange)
923        }
924    }
925}
926
927macro_rules! try_from_unsigned_int {
928    ($type_name:ty) => {
929        impl<const P: usize, const S: usize> TryFrom<$type_name> for Fixed<P, S> {
930            type Error = OutOfRange;
931
932            /// Convert `value` to `Fixed`, reporting an error if `value` is out
933            /// of range.  This is an exact conversion that cannot lose
934            /// precision if it succeeds.
935            fn try_from(value: $type_name) -> Result<Self, Self::Error> {
936                (value as u128).try_into()
937            }
938        }
939    };
940}
941
942try_from_unsigned_int!(usize);
943try_from_unsigned_int!(u64);
944try_from_unsigned_int!(u32);
945try_from_unsigned_int!(u16);
946try_from_unsigned_int!(u8);
947
948macro_rules! min_max_int {
949    ($signed_type:ty, $max_signed:ident, $min_signed:ident, $unsigned_type:ty, $max_unsigned:ident) => {
950        #[doc = "Returns the maximum `"]
951        #[doc = stringify!($signed_type)]
952        #[doc = "` that can be converted to this type."]
953        pub const fn $max_signed() -> $signed_type {
954            if Self::max_i128() > <$signed_type>::MAX as i128 {
955                <$signed_type>::MAX
956            } else {
957                Self::max_i128() as $signed_type
958            }
959        }
960
961        #[doc = "Returns the minimum `"]
962        #[doc = stringify!($signed_type)]
963        #[doc = "` that can be converted to this type."]
964        pub const fn $min_signed() -> $signed_type {
965            -Self::$max_signed()
966        }
967
968        #[doc = "Returns the maximum `"]
969        #[doc = stringify!($unsigned_type)]
970        #[doc = "` that can be converted to this type.\n\nThe minimum is 0."]
971        pub const fn $max_unsigned() -> $unsigned_type {
972            if Self::max_u128() > <$unsigned_type>::MAX as u128 {
973                <$unsigned_type>::MAX
974            } else {
975                Self::max_u128() as $unsigned_type
976            }
977        }
978    };
979}
980
981impl<const P: usize, const S: usize> Fixed<P, S> {
982    /// Returns the maximum `i128` that can be converted to this type.
983    pub const fn max_i128() -> i128 {
984        if P > S {
985            pow10(P - S) - 1
986        } else {
987            0
988        }
989    }
990
991    /// Returns the minimum `i128` that can be converted to this type.
992    pub const fn min_i128() -> i128 {
993        -Self::max_i128()
994    }
995
996    /// Returns the maximum `u128` that can be converted to this type.
997    ///
998    /// The minimum is 0.
999    pub const fn max_u128() -> u128 {
1000        Self::max_i128().cast_unsigned()
1001    }
1002
1003    min_max_int!(isize, max_isize, min_isize, usize, max_usize);
1004    min_max_int!(i64, max_i64, min_i64, u64, max_u64);
1005    min_max_int!(i32, max_i32, min_i32, u32, max_u32);
1006    min_max_int!(i16, max_i16, min_i16, u16, max_u16);
1007    min_max_int!(i8, max_i8, min_i8, u8, max_u8);
1008}
1009
1010impl<const P: usize, const S: usize> From<Fixed<P, S>> for i128 {
1011    /// Convert from `Fixed` to integer, rounding toward zero (the same
1012    /// semantics as Rust casts from float to integer).
1013    fn from(value: Fixed<P, S>) -> Self {
1014        // Integer `/` rounds toward zero in Rust.
1015        value.0 / <Fixed<P, S>>::scale()
1016    }
1017}
1018
1019macro_rules! try_to_signed_int {
1020    ($type_name:ty) => {
1021        impl<const P: usize, const S: usize> TryFrom<Fixed<P, S>> for $type_name {
1022            type Error = OutOfRange;
1023
1024            /// Convert from `Fixed` to integer, rounding toward zero (the same
1025            /// semantics as Rust casts from float to integer).
1026            fn try_from(value: Fixed<P, S>) -> Result<Self, Self::Error> {
1027                i128::from(value).try_into().map_err(|_| OutOfRange)
1028            }
1029        }
1030    };
1031}
1032
1033try_to_signed_int!(i64);
1034try_to_signed_int!(i32);
1035try_to_signed_int!(i16);
1036try_to_signed_int!(i8);
1037try_to_signed_int!(isize);
1038
1039/// This is the same as [try_to_signed_int] except for the documentation
1040/// comment.
1041macro_rules! try_to_unsigned_int {
1042    ($type_name:ty) => {
1043        impl<const P: usize, const S: usize> TryFrom<Fixed<P, S>> for $type_name {
1044            type Error = OutOfRange;
1045
1046            /// Convert from `Fixed` to integer, rounding toward zero (the same
1047            /// semantics as Rust casts from float to integer).
1048            ///
1049            /// Because this rounds toward zero, negative values greater than -1
1050            /// will convert to 0 instead of an out-of-range error.
1051            fn try_from(value: Fixed<P, S>) -> Result<Self, Self::Error> {
1052                i128::from(value).try_into().map_err(|_| OutOfRange)
1053            }
1054        }
1055    };
1056}
1057
1058try_to_unsigned_int!(u128);
1059try_to_unsigned_int!(u64);
1060try_to_unsigned_int!(u32);
1061try_to_unsigned_int!(u16);
1062try_to_unsigned_int!(u8);
1063try_to_unsigned_int!(usize);
1064
1065impl<const P: usize, const S: usize> Add for Fixed<P, S> {
1066    type Output = Self;
1067
1068    /// Returns the sum, rounding toward zero.
1069    ///
1070    /// # Panic
1071    ///
1072    /// Panics if the result is out of range.
1073    fn add(self, other: Self) -> Self::Output {
1074        self.checked_add(&other).unwrap()
1075    }
1076}
1077
1078impl<const P: usize, const S: usize> Add for &Fixed<P, S> {
1079    type Output = Fixed<P, S>;
1080
1081    /// Returns the sum, which is exact if the result is in range.
1082    ///
1083    /// # Panic
1084    ///
1085    /// Panics if the result is out of range.
1086    fn add(self, other: Self) -> Self::Output {
1087        self.checked_add(other).unwrap()
1088    }
1089}
1090
1091impl<const P: usize, const S: usize> CheckedAdd for Fixed<P, S> {
1092    /// Returns the sum, which is exact, or `None` if the result is out of
1093    /// range.
1094    fn checked_add(&self, other: &Self) -> Option<Self> {
1095        self.checked_add_generic(*other)
1096    }
1097}
1098
1099impl<const P: usize, const S: usize> AddAssign for Fixed<P, S> {
1100    /// Adds `other` to `self`, which is an exact calculation.
1101    ///
1102    /// # Panic
1103    ///
1104    /// Panics if the result is out of range.
1105    fn add_assign(&mut self, other: Self) {
1106        *self = *self + other;
1107    }
1108}
1109
1110impl<const P: usize, const S: usize> AddAssign<&Fixed<P, S>> for Fixed<P, S> {
1111    /// Adds `other` to `self`, which is an exact calculation.
1112    ///
1113    /// # Panic
1114    ///
1115    /// Panics if the result is out of range.
1116    fn add_assign(&mut self, other: &Fixed<P, S>) {
1117        *self = *self + *other;
1118    }
1119}
1120
1121impl<const P: usize, const S: usize> Sub for Fixed<P, S> {
1122    type Output = Self;
1123
1124    /// Returns the difference, which is exact if the result is in range.
1125    ///
1126    /// # Panic
1127    ///
1128    /// Panics if the result is out of range.
1129    fn sub(self, other: Self) -> Self::Output {
1130        self.checked_sub(&other).unwrap()
1131    }
1132}
1133
1134impl<const P: usize, const S: usize> Sub for &Fixed<P, S> {
1135    type Output = Fixed<P, S>;
1136
1137    /// Returns the difference, which is exact if the result is in range.
1138    ///
1139    /// # Panic
1140    ///
1141    /// Panics if the result is out of range.
1142    fn sub(self, other: Self) -> Self::Output {
1143        self.checked_sub(other).unwrap()
1144    }
1145}
1146
1147impl<const P: usize, const S: usize> CheckedSub for Fixed<P, S> {
1148    /// Returns the difference, which is exact, or `None` if the result is out
1149    /// of range.
1150    fn checked_sub(&self, other: &Self) -> Option<Self> {
1151        self.checked_sub_generic(*other)
1152    }
1153}
1154
1155impl<const P: usize, const S: usize> SubAssign for Fixed<P, S> {
1156    /// Subtracts `other` from `self`, which is an exact calculation.
1157    ///
1158    /// # Panic
1159    ///
1160    /// Panics if the result is out of range.
1161    fn sub_assign(&mut self, other: Self) {
1162        *self = *self - other;
1163    }
1164}
1165
1166impl<const P: usize, const S: usize> Mul for Fixed<P, S> {
1167    type Output = Self;
1168
1169    /// Returns the product, rounding toward zero.
1170    ///
1171    /// # Panic
1172    ///
1173    /// Panics if the result is out of range.
1174    fn mul(self, other: Self) -> Self::Output {
1175        self.checked_mul(&other).unwrap()
1176    }
1177}
1178
1179impl<const P: usize, const S: usize> Mul for &Fixed<P, S> {
1180    type Output = Fixed<P, S>;
1181
1182    /// Returns the product, rounding toward zero.
1183    ///
1184    /// # Panic
1185    ///
1186    /// Panics if the result is out of range.
1187    fn mul(self, other: Self) -> Self::Output {
1188        self.checked_mul(other).unwrap()
1189    }
1190}
1191
1192impl<const P: usize, const S: usize> CheckedMul for Fixed<P, S> {
1193    /// Returns the product, rounding toward zero, or `None` if the result is
1194    /// out of range.
1195    fn checked_mul(&self, other: &Self) -> Option<Self> {
1196        Self::checked_mul_generic(*self, *other)
1197    }
1198}
1199
1200impl<const P: usize, const S: usize> MulAssign for Fixed<P, S> {
1201    /// Multiplies `self` by `other`, rounding toward zero.
1202    ///
1203    /// # Panic
1204    ///
1205    /// Panics if the result is out of range.
1206    fn mul_assign(&mut self, other: Self) {
1207        *self = *self * other;
1208    }
1209}
1210
1211impl<const P: usize, const S: usize> Div for Fixed<P, S> {
1212    type Output = Self;
1213
1214    /// Returns the quotient, rounding toward zero.
1215    ///
1216    /// # Panic
1217    ///
1218    /// Panics if `other` is zero or the result is out of range.
1219    fn div(self, other: Self) -> Self::Output {
1220        self.checked_div(&other).unwrap()
1221    }
1222}
1223
1224impl<const P: usize, const S: usize> Div for &Fixed<P, S> {
1225    type Output = Fixed<P, S>;
1226
1227    /// Returns the quotient, rounding toward zero.
1228    ///
1229    /// # Panic
1230    ///
1231    /// Panics if `other` is zero or the result is out of range.
1232    fn div(self, other: Self) -> Self::Output {
1233        self.checked_div(other).unwrap()
1234    }
1235}
1236
1237impl<const P: usize, const S: usize> CheckedDiv for Fixed<P, S> {
1238    /// Returns the quotient, rounding toward zero, or `None` if `other` is zero
1239    /// or the result is out of range.
1240    fn checked_div(&self, other: &Self) -> Option<Self> {
1241        Self::checked_div_generic(*self, *other)
1242    }
1243}
1244
1245impl<const P: usize, const S: usize> DivAssign for Fixed<P, S> {
1246    /// Divides `self` by `other`, rounding toward zero.
1247    ///
1248    /// # Panic
1249    ///
1250    /// Panics if `other` is zero or the result is out of range.
1251    fn div_assign(&mut self, other: Self) {
1252        *self = *self / other;
1253    }
1254}
1255
1256impl<const P: usize, const S: usize> Neg for Fixed<P, S> {
1257    type Output = Self;
1258
1259    /// Returns `-self`.  This is an exact calculation that cannot overflow.
1260    fn neg(self) -> Self::Output {
1261        Self(-self.0)
1262    }
1263}
1264
1265impl<const P: usize, const S: usize> Neg for &Fixed<P, S> {
1266    type Output = Fixed<P, S>;
1267
1268    /// Returns `-self`.  This is an exact calculation that cannot overflow.
1269    fn neg(self) -> Self::Output {
1270        Fixed(-self.0)
1271    }
1272}
1273
1274impl<const P: usize, const S: usize> FromStr for Fixed<P, S> {
1275    type Err = ParseDecimalError;
1276
1277    /// Parses `s` as `Fixed`.
1278    ///
1279    /// This accepts the same forms as [f64::from_str], except that it rejects
1280    /// infinities and NaNs (which `Fixed` does not support), as well as
1281    /// out-of-range values.  Rounds overprecise values to the nearest
1282    /// representable value, rounding halfway values to even.
1283    fn from_str(s: &str) -> Result<Self, Self::Err> {
1284        let (value, exponent) = parse_decimal(s, S as i32)?;
1285        Self::try_new_with_exponent_round_even(value, exponent).ok_or(ParseDecimalError::OutOfRange)
1286    }
1287}
1288
1289impl<const P: usize, const S: usize> Debug for Fixed<P, S> {
1290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1291        debug_decimal(self.0, S, f)
1292    }
1293}
1294
1295impl<const P: usize, const S: usize> Display for Fixed<P, S> {
1296    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1297        display_decimal(self.0, S, f)
1298    }
1299}
1300
1301impl<const P: usize, const S: usize> Fixed<P, S> {
1302    /// Value returned by `Self::MIN.to_unsigned_encoding()`.
1303    ///
1304    /// This is always 0.
1305    pub const UNSIGNED_MIN: u128 = 0;
1306
1307    /// Value returned by `Self::ZERO.to_unsigned_encoding()`.
1308    pub const UNSIGNED_ZERO: u128 = pow10(P).cast_unsigned() - 1;
1309
1310    /// Value returned by `Self::MAX.to_unsigned_encoding()`.
1311    pub const UNSIGNED_MAX: u128 = pow10(P).cast_unsigned() * 2 - 2;
1312
1313    /// Returns this value converted to a `u128` in the range
1314    /// [`Self::UNSIGNED_MIN`] to [`Self::UNSIGNED_MAX`] (inclusive).  The
1315    /// values returned for any given [`Fixed<P,S>`] are suitable for equality
1316    /// and order comparison, that is, `a.cmp(&b)` has the same value as
1317    /// `a.to_unsigned_encoding().cmp(&b.to_unsigned_encoding())`.
1318    ///
1319    /// # Usage
1320    ///
1321    /// This might only be useful in practice for [DBSP] aggregates, which only
1322    /// only support unsigned integer values.  We expose it in case it's useful
1323    /// for some other purpose.
1324    ///
1325    /// [DBSP]: https://docs.rs/dbsp/latest/dbsp/
1326    pub fn to_unsigned_encoding(self) -> u128 {
1327        Self::UNSIGNED_ZERO.checked_add_signed(self.0).unwrap()
1328    }
1329
1330    /// Inverts the transformation of [`to_unsigned_encoding`], returning the
1331    /// original `Fixed` value (assuming `P` and `S` are the same as before).
1332    /// Returns `None` if `encoding` is invalid (which cannot happen if
1333    /// [`to_unsigned_encoding`] returned `encoding`).
1334    ///
1335    /// [`to_unsigned_encoding`]: Self::to_unsigned_encoding
1336    ///
1337    /// # Usage
1338    ///
1339    /// This might only be useful in practice for [DBSP] aggregates, which only
1340    /// only support unsigned integer values.  We expose it in case it's useful
1341    /// for some other purpose.
1342    ///
1343    /// [DBSP]: https://docs.rs/dbsp/latest/dbsp/
1344    pub fn from_unsigned_encoding(encoding: u128) -> Option<Self> {
1345        if encoding < Self::UNSIGNED_ZERO {
1346            Some(Self(-(Self::UNSIGNED_ZERO - encoding).cast_signed()))
1347        } else if encoding <= Self::UNSIGNED_MAX {
1348            Some(Self((encoding - Self::UNSIGNED_ZERO).cast_signed()))
1349        } else {
1350            None
1351        }
1352    }
1353}
1354
1355#[cfg(test)]
1356mod test {
1357    use std::str::FromStr;
1358
1359    use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub};
1360
1361    use crate::Fixed;
1362
1363    type F = Fixed<10, 2>;
1364    fn f(n: f64) -> F {
1365        Fixed::try_from(n).unwrap()
1366    }
1367
1368    fn f38_0(n: f64) -> Fixed<38, 0> {
1369        Fixed::try_from(n).unwrap()
1370    }
1371
1372    fn f38_38(s: &str) -> Fixed<38, 38> {
1373        Fixed::from_str(s).unwrap()
1374    }
1375
1376    #[test]
1377    fn mul() {
1378        // A few specific handwritten cases.
1379        assert_eq!(f(1.23) * f(2.34), f(2.87));
1380        assert_eq!(f(-1.23) * f(2.34), f(-2.87));
1381        assert_eq!(f(1.23) * f(-2.34), f(-2.87));
1382        assert_eq!(f(-1.23) * f(-2.34), f(2.87));
1383
1384        // General case.
1385        for a in -999..=999 {
1386            let af: Fixed<10, 2> = Fixed(a);
1387            for b in -999..=999 {
1388                let bf: Fixed<10, 2> = Fixed(b);
1389                assert_eq!(af * bf, Fixed::<10, 2>(a * b / 100));
1390            }
1391        }
1392
1393        // General case with overflow.
1394        for a in -999..=999 {
1395            let af: Fixed<3, 2> = Fixed(a);
1396            for b in -999..=999 {
1397                let bf: Fixed<3, 2> = Fixed(b);
1398                let c = a * b / 100;
1399                let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1400                assert_eq!(af.checked_mul(&bf), expected);
1401            }
1402        }
1403    }
1404
1405    #[test]
1406    fn mul_generic() {
1407        for a in -999..=999 {
1408            let af: Fixed<10, 2> = Fixed(a);
1409            for b in -999..=999 {
1410                let bf: Fixed<10, 3> = Fixed(b);
1411                let cf: Fixed<10, 5> = af.checked_mul_generic(bf).unwrap();
1412                assert_eq!(cf, Fixed::<10, 5>(a * b));
1413                let df: Fixed<10, 6> = af.checked_mul_generic(bf).unwrap();
1414                assert_eq!(df, Fixed::<10, 6>(a * b * 10));
1415                let ef: Fixed<10, 0> = af.checked_mul_generic(bf).unwrap();
1416                assert_eq!(ef, Fixed::<10, 0>(a * b / 100_000));
1417            }
1418        }
1419    }
1420
1421    #[test]
1422    fn div() {
1423        // A few specific handwritten cases.
1424        assert_eq!(f(1.23) / f(2.34), f(0.52));
1425        assert_eq!(f(-1.23) / f(2.34), f(-0.52));
1426        assert_eq!(f(1.23) / f(-2.34), f(-0.52));
1427        assert_eq!(f(-1.23) / f(-2.34), f(0.52));
1428        assert_eq!(
1429            f38_0(1.0)
1430                .checked_div_generic::<38, 0, 38, 38>(f38_0(7.0))
1431                .unwrap(),
1432            f38_38("0.14285714285714285714285714285714285714")
1433        );
1434
1435        assert_eq!(
1436            f38_0(123.0).checked_div_generic::<38, 38, 38, 38>(f38_38("0.456")),
1437            None
1438        );
1439
1440        // General case.
1441        for a in -999..=999 {
1442            let af: Fixed<10, 2> = Fixed(a);
1443            for b in -999..=999 {
1444                let bf: Fixed<10, 2> = Fixed(b);
1445                assert_eq!(af.checked_div(&bf), (b != 0).then(|| Fixed(a * 100 / b)));
1446            }
1447        }
1448
1449        // General case with overflow.
1450        for a in -999..=999 {
1451            let af: Fixed<3, 2> = Fixed(a);
1452            for b in -999..=999 {
1453                let bf: Fixed<3, 2> = Fixed(b);
1454                let expected = if b != 0 {
1455                    let result = a * 100 / b;
1456                    (result.unsigned_abs() <= 999).then_some(Fixed(result))
1457                } else {
1458                    None
1459                };
1460                assert_eq!(af.checked_div(&bf), expected);
1461            }
1462        }
1463    }
1464
1465    #[test]
1466    fn div_generic() {
1467        for a in -999..=999 {
1468            let af: Fixed<10, 2> = Fixed(a);
1469            for b in -999..=999 {
1470                if b != 0 {
1471                    let bf: Fixed<10, 3> = Fixed(b);
1472                    let cf: Fixed<10, 5> = af.checked_div_generic(bf).unwrap();
1473                    assert_eq!(cf, Fixed::<10, 5>(a * 1_000_000 / b));
1474                    let df: Fixed<10, 6> = af.checked_div_generic(bf).unwrap();
1475                    assert_eq!(df, Fixed::<10, 6>(a * 10_000_000 / b));
1476                    let ef: Fixed<10, 0> = af.checked_div_generic(bf).unwrap();
1477                    assert_eq!(ef, Fixed::<10, 0>(a * 10 / b));
1478                }
1479            }
1480        }
1481    }
1482
1483    #[test]
1484    fn add() {
1485        // A few specific handwritten cases.
1486        assert_eq!(f(1.23) + f(2.34), f(3.57));
1487        assert_eq!(f(-1.23) + f(2.34), f(1.11));
1488        assert_eq!(f(1.23) + f(-2.34), f(-1.11));
1489        assert_eq!(f(-1.23) + f(-2.34), f(-3.57));
1490
1491        // General case.
1492        for a in -999..=999 {
1493            let af: Fixed<10, 2> = Fixed(a);
1494            for b in -999..=999 {
1495                let bf: Fixed<10, 2> = Fixed(b);
1496                assert_eq!(af + bf, Fixed::<10, 2>(a + b));
1497            }
1498        }
1499
1500        // General case with overflow.
1501        for a in -999..=999 {
1502            let af: Fixed<3, 2> = Fixed(a);
1503            for b in -999..=999 {
1504                let bf: Fixed<3, 2> = Fixed(b);
1505                let c = a + b;
1506                let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1507                assert_eq!(af.checked_add(&bf), expected);
1508            }
1509        }
1510
1511        // General case with type conversion.
1512        for a in -999..=999 {
1513            let af: Fixed<10, 2> = Fixed(a);
1514            for b in -999..=999 {
1515                let bf: Fixed<10, 3> = Fixed(b);
1516                let cf: Fixed<10, 5> = af.checked_add_generic(bf).unwrap();
1517                assert_eq!(
1518                    cf,
1519                    Fixed::<10, 5>(a * 1000 + b * 100),
1520                    "{af} + {bf} ?= {cf}"
1521                );
1522                let cf: Fixed<10, 5> = bf.checked_add_generic(af).unwrap();
1523                assert_eq!(
1524                    cf,
1525                    Fixed::<10, 5>(a * 1000 + b * 100),
1526                    "{bf} + {af} ?= {cf}"
1527                );
1528                let df: Fixed<10, 6> = af.checked_add_generic(bf).unwrap();
1529                assert_eq!(
1530                    df,
1531                    Fixed::<10, 6>(a * 10_000 + b * 1000),
1532                    "{af} + {bf} ?= {df}"
1533                );
1534                let ef: Fixed<10, 0> = af.checked_add_generic(bf).unwrap();
1535                assert_eq!(
1536                    ef,
1537                    Fixed::<10, 0>((a * 10 + b) / 1000),
1538                    "{af} + {bf} ?= {ef}"
1539                );
1540            }
1541        }
1542    }
1543
1544    #[test]
1545    fn sub() {
1546        // A few specific handwritten cases.
1547        assert_eq!(f(1.23) - f(2.34), f(-1.11));
1548        assert_eq!(f(-1.23) - f(2.34), f(-3.57));
1549        assert_eq!(f(1.23) - f(-2.34), f(3.57));
1550        assert_eq!(f(-1.23) - f(-2.34), f(1.11));
1551
1552        // General case.
1553        for a in -999..=999 {
1554            let af: Fixed<10, 2> = Fixed(a);
1555            for b in -999..=999 {
1556                let bf: Fixed<10, 2> = Fixed(b);
1557                assert_eq!(af - bf, Fixed::<10, 2>(a - b));
1558            }
1559        }
1560
1561        // General case with overflow.
1562        for a in -999..=999 {
1563            let af: Fixed<3, 2> = Fixed(a);
1564            for b in -999..=999 {
1565                let bf: Fixed<3, 2> = Fixed(b);
1566                let c = a - b;
1567                let expected = (c.unsigned_abs() < 1000).then_some(Fixed(c));
1568                assert_eq!(af.checked_sub(&bf), expected);
1569            }
1570        }
1571
1572        // General case with type conversion.
1573        for a in -999..=999 {
1574            let af: Fixed<10, 2> = Fixed(a);
1575            for b in -999..=999 {
1576                let bf: Fixed<10, 3> = Fixed(b);
1577                let cf: Fixed<10, 5> = af.checked_sub_generic(bf).unwrap();
1578                assert_eq!(
1579                    cf,
1580                    Fixed::<10, 5>(a * 1000 - b * 100),
1581                    "{af} - {bf} ?= {cf}"
1582                );
1583                let cf: Fixed<10, 5> = bf.checked_sub_generic(af).unwrap();
1584                assert_eq!(
1585                    cf,
1586                    Fixed::<10, 5>(b * 100 - a * 1000),
1587                    "{bf} - {af} ?= {cf}"
1588                );
1589                let df: Fixed<10, 6> = af.checked_sub_generic(bf).unwrap();
1590                assert_eq!(df, Fixed::<10, 6>(a * 10_000 - b * 1000));
1591            }
1592        }
1593    }
1594
1595    #[test]
1596    fn powi() {
1597        assert_eq!(
1598            Fixed::<10, 8>::from_str("1.12345678")
1599                .unwrap()
1600                .powi(8)
1601                .to_string()
1602                .as_str(),
1603            "2.53776238"
1604        );
1605        assert_eq!(f(2.0).powi(3), f(8.0));
1606        assert_eq!(f(-2.0).powi(3), f(-8.0));
1607        assert_eq!(f(1.7).powi(8), f(69.75));
1608        assert_eq!(f(1.7).powi(-8), f(0.01));
1609        assert_eq!(f(0.0).powi(1), f(0.0));
1610        assert_eq!(f(0.0).checked_powi(0), None);
1611        assert_eq!(f(0.0).checked_powi(-1), None);
1612    }
1613
1614    #[test]
1615    fn convert() {
1616        let a = Fixed::<10, 10>::from_str("0.0123456789").unwrap();
1617        assert_eq!(&a.convert::<10, 0>().unwrap().to_string(), "0");
1618        assert_eq!(&a.convert::<10, 1>().unwrap().to_string(), "0");
1619        assert_eq!(&a.convert::<10, 2>().unwrap().to_string(), "0.01");
1620        assert_eq!(&a.convert::<10, 3>().unwrap().to_string(), "0.012");
1621        assert_eq!(&a.convert::<10, 4>().unwrap().to_string(), "0.0123");
1622        assert_eq!(&a.convert::<10, 5>().unwrap().to_string(), "0.01234");
1623        assert_eq!(&a.convert::<10, 6>().unwrap().to_string(), "0.012345");
1624        assert_eq!(&a.convert::<10, 7>().unwrap().to_string(), "0.0123456");
1625        assert_eq!(&a.convert::<10, 8>().unwrap().to_string(), "0.01234567");
1626        assert_eq!(&a.convert::<10, 9>().unwrap().to_string(), "0.012345678");
1627        assert_eq!(&a.convert::<10, 10>().unwrap().to_string(), "0.0123456789");
1628        assert_eq!(&a.convert_round_even::<10, 0>().unwrap().to_string(), "0");
1629        assert_eq!(&a.convert_round_even::<10, 1>().unwrap().to_string(), "0");
1630        assert_eq!(
1631            &a.convert_round_even::<10, 2>().unwrap().to_string(),
1632            "0.01"
1633        );
1634        assert_eq!(
1635            &a.convert_round_even::<10, 3>().unwrap().to_string(),
1636            "0.012"
1637        );
1638        assert_eq!(
1639            &a.convert_round_even::<10, 4>().unwrap().to_string(),
1640            "0.0123"
1641        );
1642        assert_eq!(
1643            &a.convert_round_even::<10, 5>().unwrap().to_string(),
1644            "0.01235"
1645        );
1646        assert_eq!(
1647            &a.convert_round_even::<10, 6>().unwrap().to_string(),
1648            "0.012346"
1649        );
1650        assert_eq!(
1651            &a.convert_round_even::<10, 7>().unwrap().to_string(),
1652            "0.0123457"
1653        );
1654        assert_eq!(
1655            &a.convert_round_even::<10, 8>().unwrap().to_string(),
1656            "0.01234568"
1657        );
1658        assert_eq!(
1659            &a.convert_round_even::<10, 9>().unwrap().to_string(),
1660            "0.012345679"
1661        );
1662        assert_eq!(
1663            &a.convert_round_even::<10, 10>().unwrap().to_string(),
1664            "0.0123456789"
1665        );
1666
1667        let b = Fixed::<10, 5>::from_str("12345.67895").unwrap();
1668        assert_eq!(&b.convert::<10, 0>().unwrap().to_string(), "12345");
1669        assert_eq!(&b.convert::<10, 1>().unwrap().to_string(), "12345.6");
1670        assert_eq!(&b.convert::<10, 2>().unwrap().to_string(), "12345.67");
1671        assert_eq!(&b.convert::<10, 3>().unwrap().to_string(), "12345.678");
1672        assert_eq!(&b.convert::<10, 4>().unwrap().to_string(), "12345.6789");
1673        assert_eq!(&b.convert::<10, 5>().unwrap().to_string(), "12345.67895");
1674        assert_eq!(b.convert::<10, 6>(), None);
1675        assert_eq!(b.convert::<10, 7>(), None);
1676        assert_eq!(b.convert::<10, 8>(), None);
1677        assert_eq!(b.convert::<10, 9>(), None);
1678        assert_eq!(b.convert::<10, 10>(), None);
1679        assert_eq!(
1680            &b.convert_round_even::<10, 0>().unwrap().to_string(),
1681            "12346"
1682        );
1683        assert_eq!(
1684            &b.convert_round_even::<10, 1>().unwrap().to_string(),
1685            "12345.7"
1686        );
1687        assert_eq!(
1688            &b.convert_round_even::<10, 2>().unwrap().to_string(),
1689            "12345.68"
1690        );
1691        assert_eq!(
1692            &b.convert_round_even::<10, 3>().unwrap().to_string(),
1693            "12345.679"
1694        );
1695        assert_eq!(
1696            &b.convert_round_even::<10, 4>().unwrap().to_string(),
1697            "12345.679"
1698        );
1699        assert_eq!(
1700            &b.convert_round_even::<10, 5>().unwrap().to_string(),
1701            "12345.67895"
1702        );
1703        assert_eq!(b.convert_round_even::<10, 6>(), None);
1704        assert_eq!(b.convert_round_even::<10, 7>(), None);
1705        assert_eq!(b.convert_round_even::<10, 8>(), None);
1706        assert_eq!(b.convert_round_even::<10, 9>(), None);
1707        assert_eq!(b.convert_round_even::<10, 10>(), None);
1708    }
1709
1710    #[test]
1711    fn constants() {
1712        assert_eq!(Fixed::<5, 0>::MAX, Fixed::<5, 0>(99999));
1713        assert_eq!(Fixed::<5, 0>::MIN, Fixed::<5, 0>(-99999));
1714        assert_eq!(Fixed::<5, 0>::ZERO, Fixed::<5, 0>(0));
1715        assert_eq!(Fixed::<5, 0>::ONE, Fixed::<5, 0>(1));
1716
1717        assert_eq!(Fixed::<5, 1>::MAX, Fixed::<5, 1>(99999));
1718        assert_eq!(Fixed::<5, 1>::MIN, Fixed::<5, 1>(-99999));
1719        assert_eq!(Fixed::<5, 1>::ZERO, Fixed::<5, 1>(0));
1720        assert_eq!(Fixed::<5, 1>::ONE, Fixed::<5, 1>(10));
1721
1722        assert_eq!(Fixed::<5, 2>::MAX, Fixed::<5, 2>(99999));
1723        assert_eq!(Fixed::<5, 2>::MIN, Fixed::<5, 2>(-99999));
1724        assert_eq!(Fixed::<5, 2>::ZERO, Fixed::<5, 2>(0));
1725        assert_eq!(Fixed::<5, 2>::ONE, Fixed::<5, 2>(100));
1726
1727        assert_eq!(Fixed::<5, 3>::MAX, Fixed::<5, 3>(99999));
1728        assert_eq!(Fixed::<5, 3>::MIN, Fixed::<5, 3>(-99999));
1729        assert_eq!(Fixed::<5, 3>::ZERO, Fixed::<5, 3>(0));
1730        assert_eq!(Fixed::<5, 3>::ONE, Fixed::<5, 3>(1000));
1731
1732        assert_eq!(Fixed::<5, 4>::MAX, Fixed::<5, 4>(99999));
1733        assert_eq!(Fixed::<5, 4>::MIN, Fixed::<5, 4>(-99999));
1734        assert_eq!(Fixed::<5, 4>::ZERO, Fixed::<5, 4>(0));
1735        assert_eq!(Fixed::<5, 4>::ONE, Fixed::<5, 4>(10000));
1736
1737        assert_eq!(Fixed::<5, 5>::MAX, Fixed::<5, 5>(99999));
1738        assert_eq!(Fixed::<5, 5>::MIN, Fixed::<5, 5>(-99999));
1739        assert_eq!(Fixed::<5, 5>::ZERO, Fixed::<5, 5>(0));
1740        // This would panic at compile time.  See [super::_invalid_constant_test].
1741        //let _ = Fixed::<5, 5>::ONE;
1742    }
1743
1744    #[test]
1745    fn floor() {
1746        assert_eq!(f(5.0).floor(), f(5.0));
1747        assert_eq!(f(5.1).floor(), f(5.0));
1748        assert_eq!(f(5.5).floor(), f(5.0));
1749        assert_eq!(f(5.9).floor(), f(5.0));
1750        assert_eq!(f(-5.0).floor(), f(-5.0));
1751        assert_eq!(f(-5.1).floor(), f(-6.0));
1752        assert_eq!(f(-5.5).floor(), f(-6.0));
1753        assert_eq!(f(-5.6).floor(), f(-6.0));
1754        assert_eq!(f(4.0).floor(), f(4.0));
1755        assert_eq!(f(4.1).floor(), f(4.0));
1756        assert_eq!(f(4.5).floor(), f(4.0));
1757        assert_eq!(f(4.9).floor(), f(4.0));
1758        assert_eq!(f(-4.0).floor(), f(-4.0));
1759        assert_eq!(f(-4.1).floor(), f(-5.0));
1760        assert_eq!(f(-4.5).floor(), f(-5.0));
1761        assert_eq!(f(-4.6).floor(), f(-5.0));
1762        assert_eq!(f(-99_999_999.0).floor(), f(-99_999_999.0));
1763        assert_eq!(f(-99_999_999.1).checked_floor(), None);
1764        assert_eq!(f(-99_999_999.5).checked_floor(), None);
1765        assert_eq!(f(-99_999_999.6).checked_floor(), None);
1766    }
1767
1768    #[test]
1769    fn ceil() {
1770        assert_eq!(f(5.0).ceil(), f(5.0));
1771        assert_eq!(f(5.1).ceil(), f(6.0));
1772        assert_eq!(f(5.5).ceil(), f(6.0));
1773        assert_eq!(f(5.9).ceil(), f(6.0));
1774        assert_eq!(f(-5.0).ceil(), f(-5.0));
1775        assert_eq!(f(-5.1).ceil(), f(-5.0));
1776        assert_eq!(f(-5.5).ceil(), f(-5.0));
1777        assert_eq!(f(-5.6).ceil(), f(-5.0));
1778        assert_eq!(f(4.0).ceil(), f(4.0));
1779        assert_eq!(f(4.1).ceil(), f(5.0));
1780        assert_eq!(f(4.5).ceil(), f(5.0));
1781        assert_eq!(f(4.9).ceil(), f(5.0));
1782        assert_eq!(f(-4.0).ceil(), f(-4.0));
1783        assert_eq!(f(-4.1).ceil(), f(-4.0));
1784        assert_eq!(f(-4.5).ceil(), f(-4.0));
1785        assert_eq!(f(-4.6).ceil(), f(-4.0));
1786        assert_eq!(f(99_999_999.0).ceil(), f(99_999_999.0));
1787        assert_eq!(f(99_999_999.1).checked_ceil(), None);
1788        assert_eq!(f(99_999_999.5).checked_ceil(), None);
1789        assert_eq!(f(99_999_999.6).checked_ceil(), None);
1790    }
1791
1792    #[test]
1793    fn trunc() {
1794        fn test(x: f64, expected: f64) {
1795            assert_eq!(f(x).trunc(), f(expected));
1796            assert_eq!(f(x).trunc_digits(0), f(expected));
1797        }
1798
1799        test(5.0, 5.0);
1800        test(5.1, 5.0);
1801        test(5.5, 5.0);
1802        test(5.9, 5.0);
1803        test(-5.0, -5.0);
1804        test(-5.1, -5.0);
1805        test(-5.5, -5.0);
1806        test(-5.6, -5.0);
1807        test(4.0, 4.0);
1808        test(4.1, 4.0);
1809        test(4.5, 4.0);
1810        test(4.9, 4.0);
1811        test(-4.0, -4.0);
1812        test(-4.1, -4.0);
1813        test(-4.5, -4.0);
1814        test(-4.6, -4.0);
1815        test(99_999_999.0, 99_999_999.0);
1816        test(99_999_999.1, 99_999_999.0);
1817        test(99_999_999.5, 99_999_999.0);
1818        test(99_999_999.6, 99_999_999.0);
1819        test(-99_999_999.0, -99_999_999.0);
1820        test(-99_999_999.1, -99_999_999.0);
1821        test(-99_999_999.5, -99_999_999.0);
1822        test(-99_999_999.6, -99_999_999.0);
1823    }
1824
1825    #[test]
1826    fn trunc_digits() {
1827        let x = Fixed::<10, 4>(245368746);
1828        assert_eq!(x.trunc_digits(5).to_string(), "24536.8746");
1829        assert_eq!(x.trunc_digits(4).to_string(), "24536.8746");
1830        assert_eq!(x.trunc_digits(3).to_string(), "24536.874");
1831        assert_eq!(x.trunc_digits(2).to_string(), "24536.87");
1832        assert_eq!(x.trunc_digits(1).to_string(), "24536.8");
1833        assert_eq!(x.trunc_digits(0).to_string(), "24536");
1834        assert_eq!(x.trunc_digits(-1).to_string(), "24530");
1835        assert_eq!(x.trunc_digits(-2).to_string(), "24500");
1836        assert_eq!(x.trunc_digits(-3).to_string(), "24000");
1837        assert_eq!(x.trunc_digits(-4).to_string(), "20000");
1838        assert_eq!(x.trunc_digits(-5).to_string(), "0");
1839        assert_eq!(x.trunc_digits(-50).to_string(), "0");
1840
1841        let x = -x;
1842        assert_eq!(x.trunc_digits(5).to_string(), "-24536.8746");
1843        assert_eq!(x.trunc_digits(4).to_string(), "-24536.8746");
1844        assert_eq!(x.trunc_digits(3).to_string(), "-24536.874");
1845        assert_eq!(x.trunc_digits(2).to_string(), "-24536.87");
1846        assert_eq!(x.trunc_digits(1).to_string(), "-24536.8");
1847        assert_eq!(x.trunc_digits(0).to_string(), "-24536");
1848        assert_eq!(x.trunc_digits(-1).to_string(), "-24530");
1849        assert_eq!(x.trunc_digits(-2).to_string(), "-24500");
1850        assert_eq!(x.trunc_digits(-3).to_string(), "-24000");
1851        assert_eq!(x.trunc_digits(-4).to_string(), "-20000");
1852        assert_eq!(x.trunc_digits(-5).to_string(), "0");
1853        assert_eq!(x.trunc_digits(-50).to_string(), "0");
1854    }
1855
1856    #[test]
1857    fn sign() {
1858        assert_eq!(f(-0.1).sign(), Fixed::<1, 0>::try_from(-1).unwrap());
1859        assert_eq!(f(0.0).sign(), Fixed::<1, 0>::try_from(0).unwrap());
1860        assert_eq!(f(0.5).sign(), Fixed::<1, 0>::try_from(1).unwrap());
1861    }
1862
1863    #[test]
1864    fn sqrt() {
1865        // A few selected values.
1866        assert_eq!(f(0.0).sqrt(), f(0.0));
1867        assert_eq!(f(1.0).sqrt(), f(1.0));
1868        assert_eq!(f(2.0).sqrt(), f(1.41));
1869        assert_eq!(f(3.0).sqrt(), f(1.73));
1870        assert_eq!(f(4.0).sqrt(), f(2.0));
1871        assert_eq!(f(-1.0).checked_sqrt(), None);
1872
1873        // General case.
1874        for a in 0..=999 {
1875            let af: Fixed<10, 2> = Fixed(a);
1876            assert_eq!(af.sqrt(), Fixed::<10, 2>((a * 100).isqrt()));
1877        }
1878    }
1879
1880    #[test]
1881    fn nullable() {
1882        /// Adds `a` and `b` and returns the sum.  Return `None` if `a` or `b`
1883        /// is `None` or if their sum is out of range.
1884        fn nullable_checked_add_generic<
1885            const PA: usize,
1886            const SA: usize,
1887            const PB: usize,
1888            const SB: usize,
1889            const PC: usize,
1890            const SC: usize,
1891        >(
1892            a: Option<Fixed<PA, SA>>,
1893            b: Option<Fixed<PB, SB>>,
1894        ) -> Option<Fixed<PC, SC>> {
1895            a.zip(b).and_then(|(a, b)| a.checked_add_generic(b))
1896        }
1897
1898        let a: Option<Fixed<10, 2>> = Some("1.23".parse().unwrap());
1899        let b: Option<Fixed<5, 4>> = Some("4.5678".parse().unwrap());
1900        let c: Option<Fixed<10, 4>> = nullable_checked_add_generic(a, b);
1901        assert_eq!(c, Some("5.7978".parse().unwrap()));
1902    }
1903
1904    #[test]
1905    fn to_integer() {
1906        for x in -9999..=9999 {
1907            let f = Fixed::<4, 1>(x);
1908            assert_eq!(i128::from(f), x / 10);
1909            assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
1910            assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
1911            assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
1912            assert_eq!(
1913                i8::try_from(f).ok(),
1914                (-1289..=1279).contains(&x).then_some((x / 10) as i8)
1915            );
1916            assert_eq!(
1917                u128::try_from(f).ok(),
1918                (x > -10).then_some((x / 10) as u128)
1919            );
1920            assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
1921            assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
1922            assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
1923            assert_eq!(
1924                u8::try_from(f).ok(),
1925                (-9..=2559).contains(&x).then_some((x / 10) as u8)
1926            );
1927        }
1928    }
1929
1930    #[test]
1931    fn compare_against_fixed() {
1932        fn check_comparisons<const PA: usize, const SA: usize, const PB: usize, const SB: usize>(
1933            fx: Fixed<PA, SA>,
1934            fy: Fixed<PB, SB>,
1935            x: i128,
1936            y: i128,
1937        ) {
1938            assert_eq!(fx == fy, x == y);
1939            assert_eq!(fx != fy, x != y);
1940            assert_eq!(fx > fy, x > y);
1941            assert_eq!(fx >= fy, x >= y);
1942            assert_eq!(fx < fy, x < y);
1943            assert_eq!(fx <= fy, x <= y);
1944        }
1945
1946        for x in -999..=999 {
1947            let fx = Fixed::<3, 1>(x);
1948            for y in -999..=999 {
1949                check_comparisons(fx, Fixed::<3, 0>(y), x, y * 10);
1950                check_comparisons(fx, Fixed::<3, 1>(y), x, y);
1951                check_comparisons(fx, Fixed::<3, 2>(y), x * 10, y);
1952            }
1953        }
1954    }
1955
1956    #[test]
1957    fn compare_against_integers() {
1958        for x in -999..=999 {
1959            let f = Fixed::<3, 1>(x);
1960            for y in -100..=100 {
1961                let expect = x == y * 10;
1962                assert_eq!(f == y as i8, expect);
1963                assert_eq!(f == y as i16, expect);
1964                assert_eq!(f == y as i32, expect);
1965                assert_eq!(f == y as i64, expect);
1966                assert_eq!(f == y, expect);
1967                assert_eq!(f == y as isize, expect);
1968                if y >= 0 {
1969                    assert_eq!(f == y as u8, expect);
1970                    assert_eq!(f == y as u16, expect);
1971                    assert_eq!(f == y as u32, expect);
1972                    assert_eq!(f == y as u64, expect);
1973                    assert_eq!(f == y as u128, expect);
1974                    assert_eq!(f == y as usize, expect);
1975                }
1976            }
1977        }
1978    }
1979
1980    #[test]
1981    fn unsigned_encoding() {
1982        type F = Fixed<3, 1>;
1983        for x in -999..=999 {
1984            let f = Fixed::<3, 1>(x);
1985            assert_eq!(F::from_unsigned_encoding(f.to_unsigned_encoding()), Some(f));
1986        }
1987        assert_eq!(F::MIN.to_unsigned_encoding(), 0);
1988        assert_eq!(F::ZERO.to_unsigned_encoding(), 999);
1989        assert_eq!(F::MAX.to_unsigned_encoding(), 999 * 2);
1990        assert_eq!(F::from_unsigned_encoding(0), Some(F::MIN));
1991        assert_eq!(F::from_unsigned_encoding(999), Some(F::ZERO));
1992        assert_eq!(F::from_unsigned_encoding(999 * 2), Some(F::MAX));
1993        assert_eq!(F::from_unsigned_encoding(999 * 2 + 1), None);
1994    }
1995
1996    #[test]
1997    fn new() {
1998        type F1 = Fixed<11, 1>;
1999        assert_eq!(F1::new(435, -8), None);
2000        assert_eq!(F1::new(435, -7).unwrap().to_string(), "4350000000");
2001        assert_eq!(F1::new(435, -6).unwrap().to_string(), "435000000");
2002        assert_eq!(F1::new(435, -5).unwrap().to_string(), "43500000");
2003        assert_eq!(F1::new(435, -4).unwrap().to_string(), "4350000");
2004        assert_eq!(F1::new(435, -3).unwrap().to_string(), "435000");
2005        assert_eq!(F1::new(435, -2).unwrap().to_string(), "43500");
2006        assert_eq!(F1::new(435, -1).unwrap().to_string(), "4350");
2007        assert_eq!(F1::new(435, 0).unwrap().to_string(), "435");
2008        assert_eq!(F1::new(435, 1).unwrap().to_string(), "43.5");
2009        assert_eq!(F1::new(435, 2).unwrap().to_string(), "4.3");
2010        assert_eq!(F1::new(435, 3).unwrap().to_string(), "0.4");
2011        assert_eq!(F1::new(435, 4).unwrap().to_string(), "0");
2012
2013        type F2 = Fixed<11, 2>;
2014        assert_eq!(F2::new(435, -7), None);
2015        assert_eq!(F2::new(435, -6).unwrap().to_string(), "435000000");
2016        assert_eq!(F2::new(435, -5).unwrap().to_string(), "43500000");
2017        assert_eq!(F2::new(435, -4).unwrap().to_string(), "4350000");
2018        assert_eq!(F2::new(435, -3).unwrap().to_string(), "435000");
2019        assert_eq!(F2::new(435, -2).unwrap().to_string(), "43500");
2020        assert_eq!(F2::new(435, -1).unwrap().to_string(), "4350");
2021        assert_eq!(F2::new(435, 0).unwrap().to_string(), "435");
2022        assert_eq!(F2::new(435, 1).unwrap().to_string(), "43.5");
2023        assert_eq!(F2::new(435, 2).unwrap().to_string(), "4.35");
2024        assert_eq!(F2::new(435, 3).unwrap().to_string(), "0.43");
2025        assert_eq!(F2::new(435, 4).unwrap().to_string(), "0.04");
2026        assert_eq!(F2::new(435, 5).unwrap().to_string(), "0");
2027    }
2028
2029    #[test]
2030    fn new_round_even() {
2031        type F1 = Fixed<11, 1>;
2032        assert_eq!(F1::new_round_even(435, -8), None);
2033        assert_eq!(
2034            F1::new_round_even(435, -7).unwrap().to_string(),
2035            "4350000000"
2036        );
2037        assert_eq!(
2038            F1::new_round_even(435, -6).unwrap().to_string(),
2039            "435000000"
2040        );
2041        assert_eq!(F1::new_round_even(435, -5).unwrap().to_string(), "43500000");
2042        assert_eq!(F1::new_round_even(435, -4).unwrap().to_string(), "4350000");
2043        assert_eq!(F1::new_round_even(435, -3).unwrap().to_string(), "435000");
2044        assert_eq!(F1::new_round_even(435, -2).unwrap().to_string(), "43500");
2045        assert_eq!(F1::new_round_even(435, -1).unwrap().to_string(), "4350");
2046        assert_eq!(F1::new_round_even(435, 0).unwrap().to_string(), "435");
2047        assert_eq!(F1::new_round_even(435, 1).unwrap().to_string(), "43.5");
2048        assert_eq!(F1::new_round_even(435, 2).unwrap().to_string(), "4.4");
2049        assert_eq!(F1::new_round_even(435, 3).unwrap().to_string(), "0.4");
2050        assert_eq!(F1::new_round_even(435, 4).unwrap().to_string(), "0");
2051
2052        type F2 = Fixed<11, 2>;
2053        assert_eq!(F2::new_round_even(435, -7), None);
2054        assert_eq!(
2055            F2::new_round_even(435, -6).unwrap().to_string(),
2056            "435000000"
2057        );
2058        assert_eq!(F2::new_round_even(435, -5).unwrap().to_string(), "43500000");
2059        assert_eq!(F2::new_round_even(435, -4).unwrap().to_string(), "4350000");
2060        assert_eq!(F2::new_round_even(435, -3).unwrap().to_string(), "435000");
2061        assert_eq!(F2::new_round_even(435, -2).unwrap().to_string(), "43500");
2062        assert_eq!(F2::new_round_even(435, -1).unwrap().to_string(), "4350");
2063        assert_eq!(F2::new_round_even(435, 0).unwrap().to_string(), "435");
2064        assert_eq!(F2::new_round_even(435, 1).unwrap().to_string(), "43.5");
2065        assert_eq!(F2::new_round_even(435, 2).unwrap().to_string(), "4.35");
2066        assert_eq!(F2::new_round_even(435, 3).unwrap().to_string(), "0.44");
2067        assert_eq!(F2::new_round_even(435, 4).unwrap().to_string(), "0.04");
2068        assert_eq!(F2::new_round_even(435, 5).unwrap().to_string(), "0");
2069    }
2070}