feldera_fxp/
lib.rs

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