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