feldera_fxp/
lib.rs

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