fixed/
saturating.rs

1// Copyright © 2018–2025 Trevor Spiteri
2
3// This library is free software: you can redistribute it and/or
4// modify it under the terms of either
5//
6//   * the Apache License, Version 2.0 or
7//   * the MIT License
8//
9// at your option.
10//
11// You should have recieved copies of the Apache License and the MIT
12// License along with the library. If not, see
13// <https://www.apache.org/licenses/LICENSE-2.0> and
14// <https://opensource.org/licenses/MIT>.
15
16use crate::from_str::ParseFixedError;
17use crate::traits::{Fixed, FixedSigned, FixedUnsigned, FromFixed, ToFixed};
18use crate::types::extra::{LeEqU8, LeEqU16, LeEqU32, LeEqU64, LeEqU128};
19use crate::{
20    FixedI8, FixedI16, FixedI32, FixedI64, FixedI128, FixedU8, FixedU16, FixedU32, FixedU64,
21    FixedU128,
22};
23use core::fmt::{
24    Binary, Debug, Display, Formatter, LowerExp, LowerHex, Octal, Result as FmtResult, UpperExp,
25    UpperHex,
26};
27use core::iter::{Product, Sum};
28use core::ops::{
29    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
30    Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,
31};
32use core::str::FromStr;
33
34/// Provides saturating arithmetic on fixed-point numbers.
35///
36/// The underlying value can be retrieved through the `.0` index.
37///
38/// # Examples
39///
40/// ```rust
41/// use fixed::types::I16F16;
42/// use fixed::Saturating;
43/// let max = Saturating(I16F16::MAX);
44/// let delta = Saturating(I16F16::DELTA);
45/// assert_eq!(I16F16::MAX, (max + delta).0);
46/// ```
47#[repr(transparent)]
48#[derive(Clone, Copy, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
49pub struct Saturating<F>(pub F);
50
51impl<F: Fixed> Saturating<F> {
52    /// Zero.
53    ///
54    /// See also <code>FixedI32::[ZERO][FixedI32::ZERO]</code> and
55    /// <code>FixedU32::[ZERO][FixedU32::ZERO]</code>.
56    ///
57    /// # Examples
58    ///
59    /// ```rust
60    /// use fixed::types::I16F16;
61    /// use fixed::Saturating;
62    /// assert_eq!(Saturating::<I16F16>::ZERO, Saturating(I16F16::ZERO));
63    /// ```
64    pub const ZERO: Saturating<F> = Saturating(F::ZERO);
65
66    /// The difference between any two successive representable numbers, <i>Δ</i>.
67    ///
68    /// See also <code>FixedI32::[DELTA][FixedI32::DELTA]</code> and
69    /// <code>FixedU32::[DELTA][FixedU32::DELTA]</code>.
70    ///
71    /// # Examples
72    ///
73    /// ```rust
74    /// use fixed::types::I16F16;
75    /// use fixed::Saturating;
76    /// assert_eq!(Saturating::<I16F16>::DELTA, Saturating(I16F16::DELTA));
77    /// ```
78    pub const DELTA: Saturating<F> = Saturating(F::DELTA);
79
80    /// The smallest value that can be represented.
81    ///
82    /// See also <code>FixedI32::[MIN][FixedI32::MIN]</code> and
83    /// <code>FixedU32::[MIN][FixedU32::MIN]</code>.
84    ///
85    /// # Examples
86    ///
87    /// ```rust
88    /// use fixed::types::I16F16;
89    /// use fixed::Saturating;
90    /// assert_eq!(Saturating::<I16F16>::MIN, Saturating(I16F16::MIN));
91    /// ```
92    pub const MIN: Saturating<F> = Saturating(F::MIN);
93
94    /// The largest value that can be represented.
95    ///
96    /// See also <code>FixedI32::[MAX][FixedI32::MAX]</code> and
97    /// <code>FixedU32::[MAX][FixedU32::MAX]</code>.
98    ///
99    /// # Examples
100    ///
101    /// ```rust
102    /// use fixed::types::I16F16;
103    /// use fixed::Saturating;
104    /// assert_eq!(Saturating::<I16F16>::MAX, Saturating(I16F16::MAX));
105    /// ```
106    pub const MAX: Saturating<F> = Saturating(F::MAX);
107
108    /// [`true`] if the type is signed.
109    ///
110    /// See also <code>FixedI32::[IS\_SIGNED][FixedI32::IS_SIGNED]</code> and
111    /// <code>FixedU32::[IS\_SIGNED][FixedU32::IS_SIGNED]</code>.
112    ///
113    /// # Examples
114    ///
115    /// ```rust
116    /// use fixed::types::{I16F16, U16F16};
117    /// use fixed::Saturating;
118    /// assert!(Saturating::<I16F16>::IS_SIGNED);
119    /// assert!(!Saturating::<U16F16>::IS_SIGNED);
120    /// ```
121    pub const IS_SIGNED: bool = F::IS_SIGNED;
122
123    /// The number of integer bits.
124    ///
125    /// See also <code>FixedI32::[INT\_NBITS][FixedI32::INT_NBITS]</code> and
126    /// <code>FixedU32::[INT\_NBITS][FixedU32::INT_NBITS]</code>.
127    ///
128    /// # Examples
129    ///
130    /// ```rust
131    /// use fixed::types::I16F16;
132    /// use fixed::Saturating;
133    /// assert_eq!(Saturating::<I16F16>::INT_NBITS, I16F16::INT_NBITS);
134    /// ```
135    pub const INT_NBITS: u32 = F::INT_NBITS;
136
137    /// The number of fractional bits.
138    ///
139    /// See also <code>FixedI32::[FRAC\_NBITS][FixedI32::FRAC_NBITS]</code> and
140    /// <code>FixedU32::[FRAC\_NBITS][FixedU32::FRAC_NBITS]</code>.
141    ///
142    /// # Examples
143    ///
144    /// ```rust
145    /// use fixed::types::I16F16;
146    /// use fixed::Saturating;
147    /// assert_eq!(Saturating::<I16F16>::FRAC_NBITS, I16F16::FRAC_NBITS);
148    /// ```
149    pub const FRAC_NBITS: u32 = F::FRAC_NBITS;
150
151    /// Creates a fixed-point number that has a bitwise representation
152    /// identical to the given integer.
153    ///
154    /// See also <code>FixedI32::[from\_bits][FixedI32::from_bits]</code> and
155    /// <code>FixedU32::[from\_bits][FixedU32::from_bits]</code>.
156    ///
157    /// # Examples
158    ///
159    /// ```rust
160    /// use fixed::types::I16F16;
161    /// use fixed::Saturating;
162    /// assert_eq!(Saturating::<I16F16>::from_bits(0x1C), Saturating(I16F16::from_bits(0x1C)));
163    /// ```
164    #[inline]
165    pub fn from_bits(bits: F::Bits) -> Saturating<F> {
166        Saturating(F::from_bits(bits))
167    }
168
169    /// Creates an integer that has a bitwise representation identical
170    /// to the given fixed-point number.
171    ///
172    /// See also <code>FixedI32::[to\_bits][FixedI32::to_bits]</code> and
173    /// <code>FixedU32::[to\_bits][FixedU32::to_bits]</code>.
174    ///
175    /// # Examples
176    ///
177    /// ```rust
178    /// use fixed::types::I16F16;
179    /// use fixed::Saturating;
180    /// let w = Saturating(I16F16::from_bits(0x1C));
181    /// assert_eq!(w.to_bits(), 0x1C);
182    /// ```
183    #[inline]
184    pub fn to_bits(self) -> F::Bits {
185        self.0.to_bits()
186    }
187
188    /// Converts a fixed-point number from big endian to the target’s
189    /// endianness.
190    ///
191    /// See also <code>FixedI32::[from\_be][FixedI32::from_be]</code> and
192    /// <code>FixedU32::[from\_be][FixedU32::from_be]</code>.
193    ///
194    /// # Examples
195    ///
196    /// ```rust
197    /// use fixed::types::I16F16;
198    /// use fixed::Saturating;
199    /// let w = Saturating(I16F16::from_bits(0x1234_5678));
200    /// if cfg!(target_endian = "big") {
201    ///     assert_eq!(Saturating::from_be(w), w);
202    /// } else {
203    ///     assert_eq!(Saturating::from_be(w), w.swap_bytes());
204    /// }
205    /// ```
206    #[inline]
207    pub fn from_be(w: Self) -> Self {
208        Saturating(F::from_be(w.0))
209    }
210
211    /// Converts a fixed-point number from little endian to the
212    /// target’s endianness.
213    ///
214    /// See also <code>FixedI32::[from\_le][FixedI32::from_le]</code> and
215    /// <code>FixedU32::[from\_le][FixedU32::from_le]</code>.
216    ///
217    /// # Examples
218    ///
219    /// ```rust
220    /// use fixed::types::I16F16;
221    /// use fixed::Saturating;
222    /// let w = Saturating(I16F16::from_bits(0x1234_5678));
223    /// if cfg!(target_endian = "little") {
224    ///     assert_eq!(Saturating::from_le(w), w);
225    /// } else {
226    ///     assert_eq!(Saturating::from_le(w), w.swap_bytes());
227    /// }
228    /// ```
229    #[inline]
230    pub fn from_le(w: Self) -> Self {
231        Saturating(F::from_le(w.0))
232    }
233
234    /// Converts `self` to big endian from the target’s endianness.
235    ///
236    /// See also <code>FixedI32::[to\_be][FixedI32::to_be]</code> and
237    /// <code>FixedU32::[to\_be][FixedU32::to_be]</code>.
238    ///
239    /// # Examples
240    ///
241    /// ```rust
242    /// use fixed::types::I16F16;
243    /// use fixed::Saturating;
244    /// let w = Saturating(I16F16::from_bits(0x1234_5678));
245    /// if cfg!(target_endian = "big") {
246    ///     assert_eq!(w.to_be(), w);
247    /// } else {
248    ///     assert_eq!(w.to_be(), w.swap_bytes());
249    /// }
250    /// ```
251    #[inline]
252    #[must_use]
253    pub fn to_be(self) -> Self {
254        Saturating(self.0.to_be())
255    }
256
257    /// Converts `self` to little endian from the target’s endianness.
258    ///
259    /// See also <code>FixedI32::[to\_le][FixedI32::to_le]</code> and
260    /// <code>FixedU32::[to\_le][FixedU32::to_le]</code>.
261    ///
262    /// # Examples
263    ///
264    /// ```rust
265    /// use fixed::types::I16F16;
266    /// use fixed::Saturating;
267    /// let w = Saturating(I16F16::from_bits(0x1234_5678));
268    /// if cfg!(target_endian = "little") {
269    ///     assert_eq!(w.to_le(), w);
270    /// } else {
271    ///     assert_eq!(w.to_le(), w.swap_bytes());
272    /// }
273    /// ```
274    #[inline]
275    #[must_use]
276    pub fn to_le(self) -> Self {
277        Saturating(self.0.to_le())
278    }
279
280    /// Reverses the byte order of the fixed-point number.
281    ///
282    /// See also <code>FixedI32::[swap\_bytes][FixedI32::swap_bytes]</code> and
283    /// <code>FixedU32::[swap\_bytes][FixedU32::swap_bytes]</code>.
284    ///
285    /// # Examples
286    ///
287    /// ```rust
288    /// use fixed::types::I16F16;
289    /// use fixed::Saturating;
290    /// let w = Saturating(I16F16::from_bits(0x1234_5678));
291    /// let swapped = Saturating(I16F16::from_bits(0x7856_3412));
292    /// assert_eq!(w.swap_bytes(), swapped);
293    /// ```
294    #[inline]
295    #[must_use]
296    pub fn swap_bytes(self) -> Self {
297        Saturating(self.0.swap_bytes())
298    }
299
300    /// Creates a fixed-point number from its representation
301    /// as a byte array in big endian.
302    ///
303    /// See also
304    /// <code>FixedI32::[from\_be\_bytes][FixedI32::from_be_bytes]</code> and
305    /// <code>FixedU32::[from\_be\_bytes][FixedU32::from_be_bytes]</code>.
306    ///
307    /// # Examples
308    ///
309    /// ```rust
310    /// use fixed::types::I16F16;
311    /// use fixed::Saturating;
312    /// let bytes = [0x12, 0x34, 0x56, 0x78];
313    /// assert_eq!(
314    ///     Saturating::<I16F16>::from_be_bytes(bytes),
315    ///     Saturating::<I16F16>::from_bits(0x1234_5678)
316    /// );
317    /// ```
318    #[inline]
319    pub fn from_be_bytes(bytes: F::Bytes) -> Self {
320        Saturating(F::from_be_bytes(bytes))
321    }
322
323    /// Creates a fixed-point number from its representation
324    /// as a byte array in little endian.
325    ///
326    /// See also
327    /// <code>FixedI32::[from\_le\_bytes][FixedI32::from_le_bytes]</code> and
328    /// <code>FixedU32::[from\_le\_bytes][FixedU32::from_le_bytes]</code>.
329    ///
330    /// # Examples
331    ///
332    /// ```rust
333    /// use fixed::types::I16F16;
334    /// use fixed::Saturating;
335    /// let bytes = [0x78, 0x56, 0x34, 0x12];
336    /// assert_eq!(
337    ///     Saturating::<I16F16>::from_le_bytes(bytes),
338    ///     Saturating::<I16F16>::from_bits(0x1234_5678)
339    /// );
340    /// ```
341    #[inline]
342    pub fn from_le_bytes(bytes: F::Bytes) -> Self {
343        Saturating(F::from_le_bytes(bytes))
344    }
345
346    /// Creates a fixed-point number from its representation
347    /// as a byte array in native endian.
348    ///
349    /// See also
350    /// <code>FixedI32::[from\_ne\_bytes][FixedI32::from_ne_bytes]</code> and
351    /// <code>FixedU32::[from\_ne\_bytes][FixedU32::from_ne_bytes]</code>.
352    ///
353    /// # Examples
354    ///
355    /// ```rust
356    /// use fixed::types::I16F16;
357    /// use fixed::Saturating;
358    /// let bytes = if cfg!(target_endian = "big") {
359    ///     [0x12, 0x34, 0x56, 0x78]
360    /// } else {
361    ///     [0x78, 0x56, 0x34, 0x12]
362    /// };
363    /// assert_eq!(
364    ///     Saturating::<I16F16>::from_ne_bytes(bytes),
365    ///     Saturating::<I16F16>::from_bits(0x1234_5678)
366    /// );
367    /// ```
368    #[inline]
369    pub fn from_ne_bytes(bytes: F::Bytes) -> Self {
370        Saturating(F::from_ne_bytes(bytes))
371    }
372
373    /// Returns the memory representation of this fixed-point
374    /// number as a byte array in big-endian byte order.
375    ///
376    /// See also <code>FixedI32::[to\_be\_bytes][FixedI32::to_be_bytes]</code>
377    /// and <code>FixedU32::[to\_be\_bytes][FixedU32::to_be_bytes]</code>.
378    ///
379    /// # Examples
380    ///
381    /// ```rust
382    /// use fixed::types::I16F16;
383    /// use fixed::Saturating;
384    /// assert_eq!(
385    ///     Saturating::<I16F16>::from_bits(0x1234_5678).to_be_bytes(),
386    ///     [0x12, 0x34, 0x56, 0x78]
387    /// );
388    /// ```
389    #[inline]
390    pub fn to_be_bytes(self) -> F::Bytes {
391        self.0.to_be_bytes()
392    }
393
394    /// Returns the memory representation of this fixed-point
395    /// number as a byte array in little-endian byte order.
396    ///
397    /// See also <code>FixedI32::[to\_le\_bytes][FixedI32::to_le_bytes]</code>
398    /// and <code>FixedU32::[to\_le\_bytes][FixedU32::to_le_bytes]</code>.
399    ///
400    /// # Examples
401    ///
402    /// ```rust
403    /// use fixed::types::I16F16;
404    /// use fixed::Saturating;
405    /// assert_eq!(
406    ///     Saturating::<I16F16>::from_bits(0x1234_5678).to_le_bytes(),
407    ///     [0x78, 0x56, 0x34, 0x12]
408    /// );
409    /// ```
410    #[inline]
411    pub fn to_le_bytes(self) -> F::Bytes {
412        self.0.to_le_bytes()
413    }
414
415    /// Returns the memory representation of this fixed-point
416    /// number as a byte array in native-endian byte order.
417    ///
418    /// See also <code>FixedI32::[to\_ne\_bytes][FixedI32::to_ne_bytes]</code>
419    /// and <code>FixedU32::[to\_ne\_bytes][FixedU32::to_ne_bytes]</code>.
420    ///
421    /// # Examples
422    ///
423    /// ```rust
424    /// use fixed::types::I16F16;
425    /// use fixed::Saturating;
426    /// let bytes = if cfg!(target_endian = "big") {
427    ///     [0x12, 0x34, 0x56, 0x78]
428    /// } else {
429    ///     [0x78, 0x56, 0x34, 0x12]
430    /// };
431    /// assert_eq!(
432    ///     Saturating::<I16F16>::from_bits(0x1234_5678).to_ne_bytes(),
433    ///     bytes
434    /// );
435    /// ```
436    #[inline]
437    pub fn to_ne_bytes(self) -> F::Bytes {
438        self.0.to_ne_bytes()
439    }
440
441    /// Saturating conversion from another number.
442    ///
443    /// The other number can be:
444    ///
445    ///   * A fixed-point number. Any extra fractional bits are
446    ///     discarded, which rounds towards &minus;∞.
447    ///   * An integer of type [`i8`], [`i16`], [`i32`], [`i64`], [`i128`],
448    ///     [`isize`], [`u8`], [`u16`], [`u32`], [`u64`], [`u128`], or
449    ///     [`usize`].
450    ///   * A floating-point number of type
451    ///     <code>[half]::[f16][half::f16]</code>,
452    ///     <code>[half]::[bf16][half::bf16]</code>, [`f32`], [`f64`] or
453    ///     [`F128`]. For this conversion, the method rounds to the nearest,
454    ///     with ties rounding to even.
455    ///   * Any other number `src` for which [`ToFixed`] is
456    ///     implemented, in which case this method returns
457    ///     <code>[Saturating]\(src.[saturating\_to\_fixed][ToFixed::saturating_to_fixed]\())</code>.
458    ///
459    /// See also
460    /// <code>FixedI32::[saturating\_from\_num][FixedI32::saturating_from_num]</code>
461    /// and
462    /// <code>FixedU32::[saturating\_from\_num][FixedU32::saturating_from_num]</code>.
463    ///
464    /// # Panics
465    ///
466    /// For floating-point numbers, panics if the value is NaN.
467    ///
468    /// # Examples
469    ///
470    /// ```rust
471    /// use fixed::types::{I4F4, I16F16};
472    /// use fixed::Saturating;
473    ///
474    /// let src = I16F16::from_bits(0x1234_5678);
475    /// let dst = Saturating::<I4F4>::from_num(src);
476    /// assert_eq!(dst, Saturating(I4F4::MAX));
477    ///
478    /// let src_int = 0x1234_i32;
479    /// let dst_int = Saturating::<I4F4>::from_num(src_int);
480    /// assert_eq!(dst_int, Saturating(I4F4::MAX));
481    ///
482    /// let src_float = f64::NEG_INFINITY;
483    /// let dst_float = Saturating::<I4F4>::from_num(src_float);
484    /// assert_eq!(dst_float, Saturating(I4F4::MIN));
485    /// ```
486    ///
487    /// [`F128`]: crate::F128
488    #[inline]
489    #[track_caller]
490    pub fn from_num<Src: ToFixed>(src: Src) -> Saturating<F> {
491        Saturating(src.saturating_to_fixed())
492    }
493
494    /// Converts a fixed-point number to another number, saturating the
495    /// value on overflow.
496    ///
497    /// The other number can be:
498    ///
499    ///   * Another fixed-point number. Any extra fractional bits are
500    ///     discarded, which rounds towards &minus;∞.
501    ///   * An integer of type [`i8`], [`i16`], [`i32`], [`i64`], [`i128`],
502    ///     [`isize`], [`u8`], [`u16`], [`u32`], [`u64`], [`u128`], or
503    ///     [`usize`]. Any fractional bits are discarded, which rounds
504    ///     towards &minus;∞.
505    ///   * A floating-point number of type
506    ///     <code>[half]::[f16][half::f16]</code>,
507    ///     <code>[half]::[bf16][half::bf16]</code>, [`f32`], [`f64`] or
508    ///     [`F128`]. For this conversion, the method rounds to the nearest,
509    ///     with ties rounding to even.
510    ///   * Any other type `Dst` for which [`FromFixed`] is
511    ///     implemented, in which case this method returns
512    ///     <code>Dst::[saturating\_from\_fixed][FromFixed::saturating_from_fixed]\(self.0)</code>.
513    ///
514    /// See also <code>FixedI32::[saturating\_to\_num][FixedI32::saturating_to_num]</code> and
515    /// <code>FixedU32::[saturating\_to\_num][FixedU32::saturating_to_num]</code>.
516    ///
517    /// # Examples
518    ///
519    /// ```rust
520    /// use fixed::types::{I16F16, I2F6, I4F4};
521    /// use fixed::Saturating;
522    ///
523    /// // conversion that fits
524    /// let src = Saturating(I4F4::from_num(1.75));
525    /// let expected = I16F16::from_num(1.75);
526    /// assert_eq!(src.to_num::<I16F16>(), expected);
527    ///
528    /// // conversion that saturates
529    /// let src = Saturating(I4F4::MAX);
530    /// assert_eq!(src.to_num::<I2F6>(), I2F6::MAX);
531    /// ```
532    ///
533    /// [`F128`]: crate::F128
534    #[inline]
535    pub fn to_num<Dst: FromFixed>(self) -> Dst {
536        Dst::saturating_from_fixed(self.0)
537    }
538
539    /// Parses a string slice containing binary digits to return a fixed-point number.
540    ///
541    /// Rounding is to the nearest, with ties rounded to even.
542    ///
543    /// See also
544    /// <code>FixedI32::[saturating\_from\_str\_binary][FixedI32::saturating_from_str_binary]</code>
545    /// and
546    /// <code>FixedU32::[saturating\_from\_str\_binary][FixedU32::saturating_from_str_binary]</code>.
547    ///
548    /// # Examples
549    ///
550    /// ```rust
551    /// use fixed::types::I8F8;
552    /// use fixed::Saturating;
553    /// let max = Saturating(I8F8::MAX);
554    /// assert_eq!(Saturating::<I8F8>::from_str_binary("101100111000.1"), Ok(max));
555    /// ```
556    #[inline]
557    pub fn from_str_binary(src: &str) -> Result<Saturating<F>, ParseFixedError> {
558        F::saturating_from_str_binary(src).map(Saturating)
559    }
560
561    /// Parses a string slice containing octal digits to return a fixed-point number.
562    ///
563    /// Rounding is to the nearest, with ties rounded to even.
564    ///
565    /// See also
566    /// <code>FixedI32::[saturating\_from\_str\_octal][FixedI32::saturating_from_str_octal]</code>
567    /// and
568    /// <code>FixedU32::[saturating\_from\_str\_octal][FixedU32::saturating_from_str_octal]</code>.
569    ///
570    /// # Examples
571    ///
572    /// ```rust
573    /// use fixed::types::I8F8;
574    /// use fixed::Saturating;
575    /// let max = Saturating(I8F8::MAX);
576    /// assert_eq!(Saturating::<I8F8>::from_str_octal("7165.4"), Ok(max));
577    /// ```
578    #[inline]
579    pub fn from_str_octal(src: &str) -> Result<Saturating<F>, ParseFixedError> {
580        F::saturating_from_str_octal(src).map(Saturating)
581    }
582
583    /// Parses a string slice containing hexadecimal digits to return a fixed-point number.
584    ///
585    /// Rounding is to the nearest, with ties rounded to even.
586    ///
587    /// See also
588    /// <code>FixedI32::[saturating\_from\_str\_hex][FixedI32::saturating_from_str_hex]</code>
589    /// and
590    /// <code>FixedU32::[saturating\_from\_str\_hex][FixedU32::saturating_from_str_hex]</code>.
591    ///
592    /// # Examples
593    ///
594    /// ```rust
595    /// use fixed::types::I8F8;
596    /// use fixed::Saturating;
597    /// let max = Saturating(I8F8::MAX);
598    /// assert_eq!(Saturating::<I8F8>::from_str_hex("C0F.FE"), Ok(max));
599    /// ```
600    #[inline]
601    pub fn from_str_hex(src: &str) -> Result<Saturating<F>, ParseFixedError> {
602        F::saturating_from_str_hex(src).map(Saturating)
603    }
604
605    /// Parses an ASCII-byte slice containing decimal digits to return a fixed-point number.
606    ///
607    /// Rounding is to the nearest, with ties rounded to even.
608    ///
609    /// See also
610    /// <code>FixedI32::[saturating\_from\_ascii][FixedI32::saturating_from_ascii]</code>
611    /// and
612    /// <code>FixedU32::[saturating\_from\_ascii][FixedU32::saturating_from_ascii]</code>.
613    ///
614    /// # Examples
615    ///
616    /// ```rust
617    /// use fixed::types::I8F8;
618    /// use fixed::Saturating;
619    /// let max = Saturating(I8F8::MAX);
620    /// assert_eq!(Saturating::<I8F8>::from_ascii(b"9999"), Ok(max));
621    /// ```
622    #[inline]
623    pub fn from_ascii(src: &[u8]) -> Result<Saturating<F>, ParseFixedError> {
624        F::saturating_from_ascii(src).map(Saturating)
625    }
626
627    /// Parses an ASCII-byte slice containing binary digits to return a fixed-point number.
628    ///
629    /// Rounding is to the nearest, with ties rounded to even.
630    ///
631    /// See also
632    /// <code>FixedI32::[saturating\_from\_ascii\_binary][FixedI32::saturating_from_ascii_binary]</code>
633    /// and
634    /// <code>FixedU32::[saturating\_from\_ascii\_binary][FixedU32::saturating_from_ascii_binary]</code>.
635    ///
636    /// # Examples
637    ///
638    /// ```rust
639    /// use fixed::types::I8F8;
640    /// use fixed::Saturating;
641    /// let max = Saturating(I8F8::MAX);
642    /// assert_eq!(Saturating::<I8F8>::from_ascii_binary(b"101100111000.1"), Ok(max));
643    /// ```
644    #[inline]
645    pub fn from_ascii_binary(src: &[u8]) -> Result<Saturating<F>, ParseFixedError> {
646        F::saturating_from_ascii_binary(src).map(Saturating)
647    }
648
649    /// Parses an ASCII-byte slice containing octal digits to return a fixed-point number.
650    ///
651    /// Rounding is to the nearest, with ties rounded to even.
652    ///
653    /// See also
654    /// <code>FixedI32::[saturating\_from\_ascii\_octal][FixedI32::saturating_from_ascii_octal]</code>
655    /// and
656    /// <code>FixedU32::[saturating\_from\_ascii\_octal][FixedU32::saturating_from_ascii_octal]</code>.
657    ///
658    /// # Examples
659    ///
660    /// ```rust
661    /// use fixed::types::I8F8;
662    /// use fixed::Saturating;
663    /// let max = Saturating(I8F8::MAX);
664    /// assert_eq!(Saturating::<I8F8>::from_ascii_octal(b"7165.4"), Ok(max));
665    /// ```
666    #[inline]
667    pub fn from_ascii_octal(src: &[u8]) -> Result<Saturating<F>, ParseFixedError> {
668        F::saturating_from_ascii_octal(src).map(Saturating)
669    }
670
671    /// Parses an ASCII-byte slice containing hexadecimal digits to return a fixed-point number.
672    ///
673    /// Rounding is to the nearest, with ties rounded to even.
674    ///
675    /// See also
676    /// <code>FixedI32::[saturating\_from\_ascii\_hex][FixedI32::saturating_from_ascii_hex]</code>
677    /// and
678    /// <code>FixedU32::[saturating\_from\_ascii\_hex][FixedU32::saturating_from_ascii_hex]</code>.
679    ///
680    /// # Examples
681    ///
682    /// ```rust
683    /// use fixed::types::I8F8;
684    /// use fixed::Saturating;
685    /// let max = Saturating(I8F8::MAX);
686    /// assert_eq!(Saturating::<I8F8>::from_ascii_hex(b"C0F.FE"), Ok(max));
687    /// ```
688    #[inline]
689    pub fn from_ascii_hex(src: &[u8]) -> Result<Saturating<F>, ParseFixedError> {
690        F::saturating_from_ascii_hex(src).map(Saturating)
691    }
692
693    /// Returns the integer part.
694    ///
695    /// Note that since the numbers are stored in two’s complement,
696    /// negative numbers with non-zero fractional parts will be
697    /// rounded towards &minus;∞, except in the case where there are no
698    /// integer bits, for example for the type
699    /// <code>[Saturating]&lt;[I0F16]&gt;</code>, where the return value
700    /// is always zero.
701    ///
702    /// See also <code>FixedI32::[int][FixedI32::int]</code> and
703    /// <code>FixedU32::[int][FixedU32::int]</code>.
704    ///
705    /// # Examples
706    ///
707    /// ```rust
708    /// use fixed::types::I16F16;
709    /// use fixed::Saturating;
710    /// assert_eq!(Saturating(I16F16::from_num(12.25)).int(), Saturating(I16F16::from_num(12)));
711    /// assert_eq!(Saturating(I16F16::from_num(-12.25)).int(), Saturating(I16F16::from_num(-13)));
712    /// ```
713    ///
714    /// [I0F16]: crate::types::I0F16
715    #[inline]
716    #[must_use]
717    pub fn int(self) -> Saturating<F> {
718        Saturating(self.0.int())
719    }
720
721    /// Returns the fractional part.
722    ///
723    /// Note that since the numbers are stored in two’s complement,
724    /// the returned fraction will be non-negative for negative
725    /// numbers, except in the case where there are no integer bits,
726    /// for example for the type
727    /// <code>[Saturating]&lt;[I0F16]&gt;</code>,
728    /// where the return value is always equal to `self`.
729    ///
730    /// See also <code>FixedI32::[frac][FixedI32::frac]</code> and
731    /// <code>FixedU32::[frac][FixedU32::frac]</code>.
732    ///
733    /// # Examples
734    ///
735    /// ```rust
736    /// use fixed::types::I16F16;
737    /// use fixed::Saturating;
738    /// assert_eq!(Saturating(I16F16::from_num(12.25)).frac(), Saturating(I16F16::from_num(0.25)));
739    /// assert_eq!(Saturating(I16F16::from_num(-12.25)).frac(), Saturating(I16F16::from_num(0.75)));
740    /// ```
741    ///
742    /// [I0F16]: crate::types::I0F16
743    #[inline]
744    #[must_use]
745    pub fn frac(self) -> Saturating<F> {
746        Saturating(self.0.frac())
747    }
748
749    /// Rounds to the next integer towards 0.
750    ///
751    /// See also
752    /// <code>FixedI32::[round\_to\_zero][FixedI32::round_to_zero]</code> and
753    /// <code>FixedU32::[round\_to\_zero][FixedU32::round_to_zero]</code>.
754    ///
755    /// # Examples
756    ///
757    /// ```rust
758    /// use fixed::types::I16F16;
759    /// use fixed::Saturating;
760    /// let three = Saturating(I16F16::from_num(3));
761    /// assert_eq!(Saturating(I16F16::from_num(3.9)).round_to_zero(), three);
762    /// assert_eq!(Saturating(I16F16::from_num(-3.9)).round_to_zero(), -three);
763    /// ```
764    #[inline]
765    #[must_use]
766    pub fn round_to_zero(self) -> Saturating<F> {
767        Saturating(self.0.round_to_zero())
768    }
769
770    /// Saturating ceil. Rounds to the next integer towards +∞, saturating
771    /// on overflow.
772    ///
773    /// See also
774    /// <code>FixedI32::[saturating\_ceil][FixedI32::saturating_ceil]</code> and
775    /// <code>FixedU32::[saturating\_ceil][FixedU32::saturating_ceil]</code>.
776    ///
777    /// # Examples
778    ///
779    /// ```rust
780    /// use fixed::types::I16F16;
781    /// use fixed::Saturating;
782    /// let two_half = Saturating(I16F16::from_num(5) / 2);
783    /// assert_eq!(two_half.ceil(), Saturating(I16F16::from_num(3)));
784    /// assert_eq!(Saturating(I16F16::MAX).ceil(), Saturating(I16F16::MAX));
785    /// ```
786    #[inline]
787    #[must_use]
788    pub fn ceil(self) -> Saturating<F> {
789        Saturating(self.0.saturating_ceil())
790    }
791
792    /// Saturating floor. Rounds to the next integer towards &minus;∞,
793    /// saturating on overflow.
794    ///
795    /// Overflow can only occur for signed numbers with zero integer
796    /// bits.
797    ///
798    /// See also
799    /// <code>FixedI32::[saturating\_floor][FixedI32::saturating_floor]</code> and
800    /// <code>FixedU32::[saturating\_floor][FixedU32::saturating_floor]</code>.
801    ///
802    /// # Examples
803    ///
804    /// ```rust
805    /// use fixed::types::{I0F32, I16F16};
806    /// use fixed::Saturating;
807    /// let two_half = Saturating(I16F16::from_num(5) / 2);
808    /// assert_eq!(two_half.floor(), Saturating(I16F16::from_num(2)));
809    /// assert_eq!(Saturating(I0F32::MIN).floor(), Saturating(I0F32::MIN));
810    /// ```
811    #[inline]
812    #[must_use]
813    pub fn floor(self) -> Saturating<F> {
814        Saturating(self.0.saturating_floor())
815    }
816
817    /// Saturating round. Rounds to the next integer to the nearest,
818    /// with ties rounded away from zero, and saturating on overflow.
819    ///
820    /// See also
821    /// <code>FixedI32::[saturating\_round][FixedI32::saturating_round]</code> and
822    /// <code>FixedU32::[saturating\_round][FixedU32::saturating_round]</code>.
823    ///
824    /// # Examples
825    ///
826    /// ```rust
827    /// use fixed::types::I16F16;
828    /// use fixed::Saturating;
829    /// let two_half = Saturating(I16F16::from_num(5) / 2);
830    /// assert_eq!(two_half.round(), Saturating(I16F16::from_num(3)));
831    /// assert_eq!((-two_half).round(), Saturating(I16F16::from_num(-3)));
832    /// let max = Saturating(I16F16::MAX);
833    /// assert_eq!(max.round(), max);
834    /// ```
835    #[inline]
836    #[must_use]
837    pub fn round(self) -> Saturating<F> {
838        Saturating(self.0.saturating_round())
839    }
840
841    /// Saturating round. Rounds to the next integer to the nearest, with ties
842    /// rounded to even, and saturating on overflow.
843    ///
844    /// See also
845    /// <code>FixedI32::[saturating\_round\_ties\_even][FixedI32::saturating_round_ties_even]</code>
846    /// and
847    /// <code>FixedU32::[saturating\_round\_ties\_even][FixedU32::saturating_round_ties_even]</code>.
848    ///
849    /// # Examples
850    ///
851    /// ```rust
852    /// use fixed::types::I16F16;
853    /// use fixed::Saturating;
854    /// let two_half = Saturating(I16F16::from_num(2.5));
855    /// assert_eq!(two_half.round_ties_even(), Saturating(I16F16::from_num(2)));
856    /// let three_half = Saturating(I16F16::from_num(3.5));
857    /// assert_eq!(three_half.round_ties_even(), Saturating(I16F16::from_num(4)));
858    /// let max = Saturating(I16F16::MAX);
859    /// assert_eq!(max.round_ties_even(), max);
860    /// ```
861    #[inline]
862    #[must_use]
863    pub fn round_ties_even(self) -> Saturating<F> {
864        Saturating(self.0.saturating_round_ties_even())
865    }
866
867    /// Returns the number of ones in the binary representation.
868    ///
869    /// See also <code>FixedI32::[count\_ones][FixedI32::count_ones]</code> and
870    /// <code>FixedU32::[count\_ones][FixedU32::count_ones]</code>.
871    ///
872    /// # Examples
873    ///
874    /// ```rust
875    /// use fixed::types::I16F16;
876    /// use fixed::Saturating;
877    /// let w = Saturating(I16F16::from_bits(0x00FF_FF00));
878    /// assert_eq!(w.count_ones(), w.0.count_ones());
879    /// ```
880    #[inline]
881    #[doc(alias("popcount", "popcnt"))]
882    pub fn count_ones(self) -> u32 {
883        self.0.count_ones()
884    }
885
886    /// Returns the number of zeros in the binary representation.
887    ///
888    /// See also <code>FixedI32::[count\_zeros][FixedI32::count_zeros]</code>
889    /// and <code>FixedU32::[count\_zeros][FixedU32::count_zeros]</code>.
890    ///
891    /// # Examples
892    ///
893    /// ```rust
894    /// use fixed::types::I16F16;
895    /// use fixed::Saturating;
896    /// let w = Saturating(I16F16::from_bits(0x00FF_FF00));
897    /// assert_eq!(w.count_zeros(), w.0.count_zeros());
898    /// ```
899    #[inline]
900    pub fn count_zeros(self) -> u32 {
901        self.0.count_zeros()
902    }
903
904    /// Returns the number of leading ones in the binary representation.
905    ///
906    /// See also <code>FixedI32::[leading\_ones][FixedI32::leading_ones]</code>
907    /// and <code>FixedU32::[leading\_ones][FixedU32::leading_ones]</code>.
908    ///
909    /// # Examples
910    ///
911    /// ```rust
912    /// use fixed::types::U16F16;
913    /// use fixed::Saturating;
914    /// let w = Saturating(U16F16::from_bits(0xFF00_00FF));
915    /// assert_eq!(w.leading_ones(), w.0.leading_ones());
916    /// ```
917    #[inline]
918    pub fn leading_ones(self) -> u32 {
919        self.0.leading_ones()
920    }
921
922    /// Returns the number of leading zeros in the binary representation.
923    ///
924    /// See also
925    /// <code>FixedI32::[leading\_zeros][FixedI32::leading_zeros]</code> and
926    /// <code>FixedU32::[leading\_zeros][FixedU32::leading_zeros]</code>.
927    ///
928    /// # Examples
929    ///
930    /// ```rust
931    /// use fixed::types::I16F16;
932    /// use fixed::Saturating;
933    /// let w = Saturating(I16F16::from_bits(0x00FF_FF00));
934    /// assert_eq!(w.leading_zeros(), w.0.leading_zeros());
935    /// ```
936    #[inline]
937    pub fn leading_zeros(self) -> u32 {
938        self.0.leading_zeros()
939    }
940
941    /// Returns the number of trailing ones in the binary representation.
942    ///
943    /// See also
944    /// <code>FixedI32::[trailing\_ones][FixedI32::trailing_ones]</code> and
945    /// <code>FixedU32::[trailing\_ones][FixedU32::trailing_ones]</code>.
946    ///
947    /// # Examples
948    ///
949    /// ```rust
950    /// use fixed::types::U16F16;
951    /// use fixed::Saturating;
952    /// let w = Saturating(U16F16::from_bits(0xFF00_00FF));
953    /// assert_eq!(w.trailing_ones(), w.0.trailing_ones());
954    /// ```
955    #[inline]
956    pub fn trailing_ones(self) -> u32 {
957        self.0.trailing_ones()
958    }
959
960    /// Returns the number of trailing zeros in the binary representation.
961    ///
962    /// See also
963    /// <code>FixedI32::[trailing\_zeros][FixedI32::trailing_zeros]</code> and
964    /// <code>FixedU32::[trailing\_zeros][FixedU32::trailing_zeros]</code>.
965    ///
966    /// # Examples
967    ///
968    /// ```rust
969    /// use fixed::types::I16F16;
970    /// use fixed::Saturating;
971    /// let w = Saturating(I16F16::from_bits(0x00FF_FF00));
972    /// assert_eq!(w.trailing_zeros(), w.0.trailing_zeros());
973    /// ```
974    #[inline]
975    pub fn trailing_zeros(self) -> u32 {
976        self.0.trailing_zeros()
977    }
978
979    /// Returns the square root.
980    ///
981    /// See also
982    /// <code>FixedI32::[saturating\_sqrt][FixedI32::saturating_sqrt]</code> and
983    /// <code>FixedU32::[saturating\_sqrt][FixedU32::saturating_sqrt]</code>.
984    ///
985    /// # Panics
986    ///
987    /// Panics if the number is negative.
988    ///
989    /// # Examples
990    ///
991    /// ```rust
992    /// use fixed::types::I0F32;
993    /// use fixed::Saturating;
994    /// assert_eq!(Saturating(I0F32::lit("0b0.0001")).sqrt().0, I0F32::lit("0b0.01"));
995    ///
996    /// // This method handles the overflow corner case.
997    /// let s = Saturating(I0F32::from_num(0.25));
998    /// assert_eq!(s.sqrt().0, I0F32::MAX);
999    /// ```
1000    #[inline]
1001    #[track_caller]
1002    pub fn sqrt(self) -> Self {
1003        Saturating(self.0.saturating_sqrt())
1004    }
1005
1006    /// Integer base-2 logarithm, rounded down.
1007    ///
1008    /// See also <code>FixedI32::[int\_log2][FixedI32::int_log2]</code> and
1009    /// <code>FixedU32::[int\_log2][FixedU32::int_log2]</code>.
1010    ///
1011    /// # Panics
1012    ///
1013    /// Panics if the fixed-point number is ≤&nbsp;0.
1014    #[inline]
1015    #[track_caller]
1016    #[doc(alias("ilog2"))]
1017    pub fn int_log2(self) -> i32 {
1018        self.0.int_log2()
1019    }
1020
1021    /// Integer base-10 logarithm, rounded down.
1022    ///
1023    /// See also <code>FixedI32::[int\_log10][FixedI32::int_log10]</code> and
1024    /// <code>FixedU32::[int\_log10][FixedU32::int_log10]</code>.
1025    ///
1026    /// # Panics
1027    ///
1028    /// Panics if the fixed-point number is ≤&nbsp;0.
1029    #[inline]
1030    #[track_caller]
1031    #[doc(alias("ilog10"))]
1032    pub fn int_log10(self) -> i32 {
1033        self.0.int_log10()
1034    }
1035
1036    /// Integer logarithm to the specified base, rounded down.
1037    ///
1038    /// See also <code>FixedI32::[int\_log][FixedI32::int_log]</code> and
1039    /// <code>FixedU32::[int\_log][FixedU32::int_log]</code>.
1040    ///
1041    /// # Panics
1042    ///
1043    /// Panics if the fixed-point number is ≤&nbsp;0 or if the base is <&nbsp;2.
1044    #[inline]
1045    #[track_caller]
1046    #[doc(alias("ilog"))]
1047    pub fn int_log(self, base: u32) -> i32 {
1048        self.0.int_log(base)
1049    }
1050
1051    /// Reverses the order of the bits of the fixed-point number.
1052    ///
1053    /// See also <code>FixedI32::[reverse\_bits][FixedI32::reverse_bits]</code>
1054    /// and <code>FixedU32::[reverse\_bits][FixedU32::reverse_bits]</code>.
1055    ///
1056    /// # Examples
1057    ///
1058    /// ```rust
1059    /// use fixed::types::I16F16;
1060    /// use fixed::Saturating;
1061    /// let i = I16F16::from_bits(0x1234_5678);
1062    /// assert_eq!(Saturating(i).reverse_bits(), Saturating(i.reverse_bits()));
1063    /// ```
1064    #[inline]
1065    #[must_use = "this returns the result of the operation, without modifying the original"]
1066    pub fn reverse_bits(self) -> Saturating<F> {
1067        Saturating(self.0.reverse_bits())
1068    }
1069
1070    /// Shifts to the left by `n` bits, saturating the truncated bits to the right end.
1071    ///
1072    /// See also <code>FixedI32::[rotate\_left][FixedI32::rotate_left]</code>
1073    /// and <code>FixedU32::[rotate\_left][FixedU32::rotate_left]</code>.
1074    ///
1075    /// # Examples
1076    ///
1077    /// ```rust
1078    /// use fixed::types::I16F16;
1079    /// use fixed::Saturating;
1080    /// let i = I16F16::from_bits(0x00FF_FF00);
1081    /// assert_eq!(Saturating(i).rotate_left(12), Saturating(i.rotate_left(12)));
1082    /// ```
1083    #[inline]
1084    #[must_use = "this returns the result of the operation, without modifying the original"]
1085    pub fn rotate_left(self, n: u32) -> Saturating<F> {
1086        Saturating(self.0.rotate_left(n))
1087    }
1088
1089    /// Shifts to the right by `n` bits, saturating the truncated bits to the left end.
1090    ///
1091    /// See also <code>FixedI32::[rotate\_right][FixedI32::rotate_right]</code>
1092    /// and <code>FixedU32::[rotate\_right][FixedU32::rotate_right]</code>.
1093    ///
1094    /// # Examples
1095    ///
1096    /// ```rust
1097    /// use fixed::types::I16F16;
1098    /// use fixed::Saturating;
1099    /// let i = I16F16::from_bits(0x00FF_FF00);
1100    /// assert_eq!(Saturating(i).rotate_right(12), Saturating(i.rotate_right(12)));
1101    /// ```
1102    #[inline]
1103    #[must_use = "this returns the result of the operation, without modifying the original"]
1104    pub fn rotate_right(self, n: u32) -> Saturating<F> {
1105        Saturating(self.0.rotate_right(n))
1106    }
1107
1108    /// Returns [`true`] if the number is zero.
1109    ///
1110    /// See also <code>FixedI32::[is\_zero][FixedI32::is_zero]</code> and
1111    /// <code>FixedU32::[is\_zero][FixedU32::is_zero]</code>.
1112    ///
1113    /// # Examples
1114    ///
1115    /// ```rust
1116    /// use fixed::types::I16F16;
1117    /// use fixed::Saturating;
1118    /// assert!(Saturating(I16F16::ZERO).is_zero());
1119    /// assert!(!Saturating(I16F16::from_num(4.3)).is_zero());
1120    /// ```
1121    #[inline]
1122    pub fn is_zero(self) -> bool {
1123        self.0.is_zero()
1124    }
1125
1126    /// Returns the distance from `self` to `other`.
1127    ///
1128    /// See also
1129    /// <code>FixedI32::[saturating\_dist][FixedI32::saturating_dist]</code> and
1130    /// <code>FixedU32::[saturating\_dist][FixedU32::saturating_dist]</code>.
1131    ///
1132    /// # Examples
1133    ///
1134    /// ```rust
1135    /// use fixed::types::I16F16;
1136    /// use fixed::Saturating;
1137    /// type Wr = Saturating<I16F16>;
1138    /// assert_eq!(Wr::from_num(-1).dist(Wr::from_num(4)), Wr::from_num(5));
1139    /// assert_eq!(Wr::MIN.dist(Wr::MAX), Wr::MAX);
1140    /// ```
1141    #[inline]
1142    #[must_use = "this returns the result of the operation, without modifying the original"]
1143    pub fn dist(self, other: Saturating<F>) -> Saturating<F> {
1144        Saturating(self.0.saturating_dist(other.0))
1145    }
1146
1147    /// Returns the mean of `self` and `other`.
1148    ///
1149    /// See also <code>FixedI32::[mean][FixedI32::mean]</code> and
1150    /// <code>FixedU32::[mean][FixedU32::mean]</code>.
1151    ///
1152    /// # Examples
1153    ///
1154    /// ```rust
1155    /// use fixed::types::I16F16;
1156    /// use fixed::Saturating;
1157    /// let three = Saturating(I16F16::from_num(3));
1158    /// let four = Saturating(I16F16::from_num(4));
1159    /// assert_eq!(three.mean(four), Saturating(I16F16::from_num(3.5)));
1160    /// assert_eq!(three.mean(-four), Saturating(I16F16::from_num(-0.5)));
1161    /// ```
1162    #[inline]
1163    #[must_use = "this returns the result of the operation, without modifying the original"]
1164    pub fn mean(self, other: Saturating<F>) -> Saturating<F> {
1165        Saturating(self.0.mean(other.0))
1166    }
1167
1168    /// Compute the hypotenuse of a right triange.
1169    ///
1170    /// See also
1171    /// <code>FixedI32::[saturating\_hypot][FixedI32::saturating_hypot]</code> and
1172    /// <code>FixedU32::[saturating\_hypot][FixedU32::saturating_hypot]</code>.
1173    ///
1174    /// # Examples
1175    ///
1176    /// ```rust
1177    /// use fixed::types::I8F8;
1178    /// use fixed::Saturating;
1179    /// type Sa = Saturating<I8F8>;
1180    /// // hypot(3, 4) == 5
1181    /// assert_eq!(Sa::from_num(3).hypot(Sa::from_num(4)), Sa::from_num(5));
1182    /// // hypot(88, 105) == 137, which saturates
1183    /// assert_eq!(Sa::from_num(88).hypot(Sa::from_num(105)), Sa::MAX);
1184    /// ```
1185    #[inline]
1186    #[must_use = "this returns the result of the operation, without modifying the original"]
1187    pub fn hypot(self, other: Saturating<F>) -> Saturating<F> {
1188        Saturating(self.0.saturating_hypot(other.0))
1189    }
1190
1191    /// Returns the reciprocal (inverse), 1/`self`.
1192    ///
1193    /// See also
1194    /// <code>FixedI32::[saturating\_recip][FixedI32::saturating_recip]</code> and
1195    /// <code>FixedU32::[saturating\_recip][FixedU32::saturating_recip]</code>.
1196    ///
1197    /// # Panics
1198    ///
1199    /// Panics if `self` is zero.
1200    ///
1201    /// # Examples
1202    ///
1203    /// ```rust
1204    /// use fixed::types::I8F24;
1205    /// use fixed::Saturating;
1206    /// let quarter = Saturating(I8F24::from_num(0.25));
1207    /// let frac_1_512 = Saturating(I8F24::ONE / 512);
1208    /// assert_eq!(quarter.recip(), Saturating(I8F24::from_num(4)));
1209    /// assert_eq!(frac_1_512.recip(), Saturating(I8F24::MAX));
1210    /// ```
1211    #[inline]
1212    #[track_caller]
1213    #[must_use]
1214    pub fn recip(self) -> Saturating<F> {
1215        Saturating(self.0.saturating_recip())
1216    }
1217
1218    /// Returns the next multiple of `other`.
1219    ///
1220    /// See also
1221    /// <code>FixedI32::[saturating\_next\_multiple\_of][FixedI32::saturating_next_multiple_of]</code>
1222    /// and
1223    /// <code>FixedU32::[saturating\_next\_multiple\_of][FixedU32::saturating_next_multiple_of]</code>.
1224    ///
1225    /// # Panics
1226    ///
1227    /// Panics if `other` is zero.
1228    ///
1229    /// # Examples
1230    ///
1231    /// ```rust
1232    /// use fixed::types::I16F16;
1233    /// use fixed::Saturating;
1234    /// let one_point_5 = Saturating::<I16F16>::from_num(1.5);
1235    /// let four = Saturating::<I16F16>::from_num(4);
1236    /// let four_point_5 = Saturating::<I16F16>::from_num(4.5);
1237    /// assert_eq!(four.next_multiple_of(one_point_5), four_point_5);
1238    ///
1239    /// let max = Saturating::<I16F16>::MAX;
1240    /// let max_minus_delta = max - Saturating::<I16F16>::DELTA;
1241    /// assert_eq!(max.next_multiple_of(max_minus_delta), max_minus_delta * 2);
1242    /// ```
1243    #[inline]
1244    #[track_caller]
1245    #[must_use]
1246    pub fn next_multiple_of(self, other: Saturating<F>) -> Saturating<F> {
1247        Saturating(self.0.saturating_next_multiple_of(other.0))
1248    }
1249
1250    /// Multiply and add. Returns `self` × `mul` + `add`.
1251    ///
1252    /// See also
1253    /// <code>FixedI32::[saturating\_mul\_add][FixedI32::saturating_mul_add]</code>
1254    /// and
1255    /// <code>FixedU32::[saturating\_mul\_add][FixedU32::saturating_mul_add]</code>.
1256    ///
1257    /// # Examples
1258    ///
1259    /// ```rust
1260    /// use fixed::types::I16F16;
1261    /// use fixed::Saturating;
1262    /// let half = Saturating(I16F16::from_num(0.5));
1263    /// let three = Saturating(I16F16::from_num(3));
1264    /// let four = Saturating(I16F16::from_num(4));
1265    /// let max = Saturating(I16F16::MAX);
1266    /// assert_eq!(three.mul_add(half, four), Saturating(I16F16::from_num(5.5)));
1267    /// assert_eq!(max.mul_add(three, max), max * 4);
1268    /// ```
1269    #[inline]
1270    #[must_use = "this returns the result of the operation, without modifying the original"]
1271    pub fn mul_add(self, mul: Saturating<F>, add: Saturating<F>) -> Saturating<F> {
1272        Saturating(self.0.saturating_mul_add(mul.0, add.0))
1273    }
1274
1275    /// Adds `self` to the product `a`&nbsp;×&nbsp;`b`.
1276    ///
1277    /// See also
1278    /// <code>FixedI32::[saturating\_add\_prod][FixedI32::saturating_add_prod]</code>
1279    /// and
1280    /// <code>FixedU32::[saturating\_add\_prod][FixedU32::saturating_add_prod]</code>.
1281    ///
1282    /// # Examples
1283    ///
1284    /// ```rust
1285    /// use fixed::types::I16F16;
1286    /// use fixed::Saturating;
1287    /// let half = Saturating(I16F16::from_num(0.5));
1288    /// let three = Saturating(I16F16::from_num(3));
1289    /// let four = Saturating(I16F16::from_num(4));
1290    /// let max = Saturating(I16F16::MAX);
1291    /// assert_eq!(four.add_prod(three, half), Saturating(I16F16::from_num(5.5)));
1292    /// assert_eq!(max.add_prod(max, three), max * 4);
1293    /// ```
1294    #[inline]
1295    #[must_use]
1296    pub fn add_prod(self, a: Saturating<F>, b: Saturating<F>) -> Saturating<F> {
1297        Saturating(self.0.saturating_add_prod(a.0, b.0))
1298    }
1299
1300    /// Multiply and accumulate. Adds (`a` × `b`) to `self`.
1301    ///
1302    /// See also
1303    /// <code>FixedI32::[saturating\_mul\_acc][FixedI32::saturating_mul_acc]</code>
1304    /// and
1305    /// <code>FixedU32::[saturating\_mul\_acc][FixedU32::saturating_mul_acc]</code>.
1306    ///
1307    /// # Examples
1308    ///
1309    /// ```rust
1310    /// use fixed::types::I16F16;
1311    /// use fixed::Saturating;
1312    /// let mut acc = Saturating(I16F16::from_num(3));
1313    /// acc.mul_acc(Saturating(I16F16::from_num(4)), Saturating(I16F16::from_num(0.5)));
1314    /// assert_eq!(acc, Saturating(I16F16::from_num(5)));
1315    ///
1316    /// acc = Saturating(I16F16::MAX);
1317    /// acc.mul_acc(Saturating(I16F16::MAX), Saturating(I16F16::from_num(3)));
1318    /// assert_eq!(acc, Saturating(I16F16::MAX) * 4);
1319    /// ```
1320    #[inline]
1321    pub fn mul_acc(&mut self, a: Saturating<F>, b: Saturating<F>) {
1322        self.0.saturating_mul_acc(a.0, b.0);
1323    }
1324
1325    /// Euclidean division.
1326    ///
1327    /// See also
1328    /// <code>FixedI32::[saturating\_div\_euclid][FixedI32::saturating_div_euclid]</code>
1329    /// and
1330    /// <code>FixedU32::[saturating\_div\_euclid][FixedU32::saturating_div_euclid]</code>.
1331    ///
1332    /// # Panics
1333    ///
1334    /// Panics if the divisor is zero.
1335    ///
1336    /// # Examples
1337    ///
1338    /// ```rust
1339    /// use fixed::types::I16F16;
1340    /// use fixed::Saturating;
1341    /// let num = Saturating(I16F16::from_num(7.5));
1342    /// let den = Saturating(I16F16::from_num(2));
1343    /// assert_eq!(num.div_euclid(den), Saturating(I16F16::from_num(3)));
1344    /// let quarter = Saturating(I16F16::from_num(0.25));
1345    /// let max = Saturating(I16F16::MAX);
1346    /// assert_eq!(max.div_euclid(quarter), max);
1347    /// ```
1348    #[inline]
1349    #[track_caller]
1350    #[must_use = "this returns the result of the operation, without modifying the original"]
1351    pub fn div_euclid(self, divisor: Saturating<F>) -> Saturating<F> {
1352        Saturating(self.0.saturating_div_euclid(divisor.0))
1353    }
1354
1355    /// Remainder for Euclidean division.
1356    ///
1357    /// See also <code>FixedI32::[rem\_euclid][FixedI32::rem_euclid]</code> and
1358    /// <code>FixedU32::[rem\_euclid][FixedU32::rem_euclid]</code>.
1359    ///
1360    /// # Panics
1361    ///
1362    /// Panics if the divisor is zero.
1363    ///
1364    /// # Examples
1365    ///
1366    /// ```rust
1367    /// use fixed::types::I16F16;
1368    /// use fixed::Saturating;
1369    /// let num = Saturating(I16F16::from_num(7.5));
1370    /// let den = Saturating(I16F16::from_num(2));
1371    /// assert_eq!(num.rem_euclid(den), Saturating(I16F16::from_num(1.5)));
1372    /// assert_eq!((-num).rem_euclid(den), Saturating(I16F16::from_num(0.5)));
1373    /// ```
1374    #[inline]
1375    #[track_caller]
1376    #[must_use = "this returns the result of the operation, without modifying the original"]
1377    pub fn rem_euclid(self, divisor: Saturating<F>) -> Saturating<F> {
1378        Saturating(self.0.rem_euclid(divisor.0))
1379    }
1380
1381    /// Euclidean division by an integer.
1382    ///
1383    /// See also
1384    /// <code>FixedI32::[saturating\_div\_euclid\_int][FixedI32::saturating_div_euclid_int]</code>
1385    /// and
1386    /// <code>FixedU32::[saturating\_div\_euclid\_int][FixedU32::saturating_div_euclid_int]</code>.
1387    ///
1388    /// # Panics
1389    ///
1390    /// Panics if the divisor is zero.
1391    ///
1392    /// # Examples
1393    ///
1394    /// ```rust
1395    /// use fixed::types::I16F16;
1396    /// use fixed::Saturating;
1397    /// let num = Saturating(I16F16::from_num(7.5));
1398    /// assert_eq!(num.div_euclid_int(2), Saturating(I16F16::from_num(3)));
1399    /// let min = Saturating(I16F16::MIN);
1400    /// let max = Saturating(I16F16::MAX);
1401    /// assert_eq!(min.div_euclid_int(-1), max);
1402    /// ```
1403    #[inline]
1404    #[track_caller]
1405    #[must_use = "this returns the result of the operation, without modifying the original"]
1406    pub fn div_euclid_int(self, divisor: F::Bits) -> Saturating<F> {
1407        Saturating(self.0.saturating_div_euclid_int(divisor))
1408    }
1409
1410    /// Remainder for Euclidean division.
1411    ///
1412    /// See also
1413    /// <code>FixedI32::[saturating\_rem\_euclid\_int][FixedI32::saturating_rem_euclid_int]</code>
1414    /// and
1415    /// <code>FixedU32::[saturating\_rem\_euclid\_int][FixedU32::saturating_rem_euclid_int]</code>.
1416    ///
1417    /// # Panics
1418    ///
1419    /// Panics if the divisor is zero.
1420    ///
1421    /// # Examples
1422    ///
1423    /// ```rust
1424    /// use fixed::types::I16F16;
1425    /// use fixed::Saturating;
1426    /// let num = Saturating(I16F16::from_num(7.5));
1427    /// assert_eq!(num.rem_euclid_int(2), Saturating(I16F16::from_num(1.5)));
1428    /// assert_eq!((-num).rem_euclid_int(2), Saturating(I16F16::from_num(0.5)));
1429    /// ```
1430    #[inline]
1431    #[track_caller]
1432    #[must_use = "this returns the result of the operation, without modifying the original"]
1433    pub fn rem_euclid_int(self, divisor: F::Bits) -> Saturating<F> {
1434        Saturating(self.0.saturating_rem_euclid_int(divisor))
1435    }
1436
1437    /// Unbounded shift left. Computes `self << rhs`, without bounding the value
1438    /// of `rhs`.
1439    ///
1440    /// See also
1441    /// <code>FixedI32::[unbounded\_shl][FixedI32::unbounded_shl]</code> and
1442    /// <code>FixedU32::[unbounded\_shl][FixedU32::unbounded_shl]</code>.
1443    ///
1444    /// # Examples
1445    ///
1446    /// ```rust
1447    /// use fixed::types::I16F16;
1448    /// use fixed::Saturating;
1449    /// type Sa = Saturating<I16F16>;
1450    /// let num = Sa::from_num(1.5);
1451    /// assert_eq!(num.unbounded_shl(5), Saturating(num.0 << 5));
1452    /// assert_eq!(num.unbounded_shl(32), Sa::ZERO);
1453    /// ```
1454    #[must_use = "this returns the result of the operation, without modifying the original"]
1455    #[inline]
1456    pub fn unbounded_shl(self, rhs: u32) -> Saturating<F> {
1457        Saturating(self.0.unbounded_shl(rhs))
1458    }
1459
1460    /// Unbounded shift right. Computes `self >> rhs`, without bounding the
1461    /// value of `rhs`.
1462    ///
1463    /// See also
1464    /// <code>FixedI32::[unbounded\_shr][FixedI32::unbounded_shr]</code> and
1465    /// <code>FixedU32::[unbounded\_shr][FixedU32::unbounded_shr]</code>.
1466    ///
1467    /// # Examples
1468    ///
1469    /// ```rust
1470    /// use fixed::types::I16F16;
1471    /// use fixed::Saturating;
1472    /// type Sa = Saturating<I16F16>;
1473    /// let num = Sa::from_num(1.5);
1474    /// assert_eq!(num.unbounded_shr(5), Saturating(num.0 >> 5));
1475    /// assert_eq!(num.unbounded_shr(32), Sa::ZERO);
1476    /// assert_eq!((-num).unbounded_shr(5), Saturating((-num.0) >> 5));
1477    /// assert_eq!((-num).unbounded_shr(32), -Sa::DELTA);
1478    /// ```
1479    #[must_use = "this returns the result of the operation, without modifying the original"]
1480    #[inline]
1481    pub fn unbounded_shr(self, rhs: u32) -> Saturating<F> {
1482        Saturating(self.0.unbounded_shr(rhs))
1483    }
1484
1485    /// Linear interpolation between `start` and `end`.
1486    ///
1487    /// See also
1488    /// <code>FixedI32::[saturating\_lerp][FixedI32::saturating_lerp]</code> and
1489    /// <code>FixedU32::[saturating\_lerp][FixedU32::saturating_lerp]</code>.
1490    ///
1491    /// # Examples
1492    ///
1493    /// ```rust
1494    /// use fixed::types::I16F16;
1495    /// use fixed::Saturating;
1496    /// type Sa = Saturating<I16F16>;
1497    /// assert_eq!(Sa::from_num(0.5).lerp(Sa::ZERO, Sa::MAX), Sa::MAX / 2);
1498    /// assert_eq!(Sa::from_num(1.5).lerp(Sa::ZERO, Sa::MAX), Sa::MAX + Sa::MAX / 2);
1499    /// ```
1500    #[inline]
1501    #[must_use]
1502    pub fn lerp(self, start: Saturating<F>, end: Saturating<F>) -> Saturating<F> {
1503        Saturating(self.0.saturating_lerp(start.0, end.0))
1504    }
1505
1506    /// Inverse linear interpolation between `start` and `end`.
1507    ///
1508    /// See also
1509    /// <code>FixedI32::[saturating\_inv\_lerp][FixedI32::saturating_inv_lerp]</code> and
1510    /// <code>FixedU32::[saturating\_inv\_lerp][FixedU32::saturating_inv_lerp]</code>.
1511    ///
1512    /// # Examples
1513    ///
1514    /// ```rust
1515    /// use fixed::types::I16F16;
1516    /// use fixed::Saturating;
1517    /// type Sa = Saturating<I16F16>;
1518    /// assert_eq!(
1519    ///     Sa::from_num(25).inv_lerp(Sa::from_num(20), Sa::from_num(40)),
1520    ///     Sa::from_num(0.25)
1521    /// );
1522    /// ```
1523    #[inline]
1524    #[must_use]
1525    pub fn inv_lerp(self, start: Saturating<F>, end: Saturating<F>) -> Saturating<F> {
1526        Saturating(self.0.saturating_inv_lerp(start.0, end.0))
1527    }
1528
1529    /// Saturating round. Rounds to the next integer to the nearest, with ties
1530    /// rounded to even, and saturating on overflow.
1531    #[inline]
1532    #[must_use]
1533    #[deprecated(since = "1.28.0", note = "renamed to `round_ties_even`")]
1534    pub fn round_ties_to_even(self) -> Saturating<F> {
1535        self.round_ties_even()
1536    }
1537}
1538
1539impl<F: FixedSigned> Saturating<F> {
1540    /// Returns the bit pattern of `self` reinterpreted as an unsigned
1541    /// fixed-point number of the same size.
1542    ///
1543    /// See also <code>FixedI32::[cast\_unsigned][FixedU32::cast_unsigned]</code>.
1544    ///
1545    /// # Examples
1546    ///
1547    /// ```rust
1548    /// use fixed::types::{I16F16, U16F16};
1549    /// use fixed::Saturating;
1550    ///
1551    /// let n = Saturating(-I16F16::DELTA);
1552    /// assert_eq!(n.cast_unsigned(), Saturating(U16F16::MAX));
1553    /// ```
1554    #[must_use]
1555    #[inline]
1556    pub fn cast_unsigned(self) -> Saturating<F::Unsigned> {
1557        Saturating(self.0.cast_unsigned())
1558    }
1559
1560    /// Returns the number of bits required to represent the value.
1561    ///
1562    /// The number of bits required includes an initial one for
1563    /// negative numbers, and an initial zero for non-negative
1564    /// numbers.
1565    ///
1566    /// See also <code>FixedI32::[signed\_bits][FixedI32::signed_bits]</code>.
1567    ///
1568    /// # Examples
1569    ///
1570    /// ```rust
1571    /// use fixed::types::I4F4;
1572    /// use fixed::Saturating;
1573    /// assert_eq!(Saturating(I4F4::from_num(-3)).signed_bits(), 7);      // “_101.0000”
1574    /// assert_eq!(Saturating(I4F4::from_num(-1)).signed_bits(), 5);      // “___1.0000”
1575    /// assert_eq!(Saturating(I4F4::from_num(-0.0625)).signed_bits(), 1); // “____.___1”
1576    /// assert_eq!(Saturating(I4F4::from_num(0)).signed_bits(), 1);       // “____.___0”
1577    /// assert_eq!(Saturating(I4F4::from_num(0.0625)).signed_bits(), 2);  // “____.__01”
1578    /// assert_eq!(Saturating(I4F4::from_num(1)).signed_bits(), 6);       // “__01.0000”
1579    /// assert_eq!(Saturating(I4F4::from_num(3)).signed_bits(), 7);       // “_011.0000”
1580    /// ```
1581    #[inline]
1582    pub fn signed_bits(self) -> u32 {
1583        self.0.signed_bits()
1584    }
1585
1586    /// Returns [`true`] if the number is >&nbsp;0.
1587    ///
1588    /// See also <code>FixedI32::[is\_positive][FixedI32::is_positive]</code>.
1589    ///
1590    /// # Examples
1591    ///
1592    /// ```rust
1593    /// use fixed::types::I16F16;
1594    /// use fixed::Saturating;
1595    /// assert!(Saturating(I16F16::from_num(4.3)).is_positive());
1596    /// assert!(!Saturating(I16F16::ZERO).is_positive());
1597    /// assert!(!Saturating(I16F16::from_num(-4.3)).is_positive());
1598    /// ```
1599    #[inline]
1600    pub fn is_positive(self) -> bool {
1601        self.0.is_positive()
1602    }
1603
1604    /// Returns [`true`] if the number is <&nbsp;0.
1605    ///
1606    /// See also <code>FixedI32::[is\_negative][FixedI32::is_negative]</code>.
1607    ///
1608    /// # Examples
1609    ///
1610    /// ```rust
1611    /// use fixed::types::I16F16;
1612    /// use fixed::Saturating;
1613    /// assert!(!Saturating(I16F16::from_num(4.3)).is_negative());
1614    /// assert!(!Saturating(I16F16::ZERO).is_negative());
1615    /// assert!(Saturating(I16F16::from_num(-4.3)).is_negative());
1616    /// ```
1617    #[inline]
1618    pub fn is_negative(self) -> bool {
1619        self.0.is_negative()
1620    }
1621
1622    /// Saturating absolute value. Returns the absolute value, saturating
1623    /// on overflow.
1624    ///
1625    /// Overflow can only occur when trying to find the absolute value
1626    /// of the minimum value.
1627    ///
1628    /// See also <code>FixedI32::[saturating\_abs][FixedI32::saturating_abs]</code>.
1629    ///
1630    /// # Examples
1631    ///
1632    /// ```rust
1633    /// use fixed::types::I16F16;
1634    /// use fixed::Saturating;
1635    /// assert_eq!(Saturating(I16F16::from_num(-5)).abs(), Saturating(I16F16::from_num(5)));
1636    /// assert_eq!(Saturating(I16F16::MIN).abs(), Saturating(I16F16::MAX));
1637    /// ```
1638    #[inline]
1639    #[must_use]
1640    pub fn abs(self) -> Saturating<F> {
1641        Saturating(self.0.saturating_abs())
1642    }
1643
1644    /// Returns a number representing the sign of `self`.
1645    ///
1646    /// # Warning
1647    ///
1648    /// Using this method when 1 and &minus;1 cannot be represented is
1649    /// almost certainly a bug, however, this is allowed and gives the
1650    /// following saturated results.
1651    ///
1652    ///   * When there are no integer bits, for example for the type
1653    ///     <code>[Saturating]&lt;[I0F16]&gt;</code>, the return value is zero
1654    ///     when `self` is zero, [`MIN`] when `self` is negative, and [`MAX`]
1655    ///     when `self` is positive.
1656    ///   * When there is one integer bit, for example for the type
1657    ///     <code>[Saturating]&lt;[I1F15]&gt;</code>, the return value is zero
1658    ///     when `self` is zero, &minus;1 when `self` is negative, and [`MAX`]
1659    ///     when `self` is positive.
1660    ///
1661    /// See also
1662    /// <code>FixedI32::[saturating\_signum][FixedI32::saturating_signum]</code>.
1663    ///
1664    /// # Examples
1665    ///
1666    /// ```rust
1667    /// use fixed::types::{I0F32, I1F31, I16F16};
1668    /// use fixed::Saturating;
1669    /// assert_eq!(Saturating(<I16F16>::from_num(-3.9)).signum(), Saturating(I16F16::NEG_ONE));
1670    /// assert_eq!(Saturating(<I16F16>::ZERO).signum(), Saturating(I16F16::ZERO));
1671    /// assert_eq!(Saturating(<I16F16>::from_num(3.9)).signum(), Saturating(I16F16::ONE));
1672    ///
1673    /// assert_eq!(Saturating(<I1F31>::from_num(0.5)).signum(), Saturating(I1F31::MAX));
1674    /// assert_eq!(Saturating(<I0F32>::from_num(0.25)).signum(), Saturating(I0F32::MAX));
1675    /// assert_eq!(Saturating(<I0F32>::from_num(-0.5)).signum(), Saturating(I0F32::MIN));
1676    /// ```
1677    ///
1678    /// [I0F16]: crate::types::I0F16
1679    /// [I1F15]: crate::types::I1F15
1680    /// [`MAX`]: Self::MAX
1681    /// [`MIN`]: Self::MIN
1682    #[inline]
1683    #[must_use]
1684    pub fn signum(self) -> Saturating<F> {
1685        Saturating(self.0.saturating_signum())
1686    }
1687
1688    /// Addition with an unsigned fixed-point number.
1689    ///
1690    /// See also
1691    /// <code>FixedI32::[saturating\_add\_unsigned][FixedI32::saturating_add_unsigned]</code>.
1692    ///
1693    /// # Examples
1694    ///
1695    /// ```rust
1696    /// use fixed::types::{I16F16, U16F16};
1697    /// use fixed::Saturating;
1698    /// assert_eq!(
1699    ///     Saturating::<I16F16>::from_num(-5).add_unsigned(U16F16::from_num(3)),
1700    ///     Saturating::<I16F16>::from_num(-2)
1701    /// );
1702    /// assert_eq!(
1703    ///     Saturating::<I16F16>::ZERO.add_unsigned(U16F16::MAX),
1704    ///     Saturating::<I16F16>::MAX
1705    /// );
1706    /// ```
1707    #[inline]
1708    #[must_use]
1709    pub fn add_unsigned(self, rhs: F::Unsigned) -> Saturating<F> {
1710        Saturating(self.0.saturating_add_unsigned(rhs))
1711    }
1712
1713    /// Subtraction with an unsigned fixed-point number.
1714    ///
1715    /// See also
1716    /// <code>FixedI32::[saturating\_sub\_unsigned][FixedI32::saturating_sub_unsigned]</code>.
1717    ///
1718    /// # Examples
1719    ///
1720    /// ```rust
1721    /// use fixed::types::{I16F16, U16F16};
1722    /// use fixed::Saturating;
1723    /// assert_eq!(
1724    ///     Saturating::<I16F16>::from_num(3).sub_unsigned(U16F16::from_num(5)),
1725    ///     Saturating::<I16F16>::from_num(-2)
1726    /// );
1727    /// assert_eq!(
1728    ///     Saturating::<I16F16>::ZERO.sub_unsigned(U16F16::MAX),
1729    ///     Saturating::<I16F16>::MIN
1730    /// );
1731    /// ```
1732    #[inline]
1733    #[must_use]
1734    pub fn sub_unsigned(self, rhs: F::Unsigned) -> Saturating<F> {
1735        Saturating(self.0.saturating_sub_unsigned(rhs))
1736    }
1737}
1738
1739impl<F: FixedUnsigned> Saturating<F> {
1740    /// Returns the bit pattern of `self` reinterpreted as a signed fixed-point
1741    /// number of the same size.
1742    ///
1743    /// See also <code>FixedU32::[cast\_signed][FixedU32::cast_signed]</code>.
1744    ///
1745    /// # Examples
1746    ///
1747    /// ```rust
1748    /// use fixed::types::{I16F16, U16F16};
1749    /// use fixed::Saturating;
1750    ///
1751    /// let n = Saturating(U16F16::MAX);
1752    /// assert_eq!(n.cast_signed(), Saturating(-I16F16::DELTA));
1753    /// ```
1754    #[must_use]
1755    #[inline]
1756    pub fn cast_signed(self) -> Saturating<F::Signed> {
1757        Saturating(self.0.cast_signed())
1758    }
1759
1760    /// Returns the number of bits required to represent the value.
1761    ///
1762    /// See also
1763    /// <code>FixedU32::[significant\_bits][FixedU32::significant_bits]</code>.
1764    ///
1765    /// # Examples
1766    ///
1767    /// ```rust
1768    /// use fixed::types::U4F4;
1769    /// use fixed::Saturating;
1770    /// assert_eq!(Saturating(U4F4::from_num(0)).significant_bits(), 0);      // “____.____”
1771    /// assert_eq!(Saturating(U4F4::from_num(0.0625)).significant_bits(), 1); // “____.___1”
1772    /// assert_eq!(Saturating(U4F4::from_num(1)).significant_bits(), 5);      // “___1.0000”
1773    /// assert_eq!(Saturating(U4F4::from_num(3)).significant_bits(), 6);      // “__11.0000”
1774    /// ```
1775    #[inline]
1776    pub fn significant_bits(self) -> u32 {
1777        self.0.significant_bits()
1778    }
1779
1780    /// Returns [`true`] if the fixed-point number is
1781    /// 2<sup><i>k</i></sup> for some integer <i>k</i>.
1782    ///
1783    /// See also
1784    /// <code>FixedU32::[is\_power\_of\_two][FixedU32::is_power_of_two]</code>.
1785    ///
1786    /// # Examples
1787    ///
1788    /// ```rust
1789    /// use fixed::types::U16F16;
1790    /// use fixed::Saturating;
1791    /// assert!(Saturating(U16F16::from_num(0.5)).is_power_of_two());
1792    /// assert!(Saturating(U16F16::from_num(4)).is_power_of_two());
1793    /// assert!(!Saturating(U16F16::from_num(5)).is_power_of_two());
1794    /// ```
1795    #[inline]
1796    pub fn is_power_of_two(self) -> bool {
1797        self.0.is_power_of_two()
1798    }
1799
1800    /// Returns the highest one in the binary representation, or zero
1801    /// if `self` is zero.
1802    ///
1803    /// If `self`&nbsp;>&nbsp;0, the highest one is equal to the largest power
1804    /// of two that is ≤&nbsp;`self`.
1805    ///
1806    /// See also <code>FixedU32::[highest\_one][FixedU32::highest_one]</code>.
1807    ///
1808    /// # Examples
1809    ///
1810    /// ```rust
1811    /// use fixed::types::U16F16;
1812    /// use fixed::Saturating;
1813    /// type Sa = Saturating<U16F16>;
1814    /// assert_eq!(Sa::from_bits(0b11_0010).highest_one(), Sa::from_bits(0b10_0000));
1815    /// assert_eq!(Sa::from_num(0.3).highest_one(), Sa::from_num(0.25));
1816    /// assert_eq!(Sa::from_num(4).highest_one(), Sa::from_num(4));
1817    /// assert_eq!(Sa::from_num(6.5).highest_one(), Sa::from_num(4));
1818    /// assert_eq!(Sa::ZERO.highest_one(), Sa::ZERO);
1819    /// ```
1820    #[inline]
1821    #[must_use]
1822    pub fn highest_one(self) -> Saturating<F> {
1823        Saturating(self.0.highest_one())
1824    }
1825
1826    /// Addition with an signed fixed-point number.
1827    ///
1828    /// See also
1829    /// <code>FixedU32::[saturating\_add\_signed][FixedU32::saturating_add_signed]</code>.
1830    ///
1831    /// # Examples
1832    ///
1833    /// ```rust
1834    /// use fixed::types::{I16F16, U16F16};
1835    /// use fixed::Saturating;
1836    /// assert_eq!(
1837    ///     Saturating::<U16F16>::from_num(5).add_signed(I16F16::from_num(-3)),
1838    ///     Saturating::<U16F16>::from_num(2)
1839    /// );
1840    /// assert_eq!(
1841    ///     Saturating::<U16F16>::ZERO.add_signed(-I16F16::DELTA),
1842    ///     Saturating::<U16F16>::ZERO
1843    /// );
1844    /// ```
1845    #[inline]
1846    #[must_use]
1847    pub fn add_signed(self, rhs: F::Signed) -> Saturating<F> {
1848        Saturating(self.0.saturating_add_signed(rhs))
1849    }
1850
1851    /// Subtraction with an signed fixed-point number.
1852    ///
1853    /// See also
1854    /// <code>FixedU32::[saturating\_sub\_signed][FixedU32::saturating_sub_signed]</code>.
1855    ///
1856    /// # Examples
1857    ///
1858    /// ```rust
1859    /// use fixed::types::{I16F16, U16F16};
1860    /// use fixed::Saturating;
1861    /// assert_eq!(
1862    ///     Saturating::<U16F16>::from_num(5).sub_signed(I16F16::from_num(-3)),
1863    ///     Saturating::<U16F16>::from_num(8)
1864    /// );
1865    /// assert_eq!(
1866    ///     Saturating::<U16F16>::ZERO.sub_signed(I16F16::DELTA),
1867    ///     Saturating::<U16F16>::ZERO
1868    /// );
1869    /// ```
1870    #[inline]
1871    #[must_use]
1872    pub fn sub_signed(self, rhs: F::Signed) -> Saturating<F> {
1873        Saturating(self.0.saturating_sub_signed(rhs))
1874    }
1875}
1876
1877impl<F: Fixed> Display for Saturating<F> {
1878    #[inline]
1879    fn fmt(&self, f: &mut Formatter) -> FmtResult {
1880        Display::fmt(&self.0, f)
1881    }
1882}
1883
1884impl<F: Fixed> Debug for Saturating<F> {
1885    #[inline]
1886    fn fmt(&self, f: &mut Formatter) -> FmtResult {
1887        Debug::fmt(&self.0, f)
1888    }
1889}
1890
1891impl<F: Fixed> Binary for Saturating<F> {
1892    #[inline]
1893    fn fmt(&self, f: &mut Formatter) -> FmtResult {
1894        Binary::fmt(&self.0, f)
1895    }
1896}
1897
1898impl<F: Fixed> Octal for Saturating<F> {
1899    #[inline]
1900    fn fmt(&self, f: &mut Formatter) -> FmtResult {
1901        Octal::fmt(&self.0, f)
1902    }
1903}
1904
1905impl<F: Fixed> LowerHex for Saturating<F> {
1906    #[inline]
1907    fn fmt(&self, f: &mut Formatter) -> FmtResult {
1908        LowerHex::fmt(&self.0, f)
1909    }
1910}
1911
1912impl<F: Fixed> UpperHex for Saturating<F> {
1913    #[inline]
1914    fn fmt(&self, f: &mut Formatter) -> FmtResult {
1915        UpperHex::fmt(&self.0, f)
1916    }
1917}
1918
1919impl<F: Fixed> LowerExp for Saturating<F> {
1920    #[inline]
1921    fn fmt(&self, f: &mut Formatter) -> FmtResult {
1922        LowerExp::fmt(&self.0, f)
1923    }
1924}
1925
1926impl<F: Fixed> UpperExp for Saturating<F> {
1927    #[inline]
1928    fn fmt(&self, f: &mut Formatter) -> FmtResult {
1929        UpperExp::fmt(&self.0, f)
1930    }
1931}
1932
1933impl<F: Fixed> From<F> for Saturating<F> {
1934    /// Saturates a fixed-point number.
1935    #[inline]
1936    fn from(src: F) -> Saturating<F> {
1937        Saturating(src)
1938    }
1939}
1940
1941impl<F: Fixed> FromStr for Saturating<F> {
1942    type Err = ParseFixedError;
1943    /// Parses a string slice containing decimal digits to return a fixed-point number.
1944    ///
1945    /// Rounding is to the nearest, with ties rounded to even.
1946    #[inline]
1947    fn from_str(s: &str) -> Result<Self, Self::Err> {
1948        F::saturating_from_str(s).map(Saturating)
1949    }
1950}
1951
1952macro_rules! op {
1953    ($saturating:ident, $Op:ident $op:ident, $OpAssign:ident $op_assign:ident) => {
1954        impl<F: Fixed> $Op<Saturating<F>> for Saturating<F> {
1955            type Output = Saturating<F>;
1956            #[inline]
1957            fn $op(self, other: Saturating<F>) -> Saturating<F> {
1958                Saturating((self.0).$saturating(other.0))
1959            }
1960        }
1961        impl<F: Fixed> $Op<Saturating<F>> for &Saturating<F> {
1962            type Output = Saturating<F>;
1963            #[inline]
1964            fn $op(self, other: Saturating<F>) -> Saturating<F> {
1965                Saturating((self.0).$saturating(other.0))
1966            }
1967        }
1968        impl<F: Fixed> $Op<&Saturating<F>> for Saturating<F> {
1969            type Output = Saturating<F>;
1970            #[inline]
1971            fn $op(self, other: &Saturating<F>) -> Saturating<F> {
1972                Saturating((self.0).$saturating(other.0))
1973            }
1974        }
1975        impl<F: Fixed> $Op<&Saturating<F>> for &Saturating<F> {
1976            type Output = Saturating<F>;
1977            #[inline]
1978            fn $op(self, other: &Saturating<F>) -> Saturating<F> {
1979                Saturating((self.0).$saturating(other.0))
1980            }
1981        }
1982        impl<F: Fixed> $OpAssign<Saturating<F>> for Saturating<F> {
1983            #[inline]
1984            fn $op_assign(&mut self, other: Saturating<F>) {
1985                self.0 = (self.0).$saturating(other.0);
1986            }
1987        }
1988        impl<F: Fixed> $OpAssign<&Saturating<F>> for Saturating<F> {
1989            #[inline]
1990            fn $op_assign(&mut self, other: &Saturating<F>) {
1991                self.0 = (self.0).$saturating(other.0);
1992            }
1993        }
1994        impl<F: Fixed> $OpAssign<F> for Saturating<F> {
1995            #[inline]
1996            fn $op_assign(&mut self, other: F) {
1997                self.0 = (self.0).$saturating(other);
1998            }
1999        }
2000        impl<F: Fixed> $OpAssign<&F> for Saturating<F> {
2001            #[inline]
2002            fn $op_assign(&mut self, other: &F) {
2003                self.0 = (self.0).$saturating(*other);
2004            }
2005        }
2006    };
2007}
2008
2009macro_rules! op_bitwise {
2010    ($Op:ident $op:ident, $OpAssign:ident $op_assign:ident) => {
2011        impl<F> $Op<Saturating<F>> for Saturating<F>
2012        where
2013            F: $Op<F, Output = F>,
2014        {
2015            type Output = Saturating<F>;
2016            #[inline]
2017            fn $op(self, other: Saturating<F>) -> Saturating<F> {
2018                Saturating((self.0).$op(other.0))
2019            }
2020        }
2021        impl<F> $Op<Saturating<F>> for &Saturating<F>
2022        where
2023            for<'a> &'a F: $Op<F, Output = F>,
2024        {
2025            type Output = Saturating<F>;
2026            #[inline]
2027            fn $op(self, other: Saturating<F>) -> Saturating<F> {
2028                Saturating((self.0).$op(other.0))
2029            }
2030        }
2031        impl<F> $Op<&Saturating<F>> for Saturating<F>
2032        where
2033            for<'a> F: $Op<&'a F, Output = F>,
2034        {
2035            type Output = Saturating<F>;
2036            #[inline]
2037            fn $op(self, other: &Saturating<F>) -> Saturating<F> {
2038                Saturating((self.0).$op(&other.0))
2039            }
2040        }
2041        impl<F> $Op<&Saturating<F>> for &Saturating<F>
2042        where
2043            for<'a, 'b> &'a F: $Op<&'b F, Output = F>,
2044        {
2045            type Output = Saturating<F>;
2046            #[inline]
2047            fn $op(self, other: &Saturating<F>) -> Saturating<F> {
2048                Saturating((self.0).$op(&other.0))
2049            }
2050        }
2051        impl<F> $OpAssign<Saturating<F>> for Saturating<F>
2052        where
2053            F: $OpAssign<F>,
2054        {
2055            #[inline]
2056            fn $op_assign(&mut self, other: Saturating<F>) {
2057                (self.0).$op_assign(other.0);
2058            }
2059        }
2060        impl<F> $OpAssign<&Saturating<F>> for Saturating<F>
2061        where
2062            for<'a> F: $OpAssign<&'a F>,
2063        {
2064            #[inline]
2065            fn $op_assign(&mut self, other: &Saturating<F>) {
2066                (self.0).$op_assign(&other.0);
2067            }
2068        }
2069        impl<F> $OpAssign<F> for Saturating<F>
2070        where
2071            F: $OpAssign<F>,
2072        {
2073            #[inline]
2074            fn $op_assign(&mut self, other: F) {
2075                (self.0).$op_assign(other);
2076            }
2077        }
2078        impl<F> $OpAssign<&F> for Saturating<F>
2079        where
2080            for<'a> F: $OpAssign<&'a F>,
2081        {
2082            #[inline]
2083            fn $op_assign(&mut self, other: &F) {
2084                (self.0).$op_assign(other);
2085            }
2086        }
2087    };
2088}
2089
2090impl<F: Fixed> Neg for Saturating<F> {
2091    type Output = Saturating<F>;
2092    #[inline]
2093    fn neg(self) -> Saturating<F> {
2094        Saturating((self.0).saturating_neg())
2095    }
2096}
2097
2098impl<F: Fixed> Neg for &Saturating<F> {
2099    type Output = Saturating<F>;
2100    #[inline]
2101    fn neg(self) -> Saturating<F> {
2102        Saturating((self.0).saturating_neg())
2103    }
2104}
2105op! { saturating_add, Add add, AddAssign add_assign }
2106op! { saturating_sub, Sub sub, SubAssign sub_assign }
2107op! { saturating_mul, Mul mul, MulAssign mul_assign }
2108op! { saturating_div, Div div, DivAssign div_assign }
2109op! { rem, Rem rem, RemAssign rem_assign }
2110
2111impl<F> Not for Saturating<F>
2112where
2113    F: Not<Output = F>,
2114{
2115    type Output = Saturating<F>;
2116    #[inline]
2117    fn not(self) -> Saturating<F> {
2118        Saturating((self.0).not())
2119    }
2120}
2121impl<F> Not for &Saturating<F>
2122where
2123    for<'a> &'a F: Not<Output = F>,
2124{
2125    type Output = Saturating<F>;
2126    #[inline]
2127    fn not(self) -> Saturating<F> {
2128        Saturating((self.0).not())
2129    }
2130}
2131op_bitwise! { BitAnd bitand, BitAndAssign bitand_assign }
2132op_bitwise! { BitOr bitor, BitOrAssign bitor_assign }
2133op_bitwise! { BitXor bitxor, BitXorAssign bitxor_assign }
2134
2135impl<F: Fixed> Sum<Saturating<F>> for Saturating<F> {
2136    fn sum<I>(iter: I) -> Saturating<F>
2137    where
2138        I: Iterator<Item = Saturating<F>>,
2139    {
2140        iter.fold(Saturating(F::ZERO), Add::add)
2141    }
2142}
2143
2144impl<'a, F: 'a + Fixed> Sum<&'a Saturating<F>> for Saturating<F> {
2145    fn sum<I>(iter: I) -> Saturating<F>
2146    where
2147        I: Iterator<Item = &'a Saturating<F>>,
2148    {
2149        iter.fold(Saturating(F::ZERO), Add::add)
2150    }
2151}
2152
2153impl<F: Fixed> Product<Saturating<F>> for Saturating<F> {
2154    fn product<I>(mut iter: I) -> Saturating<F>
2155    where
2156        I: Iterator<Item = Saturating<F>>,
2157    {
2158        match iter.next() {
2159            None => Saturating(1.saturating_to_fixed()),
2160            Some(first) => iter.fold(first, Mul::mul),
2161        }
2162    }
2163}
2164
2165impl<'a, F: 'a + Fixed> Product<&'a Saturating<F>> for Saturating<F> {
2166    fn product<I>(mut iter: I) -> Saturating<F>
2167    where
2168        I: Iterator<Item = &'a Saturating<F>>,
2169    {
2170        match iter.next() {
2171            None => Saturating(1.saturating_to_fixed()),
2172            Some(first) => iter.fold(*first, Mul::mul),
2173        }
2174    }
2175}
2176
2177// The following cannot be implemented for Saturating<F> where F: Fixed,
2178// otherwise there will be a conflicting implementation error. For
2179// example we cannot implement both these without triggering E0119:
2180//
2181//     impl<F: Fixed> Op<F::Bits> for Saturating<F> { /* ... */ }
2182//     impl<F: Fixed> Op<&F::Bits> for Saturating<F> { /* ... */ }
2183//
2184// To work around this, we provide implementations like this:
2185//
2186//     impl<Frac> Op<i8> for Saturating<FixedI8<Frac>> { /* ... */ }
2187//     impl<Frac> Op<&i8> for Saturating<FixedI8<Frac>> { /* ... */ }
2188//     impl<Frac> Op<i16> for Saturating<FixedI16<Frac>> { /* ... */ }
2189//     impl<Frac> Op<&i16> for Saturating<FixedI16<Frac>> { /* ... */ }
2190//     ...
2191
2192macro_rules! op_bits {
2193    (
2194        $Fixed:ident($Bits:ident $(, $LeEqU:ident)*)::$saturating:ident,
2195        $Op:ident $op:ident,
2196        $OpAssign:ident $op_assign:ident
2197    ) => {
2198        impl<Frac $(: $LeEqU)*> $Op<$Bits> for Saturating<$Fixed<Frac>> {
2199            type Output = Saturating<$Fixed<Frac>>;
2200            #[inline]
2201            fn $op(self, other: $Bits) -> Saturating<$Fixed<Frac>> {
2202                Saturating((self.0).$saturating(other))
2203            }
2204        }
2205        impl<Frac $(: $LeEqU)*> $Op<$Bits> for &Saturating<$Fixed<Frac>> {
2206            type Output = Saturating<$Fixed<Frac>>;
2207            #[inline]
2208            fn $op(self, other: $Bits) -> Saturating<$Fixed<Frac>> {
2209                Saturating((self.0).$saturating(other))
2210            }
2211        }
2212        impl<Frac $(: $LeEqU)*> $Op<&$Bits> for Saturating<$Fixed<Frac>> {
2213            type Output = Saturating<$Fixed<Frac>>;
2214            #[inline]
2215            fn $op(self, other: &$Bits) -> Saturating<$Fixed<Frac>> {
2216                Saturating((self.0).$saturating(*other))
2217            }
2218        }
2219        impl<Frac $(: $LeEqU)*> $Op<&$Bits> for &Saturating<$Fixed<Frac>> {
2220            type Output = Saturating<$Fixed<Frac>>;
2221            #[inline]
2222            fn $op(self, other: &$Bits) -> Saturating<$Fixed<Frac>> {
2223                Saturating((self.0).$saturating(*other))
2224            }
2225        }
2226        impl<Frac $(: $LeEqU)*> $OpAssign<$Bits> for Saturating<$Fixed<Frac>> {
2227            #[inline]
2228            fn $op_assign(&mut self, other: $Bits) {
2229                self.0 = (self.0).$saturating(other);
2230            }
2231        }
2232        impl<Frac $(: $LeEqU)*> $OpAssign<&$Bits> for Saturating<$Fixed<Frac>> {
2233            #[inline]
2234            fn $op_assign(&mut self, other: &$Bits) {
2235                self.0 = (self.0).$saturating(*other);
2236            }
2237        }
2238    };
2239}
2240
2241macro_rules! ops {
2242    ($Fixed:ident($Bits:ident, $LeEqU:ident)) => {
2243        op_bits! { $Fixed($Bits)::saturating_mul_int, Mul mul, MulAssign mul_assign }
2244        op_bits! { $Fixed($Bits)::saturating_div_int, Div div, DivAssign div_assign }
2245        op_bits! { $Fixed($Bits, $LeEqU)::rem, Rem rem, RemAssign rem_assign }
2246    };
2247}
2248ops! { FixedI8(i8, LeEqU8) }
2249ops! { FixedI16(i16, LeEqU16) }
2250ops! { FixedI32(i32, LeEqU32) }
2251ops! { FixedI64(i64, LeEqU64) }
2252ops! { FixedI128(i128, LeEqU128) }
2253ops! { FixedU8(u8, LeEqU8) }
2254ops! { FixedU16(u16, LeEqU16) }
2255ops! { FixedU32(u32, LeEqU32) }
2256ops! { FixedU64(u64, LeEqU64) }
2257ops! { FixedU128(u128, LeEqU128) }