Skip to main content

core/num/
saturating.rs

1//! Definitions of `Saturating<T>`.
2
3use crate::fmt;
4use crate::ops::{
5    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
6    Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,
7};
8
9/// Provides intentionally-saturating arithmetic on `T`.
10///
11/// Operations like `+` on `u32` values are intended to never overflow,
12/// and in some debug configurations overflow is detected and results
13/// in a panic. While most arithmetic falls into this category, some
14/// code explicitly expects and relies upon saturating arithmetic.
15///
16/// Saturating arithmetic can be achieved either through methods like
17/// `saturating_add`, or through the `Saturating<T>` type, which says that
18/// all standard arithmetic operations on the underlying value are
19/// intended to have saturating semantics.
20///
21/// The underlying value can be retrieved through the `.0` index of the
22/// `Saturating` tuple.
23///
24/// # Examples
25///
26/// ```
27/// use std::num::Saturating;
28///
29/// let max = Saturating(u32::MAX);
30/// let one = Saturating(1u32);
31///
32/// assert_eq!(u32::MAX, (max + one).0);
33/// ```
34///
35/// # Layout
36///
37/// `Saturating<T>` is guaranteed to have the same layout and ABI as `T`.
38#[stable(feature = "saturating_int_impl", since = "1.74.0")]
39#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
40#[repr(transparent)]
41#[rustc_diagnostic_item = "Saturating"]
42pub struct Saturating<T>(#[stable(feature = "saturating_int_impl", since = "1.74.0")] pub T);
43
44#[stable(feature = "saturating_int_impl", since = "1.74.0")]
45impl<T: fmt::Debug> fmt::Debug for Saturating<T> {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        self.0.fmt(f)
48    }
49}
50
51#[stable(feature = "saturating_int_impl", since = "1.74.0")]
52impl<T: fmt::Display> fmt::Display for Saturating<T> {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        self.0.fmt(f)
55    }
56}
57
58#[stable(feature = "saturating_int_impl", since = "1.74.0")]
59impl<T: fmt::Binary> fmt::Binary for Saturating<T> {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        self.0.fmt(f)
62    }
63}
64
65#[stable(feature = "saturating_int_impl", since = "1.74.0")]
66impl<T: fmt::Octal> fmt::Octal for Saturating<T> {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        self.0.fmt(f)
69    }
70}
71
72#[stable(feature = "saturating_int_impl", since = "1.74.0")]
73impl<T: fmt::LowerHex> fmt::LowerHex for Saturating<T> {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        self.0.fmt(f)
76    }
77}
78
79#[stable(feature = "saturating_int_impl", since = "1.74.0")]
80impl<T: fmt::UpperHex> fmt::UpperHex for Saturating<T> {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        self.0.fmt(f)
83    }
84}
85
86// FIXME the correct implementation is not clear. Waiting for a real world use case at https://github.com/rust-lang/libs-team/issues/230
87//
88// #[allow(unused_macros)]
89// macro_rules! sh_impl_signed {
90//     ($t:ident, $f:ident) => {
91//         // FIXME what is the correct implementation here? see discussion https://github.com/rust-lang/rust/pull/87921#discussion_r695870065
92//         //
93//         // #[unstable(feature = "saturating_int_impl", issue = "87920")]
94//         // impl Shl<$f> for Saturating<$t> {
95//         //     type Output = Saturating<$t>;
96//         //
97//         //     #[inline]
98//         //     fn shl(self, other: $f) -> Saturating<$t> {
99//         //         if other < 0 {
100//         //             Saturating(self.0.shr((-other & self::shift_max::$t as $f) as u32))
101//         //         } else {
102//         //             Saturating(self.0.shl((other & self::shift_max::$t as $f) as u32))
103//         //         }
104//         //     }
105//         // }
106//         // forward_ref_binop! { impl Shl, shl for Saturating<$t>, $f,
107//         // #[unstable(feature = "saturating_int_impl", issue = "87920")] }
108//         //
109//         // #[unstable(feature = "saturating_int_impl", issue = "87920")]
110//         // impl ShlAssign<$f> for Saturating<$t> {
111//         //     #[inline]
112//         //     fn shl_assign(&mut self, other: $f) {
113//         //         *self = *self << other;
114//         //     }
115//         // }
116//         // forward_ref_op_assign! { impl ShlAssign, shl_assign for Saturating<$t>, $f,
117//         // #[unstable(feature = "saturating_int_impl", issue = "87920")] }
118//
119//         #[unstable(feature = "saturating_int_impl", issue = "87920")]
120//         impl Shr<$f> for Saturating<$t> {
121//             type Output = Saturating<$t>;
122//
123//             #[inline]
124//             fn shr(self, other: $f) -> Saturating<$t> {
125//                 if other < 0 {
126//                     Saturating(self.0.shl((-other & self::shift_max::$t as $f) as u32))
127//                 } else {
128//                     Saturating(self.0.shr((other & self::shift_max::$t as $f) as u32))
129//                 }
130//             }
131//         }
132//         forward_ref_binop! { impl Shr, shr for Saturating<$t>, $f,
133//         #[unstable(feature = "saturating_int_impl", issue = "87920")] }
134//
135//         #[unstable(feature = "saturating_int_impl", issue = "87920")]
136//         impl ShrAssign<$f> for Saturating<$t> {
137//             #[inline]
138//             fn shr_assign(&mut self, other: $f) {
139//                 *self = *self >> other;
140//             }
141//         }
142//         forward_ref_op_assign! { impl ShrAssign, shr_assign for Saturating<$t>, $f,
143//         #[unstable(feature = "saturating_int_impl", issue = "87920")] }
144//     };
145// }
146//
147// macro_rules! sh_impl_unsigned {
148//     ($t:ident, $f:ident) => {
149//         #[unstable(feature = "saturating_int_impl", issue = "87920")]
150//         impl Shl<$f> for Saturating<$t> {
151//             type Output = Saturating<$t>;
152//
153//             #[inline]
154//             fn shl(self, other: $f) -> Saturating<$t> {
155//                 Saturating(self.0.wrapping_shl(other as u32))
156//             }
157//         }
158//         forward_ref_binop! { impl Shl, shl for Saturating<$t>, $f,
159//         #[unstable(feature = "saturating_int_impl", issue = "87920")] }
160//
161//         #[unstable(feature = "saturating_int_impl", issue = "87920")]
162//         impl ShlAssign<$f> for Saturating<$t> {
163//             #[inline]
164//             fn shl_assign(&mut self, other: $f) {
165//                 *self = *self << other;
166//             }
167//         }
168//         forward_ref_op_assign! { impl ShlAssign, shl_assign for Saturating<$t>, $f,
169//         #[unstable(feature = "saturating_int_impl", issue = "87920")] }
170//
171//         #[unstable(feature = "saturating_int_impl", issue = "87920")]
172//         impl Shr<$f> for Saturating<$t> {
173//             type Output = Saturating<$t>;
174//
175//             #[inline]
176//             fn shr(self, other: $f) -> Saturating<$t> {
177//                 Saturating(self.0.wrapping_shr(other as u32))
178//             }
179//         }
180//         forward_ref_binop! { impl Shr, shr for Saturating<$t>, $f,
181//         #[unstable(feature = "saturating_int_impl", issue = "87920")] }
182//
183//         #[unstable(feature = "saturating_int_impl", issue = "87920")]
184//         impl ShrAssign<$f> for Saturating<$t> {
185//             #[inline]
186//             fn shr_assign(&mut self, other: $f) {
187//                 *self = *self >> other;
188//             }
189//         }
190//         forward_ref_op_assign! { impl ShrAssign, shr_assign for Saturating<$t>, $f,
191//         #[unstable(feature = "saturating_int_impl", issue = "87920")] }
192//     };
193// }
194//
195// // FIXME (#23545): uncomment the remaining impls
196// macro_rules! sh_impl_all {
197//     ($($t:ident)*) => ($(
198//         //sh_impl_unsigned! { $t, u8 }
199//         //sh_impl_unsigned! { $t, u16 }
200//         //sh_impl_unsigned! { $t, u32 }
201//         //sh_impl_unsigned! { $t, u64 }
202//         //sh_impl_unsigned! { $t, u128 }
203//         sh_impl_unsigned! { $t, usize }
204//
205//         //sh_impl_signed! { $t, i8 }
206//         //sh_impl_signed! { $t, i16 }
207//         //sh_impl_signed! { $t, i32 }
208//         //sh_impl_signed! { $t, i64 }
209//         //sh_impl_signed! { $t, i128 }
210//         //sh_impl_signed! { $t, isize }
211//     )*)
212// }
213//
214// sh_impl_all! { u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize }
215
216// FIXME(30524): impl Op<T> for Saturating<T>, impl OpAssign<T> for Saturating<T>
217macro_rules! saturating_impl {
218    ($($t:ty)*) => ($(
219        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
220        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
221        const impl Add for Saturating<$t> {
222            type Output = Saturating<$t>;
223
224            #[inline]
225            #[ferrocene::prevalidated]
226            fn add(self, other: Saturating<$t>) -> Saturating<$t> {
227                Saturating(self.0.saturating_add(other.0))
228            }
229        }
230        forward_ref_binop! { impl Add, add for Saturating<$t>, Saturating<$t>,
231        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
232        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
233
234        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
235        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
236        const impl AddAssign for Saturating<$t> {
237            #[inline]
238            #[ferrocene::prevalidated]
239            fn add_assign(&mut self, other: Saturating<$t>) {
240                *self = *self + other;
241            }
242        }
243        forward_ref_op_assign! { impl AddAssign, add_assign for Saturating<$t>, Saturating<$t>,
244        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
245        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
246
247        #[stable(feature = "saturating_int_assign_impl", since = "1.74.0")]
248        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
249        const impl AddAssign<$t> for Saturating<$t> {
250            #[inline]
251            #[ferrocene::prevalidated]
252            fn add_assign(&mut self, other: $t) {
253                *self = *self + Saturating(other);
254            }
255        }
256        forward_ref_op_assign! { impl AddAssign, add_assign for Saturating<$t>, $t,
257        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
258        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
259
260        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
261        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
262        const impl Sub for Saturating<$t> {
263            type Output = Saturating<$t>;
264
265            #[inline]
266            #[ferrocene::prevalidated]
267            fn sub(self, other: Saturating<$t>) -> Saturating<$t> {
268                Saturating(self.0.saturating_sub(other.0))
269            }
270        }
271        forward_ref_binop! { impl Sub, sub for Saturating<$t>, Saturating<$t>,
272        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
273        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
274
275        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
276        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
277        const impl SubAssign for Saturating<$t> {
278            #[inline]
279            #[ferrocene::prevalidated]
280            fn sub_assign(&mut self, other: Saturating<$t>) {
281                *self = *self - other;
282            }
283        }
284        forward_ref_op_assign! { impl SubAssign, sub_assign for Saturating<$t>, Saturating<$t>,
285        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
286        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
287
288        #[stable(feature = "saturating_int_assign_impl", since = "1.74.0")]
289        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
290        const impl SubAssign<$t> for Saturating<$t> {
291            #[inline]
292            #[ferrocene::prevalidated]
293            fn sub_assign(&mut self, other: $t) {
294                *self = *self - Saturating(other);
295            }
296        }
297        forward_ref_op_assign! { impl SubAssign, sub_assign for Saturating<$t>, $t,
298        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
299        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
300
301        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
302        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
303        const impl Mul for Saturating<$t> {
304            type Output = Saturating<$t>;
305
306            #[inline]
307            #[ferrocene::prevalidated]
308            fn mul(self, other: Saturating<$t>) -> Saturating<$t> {
309                Saturating(self.0.saturating_mul(other.0))
310            }
311        }
312        forward_ref_binop! { impl Mul, mul for Saturating<$t>, Saturating<$t>,
313        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
314        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
315
316        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
317        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
318        const impl MulAssign for Saturating<$t> {
319            #[inline]
320            #[ferrocene::prevalidated]
321            fn mul_assign(&mut self, other: Saturating<$t>) {
322                *self = *self * other;
323            }
324        }
325        forward_ref_op_assign! { impl MulAssign, mul_assign for Saturating<$t>, Saturating<$t>,
326        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
327        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
328
329        #[stable(feature = "saturating_int_assign_impl", since = "1.74.0")]
330        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
331        const impl MulAssign<$t> for Saturating<$t> {
332            #[inline]
333            #[ferrocene::prevalidated]
334            fn mul_assign(&mut self, other: $t) {
335                *self = *self * Saturating(other);
336            }
337        }
338        forward_ref_op_assign! { impl MulAssign, mul_assign for Saturating<$t>, $t,
339        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
340        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
341
342        /// # Examples
343        ///
344        /// ```
345        /// use std::num::Saturating;
346        ///
347        #[doc = concat!("assert_eq!(Saturating(2", stringify!($t), "), Saturating(5", stringify!($t), ") / Saturating(2));")]
348        #[doc = concat!("assert_eq!(Saturating(", stringify!($t), "::MAX), Saturating(", stringify!($t), "::MAX) / Saturating(1));")]
349        #[doc = concat!("assert_eq!(Saturating(", stringify!($t), "::MIN), Saturating(", stringify!($t), "::MIN) / Saturating(1));")]
350        /// ```
351        ///
352        /// ```should_panic
353        /// use std::num::Saturating;
354        ///
355        #[doc = concat!("let _ = Saturating(0", stringify!($t), ") / Saturating(0);")]
356        /// ```
357        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
358        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
359        const impl Div for Saturating<$t> {
360            type Output = Saturating<$t>;
361
362            #[inline]
363            #[ferrocene::prevalidated]
364            fn div(self, other: Saturating<$t>) -> Saturating<$t> {
365                Saturating(self.0.saturating_div(other.0))
366            }
367        }
368        forward_ref_binop! { impl Div, div for Saturating<$t>, Saturating<$t>,
369        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
370        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
371
372        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
373        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
374        const impl DivAssign for Saturating<$t> {
375            #[inline]
376            #[ferrocene::prevalidated]
377            fn div_assign(&mut self, other: Saturating<$t>) {
378                *self = *self / other;
379            }
380        }
381        forward_ref_op_assign! { impl DivAssign, div_assign for Saturating<$t>, Saturating<$t>,
382        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
383        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
384
385        #[stable(feature = "saturating_int_assign_impl", since = "1.74.0")]
386        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
387        const impl DivAssign<$t> for Saturating<$t> {
388            #[inline]
389            #[ferrocene::prevalidated]
390            fn div_assign(&mut self, other: $t) {
391                *self = *self / Saturating(other);
392            }
393        }
394        forward_ref_op_assign! { impl DivAssign, div_assign for Saturating<$t>, $t,
395        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
396        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
397
398        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
399        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
400        const impl Rem for Saturating<$t> {
401            type Output = Saturating<$t>;
402
403            #[inline]
404            #[ferrocene::prevalidated]
405            fn rem(self, other: Saturating<$t>) -> Saturating<$t> {
406                Saturating(self.0.rem(other.0))
407            }
408        }
409        forward_ref_binop! { impl Rem, rem for Saturating<$t>, Saturating<$t>,
410        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
411        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
412
413        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
414        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
415        const impl RemAssign for Saturating<$t> {
416            #[inline]
417            #[ferrocene::prevalidated]
418            fn rem_assign(&mut self, other: Saturating<$t>) {
419                *self = *self % other;
420            }
421        }
422        forward_ref_op_assign! { impl RemAssign, rem_assign for Saturating<$t>, Saturating<$t>,
423        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
424        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
425
426        #[stable(feature = "saturating_int_assign_impl", since = "1.74.0")]
427        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
428        const impl RemAssign<$t> for Saturating<$t> {
429            #[inline]
430            #[ferrocene::prevalidated]
431            fn rem_assign(&mut self, other: $t) {
432                *self = *self % Saturating(other);
433            }
434        }
435        forward_ref_op_assign! { impl RemAssign, rem_assign for Saturating<$t>, $t,
436        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
437        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
438
439        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
440        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
441        const impl Not for Saturating<$t> {
442            type Output = Saturating<$t>;
443
444            #[inline]
445            #[ferrocene::prevalidated]
446            fn not(self) -> Saturating<$t> {
447                Saturating(!self.0)
448            }
449        }
450        forward_ref_unop! { impl Not, not for Saturating<$t>,
451        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
452        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
453
454        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
455        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
456        const impl BitXor for Saturating<$t> {
457            type Output = Saturating<$t>;
458
459            #[inline]
460            #[ferrocene::prevalidated]
461            fn bitxor(self, other: Saturating<$t>) -> Saturating<$t> {
462                Saturating(self.0 ^ other.0)
463            }
464        }
465        forward_ref_binop! { impl BitXor, bitxor for Saturating<$t>, Saturating<$t>,
466        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
467        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
468
469        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
470        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
471        const impl BitXorAssign for Saturating<$t> {
472            #[inline]
473            #[ferrocene::prevalidated]
474            fn bitxor_assign(&mut self, other: Saturating<$t>) {
475                *self = *self ^ other;
476            }
477        }
478        forward_ref_op_assign! { impl BitXorAssign, bitxor_assign for Saturating<$t>, Saturating<$t>,
479        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
480        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
481
482        #[stable(feature = "saturating_int_assign_impl", since = "1.74.0")]
483        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
484        const impl BitXorAssign<$t> for Saturating<$t> {
485            #[inline]
486            #[ferrocene::prevalidated]
487            fn bitxor_assign(&mut self, other: $t) {
488                *self = *self ^ Saturating(other);
489            }
490        }
491        forward_ref_op_assign! { impl BitXorAssign, bitxor_assign for Saturating<$t>, $t,
492        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
493        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
494
495        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
496        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
497        const impl BitOr for Saturating<$t> {
498            type Output = Saturating<$t>;
499
500            #[inline]
501            #[ferrocene::prevalidated]
502            fn bitor(self, other: Saturating<$t>) -> Saturating<$t> {
503                Saturating(self.0 | other.0)
504            }
505        }
506        forward_ref_binop! { impl BitOr, bitor for Saturating<$t>, Saturating<$t>,
507        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
508        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
509
510        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
511        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
512        const impl BitOrAssign for Saturating<$t> {
513            #[inline]
514            #[ferrocene::prevalidated]
515            fn bitor_assign(&mut self, other: Saturating<$t>) {
516                *self = *self | other;
517            }
518        }
519        forward_ref_op_assign! { impl BitOrAssign, bitor_assign for Saturating<$t>, Saturating<$t>,
520        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
521        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
522
523        #[stable(feature = "saturating_int_assign_impl", since = "1.74.0")]
524        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
525        const impl BitOrAssign<$t> for Saturating<$t> {
526            #[inline]
527            #[ferrocene::prevalidated]
528            fn bitor_assign(&mut self, other: $t) {
529                *self = *self | Saturating(other);
530            }
531        }
532        forward_ref_op_assign! { impl BitOrAssign, bitor_assign for Saturating<$t>, $t,
533        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
534        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
535
536        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
537        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
538        const impl BitAnd for Saturating<$t> {
539            type Output = Saturating<$t>;
540
541            #[inline]
542            #[ferrocene::prevalidated]
543            fn bitand(self, other: Saturating<$t>) -> Saturating<$t> {
544                Saturating(self.0 & other.0)
545            }
546        }
547        forward_ref_binop! { impl BitAnd, bitand for Saturating<$t>, Saturating<$t>,
548        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
549        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
550
551        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
552        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
553        const impl BitAndAssign for Saturating<$t> {
554            #[inline]
555            #[ferrocene::prevalidated]
556            fn bitand_assign(&mut self, other: Saturating<$t>) {
557                *self = *self & other;
558            }
559        }
560        forward_ref_op_assign! { impl BitAndAssign, bitand_assign for Saturating<$t>, Saturating<$t>,
561        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
562        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
563
564        #[stable(feature = "saturating_int_assign_impl", since = "1.74.0")]
565        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
566        const impl BitAndAssign<$t> for Saturating<$t> {
567            #[inline]
568            #[ferrocene::prevalidated]
569            fn bitand_assign(&mut self, other: $t) {
570                *self = *self & Saturating(other);
571            }
572        }
573        forward_ref_op_assign! { impl BitAndAssign, bitand_assign for Saturating<$t>, $t,
574        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
575        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
576
577    )*)
578}
579
580saturating_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
581
582macro_rules! saturating_int_impl {
583    ($($t:ty)*) => ($(
584        impl Saturating<$t> {
585            /// Returns the smallest value that can be represented by this integer type.
586            ///
587            /// # Examples
588            ///
589            /// ```
590            /// use std::num::Saturating;
591            ///
592            #[doc = concat!("assert_eq!(<Saturating<", stringify!($t), ">>::MIN, Saturating(", stringify!($t), "::MIN));")]
593            /// ```
594            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
595            pub const MIN: Self = Self(<$t>::MIN);
596
597            /// Returns the largest value that can be represented by this integer type.
598            ///
599            /// # Examples
600            ///
601            /// ```
602            /// use std::num::Saturating;
603            ///
604            #[doc = concat!("assert_eq!(<Saturating<", stringify!($t), ">>::MAX, Saturating(", stringify!($t), "::MAX));")]
605            /// ```
606            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
607            pub const MAX: Self = Self(<$t>::MAX);
608
609            /// Returns the size of this integer type in bits.
610            ///
611            /// # Examples
612            ///
613            /// ```
614            /// use std::num::Saturating;
615            ///
616            #[doc = concat!("assert_eq!(<Saturating<", stringify!($t), ">>::BITS, ", stringify!($t), "::BITS);")]
617            /// ```
618            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
619            pub const BITS: u32 = <$t>::BITS;
620
621            /// Returns the number of ones in the binary representation of `self`.
622            ///
623            /// # Examples
624            ///
625            /// ```
626            /// use std::num::Saturating;
627            ///
628            #[doc = concat!("let n = Saturating(0b01001100", stringify!($t), ");")]
629            ///
630            /// assert_eq!(n.count_ones(), 3);
631            /// ```
632            #[inline]
633            #[doc(alias = "popcount")]
634            #[doc(alias = "popcnt")]
635            #[must_use = "this returns the result of the operation, \
636                          without modifying the original"]
637            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
638            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
639            pub const fn count_ones(self) -> u32 {
640                self.0.count_ones()
641            }
642
643            /// Returns the number of zeros in the binary representation of `self`.
644            ///
645            /// # Examples
646            ///
647            /// ```
648            /// use std::num::Saturating;
649            ///
650            #[doc = concat!("assert_eq!(Saturating(!0", stringify!($t), ").count_zeros(), 0);")]
651            /// ```
652            #[inline]
653            #[must_use = "this returns the result of the operation, \
654                          without modifying the original"]
655            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
656            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
657            pub const fn count_zeros(self) -> u32 {
658                self.0.count_zeros()
659            }
660
661            /// Returns the number of trailing zeros in the binary representation of `self`.
662            ///
663            /// # Examples
664            ///
665            /// ```
666            /// use std::num::Saturating;
667            ///
668            #[doc = concat!("let n = Saturating(0b0101000", stringify!($t), ");")]
669            ///
670            /// assert_eq!(n.trailing_zeros(), 3);
671            /// ```
672            #[inline]
673            #[must_use = "this returns the result of the operation, \
674                          without modifying the original"]
675            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
676            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
677            pub const fn trailing_zeros(self) -> u32 {
678                self.0.trailing_zeros()
679            }
680
681            /// Shifts the bits to the left by a specified amount, `n`,
682            /// saturating the truncated bits to the end of the resulting
683            /// integer.
684            ///
685            /// Please note this isn't the same operation as the `<<` shifting
686            /// operator!
687            ///
688            /// # Examples
689            ///
690            /// ```
691            /// use std::num::Saturating;
692            ///
693            /// let n: Saturating<i64> = Saturating(0x0123456789ABCDEF);
694            /// let m: Saturating<i64> = Saturating(-0x76543210FEDCBA99);
695            ///
696            /// assert_eq!(n.rotate_left(32), m);
697            /// ```
698            #[inline]
699            #[must_use = "this returns the result of the operation, \
700                          without modifying the original"]
701            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
702            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
703            pub const fn rotate_left(self, n: u32) -> Self {
704                Saturating(self.0.rotate_left(n))
705            }
706
707            /// Shifts the bits to the right by a specified amount, `n`,
708            /// saturating the truncated bits to the beginning of the resulting
709            /// integer.
710            ///
711            /// Please note this isn't the same operation as the `>>` shifting
712            /// operator!
713            ///
714            /// # Examples
715            ///
716            /// ```
717            /// use std::num::Saturating;
718            ///
719            /// let n: Saturating<i64> = Saturating(0x0123456789ABCDEF);
720            /// let m: Saturating<i64> = Saturating(-0xFEDCBA987654322);
721            ///
722            /// assert_eq!(n.rotate_right(4), m);
723            /// ```
724            #[inline]
725            #[must_use = "this returns the result of the operation, \
726                          without modifying the original"]
727            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
728            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
729            pub const fn rotate_right(self, n: u32) -> Self {
730                Saturating(self.0.rotate_right(n))
731            }
732
733            /// Reverses the byte order of the integer.
734            ///
735            /// # Examples
736            ///
737            /// ```
738            /// use std::num::Saturating;
739            ///
740            /// let n: Saturating<i16> = Saturating(0b0000000_01010101);
741            /// assert_eq!(n, Saturating(85));
742            ///
743            /// let m = n.swap_bytes();
744            ///
745            /// assert_eq!(m, Saturating(0b01010101_00000000));
746            /// assert_eq!(m, Saturating(21760));
747            /// ```
748            #[inline]
749            #[must_use = "this returns the result of the operation, \
750                          without modifying the original"]
751            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
752            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
753            pub const fn swap_bytes(self) -> Self {
754                Saturating(self.0.swap_bytes())
755            }
756
757            /// Reverses the bit pattern of the integer.
758            ///
759            /// # Examples
760            ///
761            /// Please note that this example is shared among integer types, which is why `i16`
762            /// is used.
763            ///
764            /// ```
765            /// use std::num::Saturating;
766            ///
767            /// let n = Saturating(0b0000000_01010101i16);
768            /// assert_eq!(n, Saturating(85));
769            ///
770            /// let m = n.reverse_bits();
771            ///
772            /// assert_eq!(m.0 as u16, 0b10101010_00000000);
773            /// assert_eq!(m, Saturating(-22016));
774            /// ```
775            #[inline]
776            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
777            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
778            #[must_use = "this returns the result of the operation, \
779                          without modifying the original"]
780            pub const fn reverse_bits(self) -> Self {
781                Saturating(self.0.reverse_bits())
782            }
783
784            /// Converts an integer from big endian to the target's endianness.
785            ///
786            /// On big endian this is a no-op. On little endian the bytes are
787            /// swapped.
788            ///
789            /// # Examples
790            ///
791            /// ```
792            /// use std::num::Saturating;
793            ///
794            #[doc = concat!("let n = Saturating(0x1A", stringify!($t), ");")]
795            ///
796            /// if cfg!(target_endian = "big") {
797            #[doc = concat!("    assert_eq!(<Saturating<", stringify!($t), ">>::from_be(n), n)")]
798            /// } else {
799            #[doc = concat!("    assert_eq!(<Saturating<", stringify!($t), ">>::from_be(n), n.swap_bytes())")]
800            /// }
801            /// ```
802            #[inline]
803            #[must_use]
804            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
805            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
806            pub const fn from_be(x: Self) -> Self {
807                Saturating(<$t>::from_be(x.0))
808            }
809
810            /// Converts an integer from little endian to the target's endianness.
811            ///
812            /// On little endian this is a no-op. On big endian the bytes are
813            /// swapped.
814            ///
815            /// # Examples
816            ///
817            /// ```
818            /// use std::num::Saturating;
819            ///
820            #[doc = concat!("let n = Saturating(0x1A", stringify!($t), ");")]
821            ///
822            /// if cfg!(target_endian = "little") {
823            #[doc = concat!("    assert_eq!(<Saturating<", stringify!($t), ">>::from_le(n), n)")]
824            /// } else {
825            #[doc = concat!("    assert_eq!(<Saturating<", stringify!($t), ">>::from_le(n), n.swap_bytes())")]
826            /// }
827            /// ```
828            #[inline]
829            #[must_use]
830            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
831            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
832            pub const fn from_le(x: Self) -> Self {
833                Saturating(<$t>::from_le(x.0))
834            }
835
836            /// Converts `self` to big endian from the target's endianness.
837            ///
838            /// On big endian this is a no-op. On little endian the bytes are
839            /// swapped.
840            ///
841            /// # Examples
842            ///
843            /// ```
844            /// use std::num::Saturating;
845            ///
846            #[doc = concat!("let n = Saturating(0x1A", stringify!($t), ");")]
847            ///
848            /// if cfg!(target_endian = "big") {
849            ///     assert_eq!(n.to_be(), n)
850            /// } else {
851            ///     assert_eq!(n.to_be(), n.swap_bytes())
852            /// }
853            /// ```
854            #[inline]
855            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
856            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
857            #[must_use = "this returns the result of the operation, \
858                          without modifying the original"]
859            pub const fn to_be(self) -> Self {
860                Saturating(self.0.to_be())
861            }
862
863            /// Converts `self` to little endian from the target's endianness.
864            ///
865            /// On little endian this is a no-op. On big endian the bytes are
866            /// swapped.
867            ///
868            /// # Examples
869            ///
870            /// ```
871            /// use std::num::Saturating;
872            ///
873            #[doc = concat!("let n = Saturating(0x1A", stringify!($t), ");")]
874            ///
875            /// if cfg!(target_endian = "little") {
876            ///     assert_eq!(n.to_le(), n)
877            /// } else {
878            ///     assert_eq!(n.to_le(), n.swap_bytes())
879            /// }
880            /// ```
881            #[inline]
882            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
883            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
884            #[must_use = "this returns the result of the operation, \
885                          without modifying the original"]
886            pub const fn to_le(self) -> Self {
887                Saturating(self.0.to_le())
888            }
889
890            /// Raises self to the power of `exp`, using exponentiation by squaring.
891            ///
892            /// # Examples
893            ///
894            /// ```
895            /// use std::num::Saturating;
896            ///
897            #[doc = concat!("assert_eq!(Saturating(3", stringify!($t), ").pow(4), Saturating(81));")]
898            /// ```
899            ///
900            /// Results that are too large are saturated:
901            ///
902            /// ```
903            /// use std::num::Saturating;
904            ///
905            /// assert_eq!(Saturating(3i8).pow(5), Saturating(127));
906            /// assert_eq!(Saturating(3i8).pow(6), Saturating(127));
907            /// ```
908            #[inline]
909            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
910            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
911            #[must_use = "this returns the result of the operation, \
912                          without modifying the original"]
913            pub const fn pow(self, exp: u32) -> Self {
914                Saturating(self.0.saturating_pow(exp))
915            }
916        }
917    )*)
918}
919
920saturating_int_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
921
922macro_rules! saturating_int_impl_signed {
923    ($($t:ty)*) => ($(
924        impl Saturating<$t> {
925            /// Returns the number of leading zeros in the binary representation of `self`.
926            ///
927            /// # Examples
928            ///
929            /// ```
930            /// use std::num::Saturating;
931            ///
932            #[doc = concat!("let n = Saturating(", stringify!($t), "::MAX >> 2);")]
933            ///
934            /// assert_eq!(n.leading_zeros(), 3);
935            /// ```
936            #[inline]
937            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
938            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
939            #[must_use = "this returns the result of the operation, \
940                          without modifying the original"]
941            pub const fn leading_zeros(self) -> u32 {
942                self.0.leading_zeros()
943            }
944
945            /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self == MIN`
946            /// instead of overflowing.
947            ///
948            /// # Examples
949            ///
950            /// ```
951            /// use std::num::Saturating;
952            ///
953            #[doc = concat!("assert_eq!(Saturating(100", stringify!($t), ").abs(), Saturating(100));")]
954            #[doc = concat!("assert_eq!(Saturating(-100", stringify!($t), ").abs(), Saturating(100));")]
955            #[doc = concat!("assert_eq!(Saturating(", stringify!($t), "::MIN).abs(), Saturating((", stringify!($t), "::MIN + 1).abs()));")]
956            #[doc = concat!("assert_eq!(Saturating(", stringify!($t), "::MIN).abs(), Saturating(", stringify!($t), "::MIN.saturating_abs()));")]
957            #[doc = concat!("assert_eq!(Saturating(", stringify!($t), "::MIN).abs(), Saturating(", stringify!($t), "::MAX));")]
958            /// ```
959            #[inline]
960            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
961            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
962            #[must_use = "this returns the result of the operation, \
963                          without modifying the original"]
964            pub const fn abs(self) -> Saturating<$t> {
965                Saturating(self.0.saturating_abs())
966            }
967
968            /// Returns a number representing sign of `self`.
969            ///
970            ///  - `0` if the number is zero
971            ///  - `1` if the number is positive
972            ///  - `-1` if the number is negative
973            ///
974            /// # Examples
975            ///
976            /// ```
977            /// use std::num::Saturating;
978            ///
979            #[doc = concat!("assert_eq!(Saturating(10", stringify!($t), ").signum(), Saturating(1));")]
980            #[doc = concat!("assert_eq!(Saturating(0", stringify!($t), ").signum(), Saturating(0));")]
981            #[doc = concat!("assert_eq!(Saturating(-10", stringify!($t), ").signum(), Saturating(-1));")]
982            /// ```
983            #[inline]
984            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
985            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
986            #[must_use = "this returns the result of the operation, \
987                          without modifying the original"]
988            pub const fn signum(self) -> Saturating<$t> {
989                Saturating(self.0.signum())
990            }
991
992            /// Returns `true` if `self` is positive and `false` if the number is zero or
993            /// negative.
994            ///
995            /// # Examples
996            ///
997            /// ```
998            /// use std::num::Saturating;
999            ///
1000            #[doc = concat!("assert!(Saturating(10", stringify!($t), ").is_positive());")]
1001            #[doc = concat!("assert!(!Saturating(-10", stringify!($t), ").is_positive());")]
1002            /// ```
1003            #[must_use]
1004            #[inline]
1005            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
1006            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
1007            pub const fn is_positive(self) -> bool {
1008                self.0.is_positive()
1009            }
1010
1011            /// Returns `true` if `self` is negative and `false` if the number is zero or
1012            /// positive.
1013            ///
1014            /// # Examples
1015            ///
1016            /// ```
1017            /// use std::num::Saturating;
1018            ///
1019            #[doc = concat!("assert!(Saturating(-10", stringify!($t), ").is_negative());")]
1020            #[doc = concat!("assert!(!Saturating(10", stringify!($t), ").is_negative());")]
1021            /// ```
1022            #[must_use]
1023            #[inline]
1024            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
1025            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
1026            pub const fn is_negative(self) -> bool {
1027                self.0.is_negative()
1028            }
1029        }
1030
1031        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
1032        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1033        const impl Neg for Saturating<$t> {
1034            type Output = Self;
1035            #[inline]
1036            #[ferrocene::prevalidated]
1037            fn neg(self) -> Self {
1038                Saturating(self.0.saturating_neg())
1039            }
1040        }
1041        forward_ref_unop! { impl Neg, neg for Saturating<$t>,
1042        #[stable(feature = "saturating_int_impl", since = "1.74.0")]
1043        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
1044    )*)
1045}
1046
1047saturating_int_impl_signed! { isize i8 i16 i32 i64 i128 }
1048
1049macro_rules! saturating_int_impl_unsigned {
1050    ($($t:ty)*) => ($(
1051        impl Saturating<$t> {
1052            /// Returns the number of leading zeros in the binary representation of `self`.
1053            ///
1054            /// # Examples
1055            ///
1056            /// ```
1057            /// use std::num::Saturating;
1058            ///
1059            #[doc = concat!("let n = Saturating(", stringify!($t), "::MAX >> 2);")]
1060            ///
1061            /// assert_eq!(n.leading_zeros(), 2);
1062            /// ```
1063            #[inline]
1064            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
1065            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
1066            #[must_use = "this returns the result of the operation, \
1067                          without modifying the original"]
1068            pub const fn leading_zeros(self) -> u32 {
1069                self.0.leading_zeros()
1070            }
1071
1072            /// Returns `true` if and only if `self == 2^k` for some `k`.
1073            ///
1074            /// # Examples
1075            ///
1076            /// ```
1077            /// use std::num::Saturating;
1078            ///
1079            #[doc = concat!("assert!(Saturating(16", stringify!($t), ").is_power_of_two());")]
1080            #[doc = concat!("assert!(!Saturating(10", stringify!($t), ").is_power_of_two());")]
1081            /// ```
1082            #[must_use]
1083            #[inline]
1084            #[rustc_const_stable(feature = "saturating_int_impl", since = "1.74.0")]
1085            #[stable(feature = "saturating_int_impl", since = "1.74.0")]
1086            pub const fn is_power_of_two(self) -> bool {
1087                self.0.is_power_of_two()
1088            }
1089
1090        }
1091    )*)
1092}
1093
1094saturating_int_impl_unsigned! { usize u8 u16 u32 u64 u128 }
1095
1096// Related to potential Shl and ShlAssign implementation
1097//
1098// mod shift_max {
1099//     #![allow(non_upper_case_globals)]
1100//
1101//     #[cfg(target_pointer_width = "16")]
1102//     mod platform {
1103//         pub const usize: u32 = super::u16;
1104//         pub const isize: u32 = super::i16;
1105//     }
1106//
1107//     #[cfg(target_pointer_width = "32")]
1108//     mod platform {
1109//         pub const usize: u32 = super::u32;
1110//         pub const isize: u32 = super::i32;
1111//     }
1112//
1113//     #[cfg(target_pointer_width = "64")]
1114//     mod platform {
1115//         pub const usize: u32 = super::u64;
1116//         pub const isize: u32 = super::i64;
1117//     }
1118//
1119//     pub const i8: u32 = (1 << 3) - 1;
1120//     pub const i16: u32 = (1 << 4) - 1;
1121//     pub const i32: u32 = (1 << 5) - 1;
1122//     pub const i64: u32 = (1 << 6) - 1;
1123//     pub const i128: u32 = (1 << 7) - 1;
1124//     pub use self::platform::isize;
1125//
1126//     pub const u8: u32 = i8;
1127//     pub const u16: u32 = i16;
1128//     pub const u32: u32 = i32;
1129//     pub const u64: u32 = i64;
1130//     pub const u128: u32 = i128;
1131//     pub use self::platform::usize;
1132// }