]> git.lizzy.rs Git - rust.git/blob - library/core/src/num/nonzero.rs
Auto merge of #102565 - jyn514:refactor-build-manifest, r=Mark-Simulacrum
[rust.git] / library / core / src / num / nonzero.rs
1 //! Definitions of integer that is known not to equal zero.
2
3 use crate::fmt;
4 use crate::ops::{BitOr, BitOrAssign, Div, Rem};
5 use crate::str::FromStr;
6
7 use super::from_str_radix;
8 use super::{IntErrorKind, ParseIntError};
9 use crate::intrinsics;
10
11 macro_rules! impl_nonzero_fmt {
12     ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
13         $(
14             #[$stability]
15             impl fmt::$Trait for $Ty {
16                 #[inline]
17                 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18                     self.get().fmt(f)
19                 }
20             }
21         )+
22     }
23 }
24
25 macro_rules! nonzero_integers {
26     ( $( #[$stability: meta] #[$const_new_unchecked_stability: meta] $Ty: ident($Int: ty); )+ ) => {
27         $(
28             /// An integer that is known not to equal zero.
29             ///
30             /// This enables some memory layout optimization.
31             #[doc = concat!("For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:")]
32             ///
33             /// ```rust
34             /// use std::mem::size_of;
35             #[doc = concat!("assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int), ">());")]
36             /// ```
37             #[$stability]
38             #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
39             #[repr(transparent)]
40             #[rustc_layout_scalar_valid_range_start(1)]
41             #[rustc_nonnull_optimization_guaranteed]
42             #[rustc_diagnostic_item = stringify!($Ty)]
43             pub struct $Ty($Int);
44
45             impl $Ty {
46                 /// Creates a non-zero without checking whether the value is non-zero.
47                 /// This results in undefined behaviour if the value is zero.
48                 ///
49                 /// # Safety
50                 ///
51                 /// The value must not be zero.
52                 #[$stability]
53                 #[$const_new_unchecked_stability]
54                 #[must_use]
55                 #[inline]
56                 pub const unsafe fn new_unchecked(n: $Int) -> Self {
57                     // SAFETY: this is guaranteed to be safe by the caller.
58                     unsafe {
59                         core::intrinsics::assert_unsafe_precondition!(
60                             concat!(stringify!($Ty), "::new_unchecked requires a non-zero argument"),
61                             (n: $Int) => n != 0
62                         );
63                         Self(n)
64                     }
65                 }
66
67                 /// Creates a non-zero if the given value is not zero.
68                 #[$stability]
69                 #[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
70                 #[must_use]
71                 #[inline]
72                 pub const fn new(n: $Int) -> Option<Self> {
73                     if n != 0 {
74                         // SAFETY: we just checked that there's no `0`
75                         Some(unsafe { Self(n) })
76                     } else {
77                         None
78                     }
79                 }
80
81                 /// Returns the value as a primitive type.
82                 #[$stability]
83                 #[inline]
84                 #[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
85                 pub const fn get(self) -> $Int {
86                     self.0
87                 }
88
89             }
90
91             #[stable(feature = "from_nonzero", since = "1.31.0")]
92             #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")]
93             impl const From<$Ty> for $Int {
94                 #[doc = concat!("Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`")]
95                 #[inline]
96                 fn from(nonzero: $Ty) -> Self {
97                     nonzero.0
98                 }
99             }
100
101             #[stable(feature = "nonzero_bitor", since = "1.45.0")]
102             #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
103             impl const BitOr for $Ty {
104                 type Output = Self;
105                 #[inline]
106                 fn bitor(self, rhs: Self) -> Self::Output {
107                     // SAFETY: since `self` and `rhs` are both nonzero, the
108                     // result of the bitwise-or will be nonzero.
109                     unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
110                 }
111             }
112
113             #[stable(feature = "nonzero_bitor", since = "1.45.0")]
114             #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
115             impl const BitOr<$Int> for $Ty {
116                 type Output = Self;
117                 #[inline]
118                 fn bitor(self, rhs: $Int) -> Self::Output {
119                     // SAFETY: since `self` is nonzero, the result of the
120                     // bitwise-or will be nonzero regardless of the value of
121                     // `rhs`.
122                     unsafe { $Ty::new_unchecked(self.get() | rhs) }
123                 }
124             }
125
126             #[stable(feature = "nonzero_bitor", since = "1.45.0")]
127             #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
128             impl const BitOr<$Ty> for $Int {
129                 type Output = $Ty;
130                 #[inline]
131                 fn bitor(self, rhs: $Ty) -> Self::Output {
132                     // SAFETY: since `rhs` is nonzero, the result of the
133                     // bitwise-or will be nonzero regardless of the value of
134                     // `self`.
135                     unsafe { $Ty::new_unchecked(self | rhs.get()) }
136                 }
137             }
138
139             #[stable(feature = "nonzero_bitor", since = "1.45.0")]
140             #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
141             impl const BitOrAssign for $Ty {
142                 #[inline]
143                 fn bitor_assign(&mut self, rhs: Self) {
144                     *self = *self | rhs;
145                 }
146             }
147
148             #[stable(feature = "nonzero_bitor", since = "1.45.0")]
149             #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
150             impl const BitOrAssign<$Int> for $Ty {
151                 #[inline]
152                 fn bitor_assign(&mut self, rhs: $Int) {
153                     *self = *self | rhs;
154                 }
155             }
156
157             impl_nonzero_fmt! {
158                 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
159             }
160         )+
161     }
162 }
163
164 nonzero_integers! {
165     #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
166     #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
167     #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
168     #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
169     #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
170     #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
171     #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
172     #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
173     #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
174     #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
175     #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
176     #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
177 }
178
179 macro_rules! from_str_radix_nzint_impl {
180     ($($t:ty)*) => {$(
181         #[stable(feature = "nonzero_parse", since = "1.35.0")]
182         impl FromStr for $t {
183             type Err = ParseIntError;
184             fn from_str(src: &str) -> Result<Self, Self::Err> {
185                 Self::new(from_str_radix(src, 10)?)
186                     .ok_or(ParseIntError {
187                         kind: IntErrorKind::Zero
188                     })
189             }
190         }
191     )*}
192 }
193
194 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
195 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
196
197 macro_rules! nonzero_leading_trailing_zeros {
198     ( $( $Ty: ident($Uint: ty) , $LeadingTestExpr:expr ;)+ ) => {
199         $(
200             impl $Ty {
201                 /// Returns the number of leading zeros in the binary representation of `self`.
202                 ///
203                 /// On many architectures, this function can perform better than `leading_zeros()` on the underlying integer type, as special handling of zero can be avoided.
204                 ///
205                 /// # Examples
206                 ///
207                 /// Basic usage:
208                 ///
209                 /// ```
210                 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(", stringify!($LeadingTestExpr), ").unwrap();")]
211                 ///
212                 /// assert_eq!(n.leading_zeros(), 0);
213                 /// ```
214                 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
215                 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
216                 #[must_use = "this returns the result of the operation, \
217                               without modifying the original"]
218                 #[inline]
219                 pub const fn leading_zeros(self) -> u32 {
220                     // SAFETY: since `self` cannot be zero, it is safe to call `ctlz_nonzero`.
221                     unsafe { intrinsics::ctlz_nonzero(self.0 as $Uint) as u32 }
222                 }
223
224                 /// Returns the number of trailing zeros in the binary representation
225                 /// of `self`.
226                 ///
227                 /// On many architectures, this function can perform better than `trailing_zeros()` on the underlying integer type, as special handling of zero can be avoided.
228                 ///
229                 /// # Examples
230                 ///
231                 /// Basic usage:
232                 ///
233                 /// ```
234                 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(0b0101000).unwrap();")]
235                 ///
236                 /// assert_eq!(n.trailing_zeros(), 3);
237                 /// ```
238                 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
239                 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
240                 #[must_use = "this returns the result of the operation, \
241                               without modifying the original"]
242                 #[inline]
243                 pub const fn trailing_zeros(self) -> u32 {
244                     // SAFETY: since `self` cannot be zero, it is safe to call `cttz_nonzero`.
245                     unsafe { intrinsics::cttz_nonzero(self.0 as $Uint) as u32 }
246                 }
247
248             }
249         )+
250     }
251 }
252
253 nonzero_leading_trailing_zeros! {
254     NonZeroU8(u8), u8::MAX;
255     NonZeroU16(u16), u16::MAX;
256     NonZeroU32(u32), u32::MAX;
257     NonZeroU64(u64), u64::MAX;
258     NonZeroU128(u128), u128::MAX;
259     NonZeroUsize(usize), usize::MAX;
260     NonZeroI8(u8), -1i8;
261     NonZeroI16(u16), -1i16;
262     NonZeroI32(u32), -1i32;
263     NonZeroI64(u64), -1i64;
264     NonZeroI128(u128), -1i128;
265     NonZeroIsize(usize), -1isize;
266 }
267
268 macro_rules! nonzero_integers_div {
269     ( $( $Ty: ident($Int: ty); )+ ) => {
270         $(
271             #[stable(feature = "nonzero_div", since = "1.51.0")]
272             #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
273             impl const Div<$Ty> for $Int {
274                 type Output = $Int;
275                 /// This operation rounds towards zero,
276                 /// truncating any fractional part of the exact result, and cannot panic.
277                 #[inline]
278                 fn div(self, other: $Ty) -> $Int {
279                     // SAFETY: div by zero is checked because `other` is a nonzero,
280                     // and MIN/-1 is checked because `self` is an unsigned int.
281                     unsafe { crate::intrinsics::unchecked_div(self, other.get()) }
282                 }
283             }
284
285             #[stable(feature = "nonzero_div", since = "1.51.0")]
286             #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
287             impl const Rem<$Ty> for $Int {
288                 type Output = $Int;
289                 /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
290                 #[inline]
291                 fn rem(self, other: $Ty) -> $Int {
292                     // SAFETY: rem by zero is checked because `other` is a nonzero,
293                     // and MIN/-1 is checked because `self` is an unsigned int.
294                     unsafe { crate::intrinsics::unchecked_rem(self, other.get()) }
295                 }
296             }
297         )+
298     }
299 }
300
301 nonzero_integers_div! {
302     NonZeroU8(u8);
303     NonZeroU16(u16);
304     NonZeroU32(u32);
305     NonZeroU64(u64);
306     NonZeroU128(u128);
307     NonZeroUsize(usize);
308 }
309
310 // A bunch of methods for unsigned nonzero types only.
311 macro_rules! nonzero_unsigned_operations {
312     ( $( $Ty: ident($Int: ident); )+ ) => {
313         $(
314             impl $Ty {
315                 /// Adds an unsigned integer to a non-zero value.
316                 /// Checks for overflow and returns [`None`] on overflow.
317                 /// As a consequence, the result cannot wrap to zero.
318                 ///
319                 ///
320                 /// # Examples
321                 ///
322                 /// ```
323                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
324                 ///
325                 /// # fn main() { test().unwrap(); }
326                 /// # fn test() -> Option<()> {
327                 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
328                 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
329                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
330                                 stringify!($Int), "::MAX)?;")]
331                 ///
332                 /// assert_eq!(Some(two), one.checked_add(1));
333                 /// assert_eq!(None, max.checked_add(1));
334                 /// # Some(())
335                 /// # }
336                 /// ```
337                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
338                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
339                 #[must_use = "this returns the result of the operation, \
340                               without modifying the original"]
341                 #[inline]
342                 pub const fn checked_add(self, other: $Int) -> Option<$Ty> {
343                     if let Some(result) = self.get().checked_add(other) {
344                         // SAFETY: $Int::checked_add returns None on overflow
345                         // so the result cannot be zero.
346                         Some(unsafe { $Ty::new_unchecked(result) })
347                     } else {
348                         None
349                     }
350                 }
351
352                 /// Adds an unsigned integer to a non-zero value.
353                 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
354                 ///
355                 /// # Examples
356                 ///
357                 /// ```
358                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
359                 ///
360                 /// # fn main() { test().unwrap(); }
361                 /// # fn test() -> Option<()> {
362                 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
363                 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
364                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
365                                 stringify!($Int), "::MAX)?;")]
366                 ///
367                 /// assert_eq!(two, one.saturating_add(1));
368                 /// assert_eq!(max, max.saturating_add(1));
369                 /// # Some(())
370                 /// # }
371                 /// ```
372                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
373                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
374                 #[must_use = "this returns the result of the operation, \
375                               without modifying the original"]
376                 #[inline]
377                 pub const fn saturating_add(self, other: $Int) -> $Ty {
378                     // SAFETY: $Int::saturating_add returns $Int::MAX on overflow
379                     // so the result cannot be zero.
380                     unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
381                 }
382
383                 /// Adds an unsigned integer to a non-zero value,
384                 /// assuming overflow cannot occur.
385                 /// Overflow is unchecked, and it is undefined behaviour to overflow
386                 /// *even if the result would wrap to a non-zero value*.
387                 /// The behaviour is undefined as soon as
388                 #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
389                 ///
390                 /// # Examples
391                 ///
392                 /// ```
393                 /// #![feature(nonzero_ops)]
394                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
395                 ///
396                 /// # fn main() { test().unwrap(); }
397                 /// # fn test() -> Option<()> {
398                 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
399                 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
400                 ///
401                 /// assert_eq!(two, unsafe { one.unchecked_add(1) });
402                 /// # Some(())
403                 /// # }
404                 /// ```
405                 #[unstable(feature = "nonzero_ops", issue = "84186")]
406                 #[must_use = "this returns the result of the operation, \
407                               without modifying the original"]
408                 #[inline]
409                 pub const unsafe fn unchecked_add(self, other: $Int) -> $Ty {
410                     // SAFETY: The caller ensures there is no overflow.
411                     unsafe { $Ty::new_unchecked(self.get().unchecked_add(other)) }
412                 }
413
414                 /// Returns the smallest power of two greater than or equal to n.
415                 /// Checks for overflow and returns [`None`]
416                 /// if the next power of two is greater than the type’s maximum value.
417                 /// As a consequence, the result cannot wrap to zero.
418                 ///
419                 /// # Examples
420                 ///
421                 /// ```
422                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
423                 ///
424                 /// # fn main() { test().unwrap(); }
425                 /// # fn test() -> Option<()> {
426                 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
427                 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
428                 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
429                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
430                                 stringify!($Int), "::MAX)?;")]
431                 ///
432                 /// assert_eq!(Some(two), two.checked_next_power_of_two() );
433                 /// assert_eq!(Some(four), three.checked_next_power_of_two() );
434                 /// assert_eq!(None, max.checked_next_power_of_two() );
435                 /// # Some(())
436                 /// # }
437                 /// ```
438                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
439                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
440                 #[must_use = "this returns the result of the operation, \
441                               without modifying the original"]
442                 #[inline]
443                 pub const fn checked_next_power_of_two(self) -> Option<$Ty> {
444                     if let Some(nz) = self.get().checked_next_power_of_two() {
445                         // SAFETY: The next power of two is positive
446                         // and overflow is checked.
447                         Some(unsafe { $Ty::new_unchecked(nz) })
448                     } else {
449                         None
450                     }
451                 }
452
453                 /// Returns the base 2 logarithm of the number, rounded down.
454                 ///
455                 /// This is the same operation as
456                 #[doc = concat!("[`", stringify!($Int), "::ilog2`],")]
457                 /// except that it has no failure cases to worry about
458                 /// since this value can never be zero.
459                 ///
460                 /// # Examples
461                 ///
462                 /// ```
463                 /// #![feature(int_log)]
464                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
465                 ///
466                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(7).unwrap().ilog2(), 2);")]
467                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(8).unwrap().ilog2(), 3);")]
468                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(9).unwrap().ilog2(), 3);")]
469                 /// ```
470                 #[unstable(feature = "int_log", issue = "70887")]
471                 #[must_use = "this returns the result of the operation, \
472                               without modifying the original"]
473                 #[inline]
474                 pub const fn ilog2(self) -> u32 {
475                     Self::BITS - 1 - self.leading_zeros()
476                 }
477
478                 /// Returns the base 10 logarithm of the number, rounded down.
479                 ///
480                 /// This is the same operation as
481                 #[doc = concat!("[`", stringify!($Int), "::ilog10`],")]
482                 /// except that it has no failure cases to worry about
483                 /// since this value can never be zero.
484                 ///
485                 /// # Examples
486                 ///
487                 /// ```
488                 /// #![feature(int_log)]
489                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
490                 ///
491                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(99).unwrap().ilog10(), 1);")]
492                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(100).unwrap().ilog10(), 2);")]
493                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(101).unwrap().ilog10(), 2);")]
494                 /// ```
495                 #[unstable(feature = "int_log", issue = "70887")]
496                 #[must_use = "this returns the result of the operation, \
497                               without modifying the original"]
498                 #[inline]
499                 pub const fn ilog10(self) -> u32 {
500                     super::int_log10::$Int(self.0)
501                 }
502             }
503         )+
504     }
505 }
506
507 nonzero_unsigned_operations! {
508     NonZeroU8(u8);
509     NonZeroU16(u16);
510     NonZeroU32(u32);
511     NonZeroU64(u64);
512     NonZeroU128(u128);
513     NonZeroUsize(usize);
514 }
515
516 // A bunch of methods for signed nonzero types only.
517 macro_rules! nonzero_signed_operations {
518     ( $( $Ty: ident($Int: ty) -> $Uty: ident($Uint: ty); )+ ) => {
519         $(
520             impl $Ty {
521                 /// Computes the absolute value of self.
522                 #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
523                 /// for documentation on overflow behaviour.
524                 ///
525                 /// # Example
526                 ///
527                 /// ```
528                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
529                 ///
530                 /// # fn main() { test().unwrap(); }
531                 /// # fn test() -> Option<()> {
532                 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
533                 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
534                 ///
535                 /// assert_eq!(pos, pos.abs());
536                 /// assert_eq!(pos, neg.abs());
537                 /// # Some(())
538                 /// # }
539                 /// ```
540                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
541                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
542                 #[must_use = "this returns the result of the operation, \
543                               without modifying the original"]
544                 #[inline]
545                 pub const fn abs(self) -> $Ty {
546                     // SAFETY: This cannot overflow to zero.
547                     unsafe { $Ty::new_unchecked(self.get().abs()) }
548                 }
549
550                 /// Checked absolute value.
551                 /// Checks for overflow and returns [`None`] if
552                 #[doc = concat!("`self == ", stringify!($Int), "::MIN`.")]
553                 /// The result cannot be zero.
554                 ///
555                 /// # Example
556                 ///
557                 /// ```
558                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
559                 ///
560                 /// # fn main() { test().unwrap(); }
561                 /// # fn test() -> Option<()> {
562                 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
563                 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
564                 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
565                                 stringify!($Int), "::MIN)?;")]
566                 ///
567                 /// assert_eq!(Some(pos), neg.checked_abs());
568                 /// assert_eq!(None, min.checked_abs());
569                 /// # Some(())
570                 /// # }
571                 /// ```
572                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
573                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
574                 #[must_use = "this returns the result of the operation, \
575                               without modifying the original"]
576                 #[inline]
577                 pub const fn checked_abs(self) -> Option<$Ty> {
578                     if let Some(nz) = self.get().checked_abs() {
579                         // SAFETY: absolute value of nonzero cannot yield zero values.
580                         Some(unsafe { $Ty::new_unchecked(nz) })
581                     } else {
582                         None
583                     }
584                 }
585
586                 /// Computes the absolute value of self,
587                 /// with overflow information, see
588                 #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
589                 ///
590                 /// # Example
591                 ///
592                 /// ```
593                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
594                 ///
595                 /// # fn main() { test().unwrap(); }
596                 /// # fn test() -> Option<()> {
597                 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
598                 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
599                 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
600                                 stringify!($Int), "::MIN)?;")]
601                 ///
602                 /// assert_eq!((pos, false), pos.overflowing_abs());
603                 /// assert_eq!((pos, false), neg.overflowing_abs());
604                 /// assert_eq!((min, true), min.overflowing_abs());
605                 /// # Some(())
606                 /// # }
607                 /// ```
608                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
609                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
610                 #[must_use = "this returns the result of the operation, \
611                               without modifying the original"]
612                 #[inline]
613                 pub const fn overflowing_abs(self) -> ($Ty, bool) {
614                     let (nz, flag) = self.get().overflowing_abs();
615                     (
616                         // SAFETY: absolute value of nonzero cannot yield zero values.
617                         unsafe { $Ty::new_unchecked(nz) },
618                         flag,
619                     )
620                 }
621
622                 /// Saturating absolute value, see
623                 #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
624                 ///
625                 /// # Example
626                 ///
627                 /// ```
628                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
629                 ///
630                 /// # fn main() { test().unwrap(); }
631                 /// # fn test() -> Option<()> {
632                 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
633                 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
634                 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
635                                 stringify!($Int), "::MIN)?;")]
636                 #[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
637                                 stringify!($Int), "::MIN + 1)?;")]
638                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
639                                 stringify!($Int), "::MAX)?;")]
640                 ///
641                 /// assert_eq!(pos, pos.saturating_abs());
642                 /// assert_eq!(pos, neg.saturating_abs());
643                 /// assert_eq!(max, min.saturating_abs());
644                 /// assert_eq!(max, min_plus.saturating_abs());
645                 /// # Some(())
646                 /// # }
647                 /// ```
648                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
649                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
650                 #[must_use = "this returns the result of the operation, \
651                               without modifying the original"]
652                 #[inline]
653                 pub const fn saturating_abs(self) -> $Ty {
654                     // SAFETY: absolute value of nonzero cannot yield zero values.
655                     unsafe { $Ty::new_unchecked(self.get().saturating_abs()) }
656                 }
657
658                 /// Wrapping absolute value, see
659                 #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
660                 ///
661                 /// # Example
662                 ///
663                 /// ```
664                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
665                 ///
666                 /// # fn main() { test().unwrap(); }
667                 /// # fn test() -> Option<()> {
668                 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
669                 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
670                 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
671                                 stringify!($Int), "::MIN)?;")]
672                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
673                                 stringify!($Int), "::MAX)?;")]
674                 ///
675                 /// assert_eq!(pos, pos.wrapping_abs());
676                 /// assert_eq!(pos, neg.wrapping_abs());
677                 /// assert_eq!(min, min.wrapping_abs());
678                 /// # // FIXME: add once Neg is implemented?
679                 /// # // assert_eq!(max, (-max).wrapping_abs());
680                 /// # Some(())
681                 /// # }
682                 /// ```
683                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
684                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
685                 #[must_use = "this returns the result of the operation, \
686                               without modifying the original"]
687                 #[inline]
688                 pub const fn wrapping_abs(self) -> $Ty {
689                     // SAFETY: absolute value of nonzero cannot yield zero values.
690                     unsafe { $Ty::new_unchecked(self.get().wrapping_abs()) }
691                 }
692
693                 /// Computes the absolute value of self
694                 /// without any wrapping or panicking.
695                 ///
696                 /// # Example
697                 ///
698                 /// ```
699                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
700                 #[doc = concat!("# use std::num::", stringify!($Uty), ";")]
701                 ///
702                 /// # fn main() { test().unwrap(); }
703                 /// # fn test() -> Option<()> {
704                 #[doc = concat!("let u_pos = ", stringify!($Uty), "::new(1)?;")]
705                 #[doc = concat!("let i_pos = ", stringify!($Ty), "::new(1)?;")]
706                 #[doc = concat!("let i_neg = ", stringify!($Ty), "::new(-1)?;")]
707                 #[doc = concat!("let i_min = ", stringify!($Ty), "::new(",
708                                 stringify!($Int), "::MIN)?;")]
709                 #[doc = concat!("let u_max = ", stringify!($Uty), "::new(",
710                                 stringify!($Uint), "::MAX / 2 + 1)?;")]
711                 ///
712                 /// assert_eq!(u_pos, i_pos.unsigned_abs());
713                 /// assert_eq!(u_pos, i_neg.unsigned_abs());
714                 /// assert_eq!(u_max, i_min.unsigned_abs());
715                 /// # Some(())
716                 /// # }
717                 /// ```
718                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
719                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
720                 #[must_use = "this returns the result of the operation, \
721                               without modifying the original"]
722                 #[inline]
723                 pub const fn unsigned_abs(self) -> $Uty {
724                     // SAFETY: absolute value of nonzero cannot yield zero values.
725                     unsafe { $Uty::new_unchecked(self.get().unsigned_abs()) }
726                 }
727
728                 /// Returns `true` if `self` is negative and `false` if the
729                 /// number is positive.
730                 ///
731                 /// # Example
732                 ///
733                 /// ```
734                 /// #![feature(nonzero_negation_ops)]
735                 ///
736                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
737                 /// # fn main() { test().unwrap(); }
738                 /// # fn test() -> Option<()> {
739                 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
740                 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
741                 ///
742                 /// assert!(neg_five.is_negative());
743                 /// assert!(!pos_five.is_negative());
744                 /// # Some(())
745                 /// # }
746                 /// ```
747                 #[must_use]
748                 #[inline]
749                 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
750                 pub const fn is_negative(self) -> bool {
751                     self.get().is_negative()
752                 }
753
754                 /// Checked negation. Computes `-self`, returning `None` if `self == i32::MIN`.
755                 ///
756                 /// # Example
757                 ///
758                 /// ```
759                 /// #![feature(nonzero_negation_ops)]
760                 ///
761                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
762                 /// # fn main() { test().unwrap(); }
763                 /// # fn test() -> Option<()> {
764                 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
765                 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
766                 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
767                                 stringify!($Int), "::MIN)?;")]
768                 ///
769                 /// assert_eq!(pos_five.checked_neg(), Some(neg_five));
770                 /// assert_eq!(min.checked_neg(), None);
771                 /// # Some(())
772                 /// # }
773                 /// ```
774                 #[inline]
775                 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
776                 pub const fn checked_neg(self) -> Option<$Ty> {
777                     if let Some(result) = self.get().checked_neg() {
778                         // SAFETY: negation of nonzero cannot yield zero values.
779                         return Some(unsafe { $Ty::new_unchecked(result) });
780                     }
781                     None
782                 }
783
784                 /// Negates self, overflowing if this is equal to the minimum value.
785                 ///
786                 #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")]
787                 /// for documentation on overflow behaviour.
788                 ///
789                 /// # Example
790                 ///
791                 /// ```
792                 /// #![feature(nonzero_negation_ops)]
793                 ///
794                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
795                 /// # fn main() { test().unwrap(); }
796                 /// # fn test() -> Option<()> {
797                 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
798                 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
799                 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
800                                 stringify!($Int), "::MIN)?;")]
801                 ///
802                 /// assert_eq!(pos_five.overflowing_neg(), (neg_five, false));
803                 /// assert_eq!(min.overflowing_neg(), (min, true));
804                 /// # Some(())
805                 /// # }
806                 /// ```
807                 #[inline]
808                 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
809                 pub const fn overflowing_neg(self) -> ($Ty, bool) {
810                     let (result, overflow) = self.get().overflowing_neg();
811                     // SAFETY: negation of nonzero cannot yield zero values.
812                     ((unsafe { $Ty::new_unchecked(result) }), overflow)
813                 }
814
815                 /// Saturating negation. Computes `-self`, returning `MAX` if
816                 /// `self == i32::MIN` instead of overflowing.
817                 ///
818                 /// # Example
819                 ///
820                 /// ```
821                 /// #![feature(nonzero_negation_ops)]
822                 ///
823                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
824                 /// # fn main() { test().unwrap(); }
825                 /// # fn test() -> Option<()> {
826                 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
827                 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
828                 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
829                                 stringify!($Int), "::MIN)?;")]
830                 #[doc = concat!("let min_plus_one = ", stringify!($Ty), "::new(",
831                                 stringify!($Int), "::MIN + 1)?;")]
832                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
833                                 stringify!($Int), "::MAX)?;")]
834                 ///
835                 /// assert_eq!(pos_five.saturating_neg(), neg_five);
836                 /// assert_eq!(min.saturating_neg(), max);
837                 /// assert_eq!(max.saturating_neg(), min_plus_one);
838                 /// # Some(())
839                 /// # }
840                 /// ```
841                 #[inline]
842                 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
843                 pub const fn saturating_neg(self) -> $Ty {
844                     if let Some(result) = self.checked_neg() {
845                         return result;
846                     }
847                     $Ty::MAX
848                 }
849
850                 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
851                 /// of the type.
852                 ///
853                 #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")]
854                 /// for documentation on overflow behaviour.
855                 ///
856                 /// # Example
857                 ///
858                 /// ```
859                 /// #![feature(nonzero_negation_ops)]
860                 ///
861                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
862                 /// # fn main() { test().unwrap(); }
863                 /// # fn test() -> Option<()> {
864                 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
865                 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
866                 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
867                                 stringify!($Int), "::MIN)?;")]
868                 ///
869                 /// assert_eq!(pos_five.wrapping_neg(), neg_five);
870                 /// assert_eq!(min.wrapping_neg(), min);
871                 /// # Some(())
872                 /// # }
873                 /// ```
874                 #[inline]
875                 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
876                 pub const fn wrapping_neg(self) -> $Ty {
877                     let result = self.get().wrapping_neg();
878                     // SAFETY: negation of nonzero cannot yield zero values.
879                     unsafe { $Ty::new_unchecked(result) }
880                 }
881             }
882         )+
883     }
884 }
885
886 nonzero_signed_operations! {
887     NonZeroI8(i8) -> NonZeroU8(u8);
888     NonZeroI16(i16) -> NonZeroU16(u16);
889     NonZeroI32(i32) -> NonZeroU32(u32);
890     NonZeroI64(i64) -> NonZeroU64(u64);
891     NonZeroI128(i128) -> NonZeroU128(u128);
892     NonZeroIsize(isize) -> NonZeroUsize(usize);
893 }
894
895 // A bunch of methods for both signed and unsigned nonzero types.
896 macro_rules! nonzero_unsigned_signed_operations {
897     ( $( $signedness:ident $Ty: ident($Int: ty); )+ ) => {
898         $(
899             impl $Ty {
900                 /// Multiplies two non-zero integers together.
901                 /// Checks for overflow and returns [`None`] on overflow.
902                 /// As a consequence, the result cannot wrap to zero.
903                 ///
904                 /// # Examples
905                 ///
906                 /// ```
907                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
908                 ///
909                 /// # fn main() { test().unwrap(); }
910                 /// # fn test() -> Option<()> {
911                 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
912                 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
913                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
914                                 stringify!($Int), "::MAX)?;")]
915                 ///
916                 /// assert_eq!(Some(four), two.checked_mul(two));
917                 /// assert_eq!(None, max.checked_mul(two));
918                 /// # Some(())
919                 /// # }
920                 /// ```
921                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
922                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
923                 #[must_use = "this returns the result of the operation, \
924                               without modifying the original"]
925                 #[inline]
926                 pub const fn checked_mul(self, other: $Ty) -> Option<$Ty> {
927                     if let Some(result) = self.get().checked_mul(other.get()) {
928                         // SAFETY: checked_mul returns None on overflow
929                         // and `other` is also non-null
930                         // so the result cannot be zero.
931                         Some(unsafe { $Ty::new_unchecked(result) })
932                     } else {
933                         None
934                     }
935                 }
936
937                 /// Multiplies two non-zero integers together.
938                 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
939                 ///
940                 /// # Examples
941                 ///
942                 /// ```
943                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
944                 ///
945                 /// # fn main() { test().unwrap(); }
946                 /// # fn test() -> Option<()> {
947                 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
948                 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
949                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
950                                 stringify!($Int), "::MAX)?;")]
951                 ///
952                 /// assert_eq!(four, two.saturating_mul(two));
953                 /// assert_eq!(max, four.saturating_mul(max));
954                 /// # Some(())
955                 /// # }
956                 /// ```
957                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
958                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
959                 #[must_use = "this returns the result of the operation, \
960                               without modifying the original"]
961                 #[inline]
962                 pub const fn saturating_mul(self, other: $Ty) -> $Ty {
963                     // SAFETY: saturating_mul returns u*::MAX on overflow
964                     // and `other` is also non-null
965                     // so the result cannot be zero.
966                     unsafe { $Ty::new_unchecked(self.get().saturating_mul(other.get())) }
967                 }
968
969                 /// Multiplies two non-zero integers together,
970                 /// assuming overflow cannot occur.
971                 /// Overflow is unchecked, and it is undefined behaviour to overflow
972                 /// *even if the result would wrap to a non-zero value*.
973                 /// The behaviour is undefined as soon as
974                 #[doc = sign_dependent_expr!{
975                     $signedness ?
976                     if signed {
977                         concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
978                                 "or `self * rhs < ", stringify!($Int), "::MIN`.")
979                     }
980                     if unsigned {
981                         concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
982                     }
983                 }]
984                 ///
985                 /// # Examples
986                 ///
987                 /// ```
988                 /// #![feature(nonzero_ops)]
989                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
990                 ///
991                 /// # fn main() { test().unwrap(); }
992                 /// # fn test() -> Option<()> {
993                 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
994                 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
995                 ///
996                 /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
997                 /// # Some(())
998                 /// # }
999                 /// ```
1000                 #[unstable(feature = "nonzero_ops", issue = "84186")]
1001                 #[must_use = "this returns the result of the operation, \
1002                               without modifying the original"]
1003                 #[inline]
1004                 pub const unsafe fn unchecked_mul(self, other: $Ty) -> $Ty {
1005                     // SAFETY: The caller ensures there is no overflow.
1006                     unsafe { $Ty::new_unchecked(self.get().unchecked_mul(other.get())) }
1007                 }
1008
1009                 /// Raises non-zero value to an integer power.
1010                 /// Checks for overflow and returns [`None`] on overflow.
1011                 /// As a consequence, the result cannot wrap to zero.
1012                 ///
1013                 /// # Examples
1014                 ///
1015                 /// ```
1016                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1017                 ///
1018                 /// # fn main() { test().unwrap(); }
1019                 /// # fn test() -> Option<()> {
1020                 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
1021                 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
1022                 #[doc = concat!("let half_max = ", stringify!($Ty), "::new(",
1023                                 stringify!($Int), "::MAX / 2)?;")]
1024                 ///
1025                 /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
1026                 /// assert_eq!(None, half_max.checked_pow(3));
1027                 /// # Some(())
1028                 /// # }
1029                 /// ```
1030                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1031                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1032                 #[must_use = "this returns the result of the operation, \
1033                               without modifying the original"]
1034                 #[inline]
1035                 pub const fn checked_pow(self, other: u32) -> Option<$Ty> {
1036                     if let Some(result) = self.get().checked_pow(other) {
1037                         // SAFETY: checked_pow returns None on overflow
1038                         // so the result cannot be zero.
1039                         Some(unsafe { $Ty::new_unchecked(result) })
1040                     } else {
1041                         None
1042                     }
1043                 }
1044
1045                 /// Raise non-zero value to an integer power.
1046                 #[doc = sign_dependent_expr!{
1047                     $signedness ?
1048                     if signed {
1049                         concat!("Return [`", stringify!($Int), "::MIN`] ",
1050                                     "or [`", stringify!($Int), "::MAX`] on overflow.")
1051                     }
1052                     if unsigned {
1053                         concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")
1054                     }
1055                 }]
1056                 ///
1057                 /// # Examples
1058                 ///
1059                 /// ```
1060                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1061                 ///
1062                 /// # fn main() { test().unwrap(); }
1063                 /// # fn test() -> Option<()> {
1064                 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
1065                 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
1066                 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
1067                                 stringify!($Int), "::MAX)?;")]
1068                 ///
1069                 /// assert_eq!(twenty_seven, three.saturating_pow(3));
1070                 /// assert_eq!(max, max.saturating_pow(3));
1071                 /// # Some(())
1072                 /// # }
1073                 /// ```
1074                 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1075                 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1076                 #[must_use = "this returns the result of the operation, \
1077                               without modifying the original"]
1078                 #[inline]
1079                 pub const fn saturating_pow(self, other: u32) -> $Ty {
1080                     // SAFETY: saturating_pow returns u*::MAX on overflow
1081                     // so the result cannot be zero.
1082                     unsafe { $Ty::new_unchecked(self.get().saturating_pow(other)) }
1083                 }
1084             }
1085         )+
1086     }
1087 }
1088
1089 // Use this when the generated code should differ between signed and unsigned types.
1090 macro_rules! sign_dependent_expr {
1091     (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1092         $signed_case
1093     };
1094     (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1095         $unsigned_case
1096     };
1097 }
1098
1099 nonzero_unsigned_signed_operations! {
1100     unsigned NonZeroU8(u8);
1101     unsigned NonZeroU16(u16);
1102     unsigned NonZeroU32(u32);
1103     unsigned NonZeroU64(u64);
1104     unsigned NonZeroU128(u128);
1105     unsigned NonZeroUsize(usize);
1106     signed NonZeroI8(i8);
1107     signed NonZeroI16(i16);
1108     signed NonZeroI32(i32);
1109     signed NonZeroI64(i64);
1110     signed NonZeroI128(i128);
1111     signed NonZeroIsize(isize);
1112 }
1113
1114 macro_rules! nonzero_unsigned_is_power_of_two {
1115     ( $( $Ty: ident )+ ) => {
1116         $(
1117             impl $Ty {
1118
1119                 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
1120                 ///
1121                 /// On many architectures, this function can perform better than `is_power_of_two()`
1122                 /// on the underlying integer type, as special handling of zero can be avoided.
1123                 ///
1124                 /// # Examples
1125                 ///
1126                 /// Basic usage:
1127                 ///
1128                 /// ```
1129                 #[doc = concat!("let eight = std::num::", stringify!($Ty), "::new(8).unwrap();")]
1130                 /// assert!(eight.is_power_of_two());
1131                 #[doc = concat!("let ten = std::num::", stringify!($Ty), "::new(10).unwrap();")]
1132                 /// assert!(!ten.is_power_of_two());
1133                 /// ```
1134                 #[must_use]
1135                 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1136                 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1137                 #[inline]
1138                 pub const fn is_power_of_two(self) -> bool {
1139                     // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
1140                     // On the basic x86-64 target, this saves 3 instructions for the zero check.
1141                     // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
1142                     // compared to the `POPCNT` implementation on the underlying integer type.
1143
1144                     intrinsics::ctpop(self.get()) < 2
1145                 }
1146
1147             }
1148         )+
1149     }
1150 }
1151
1152 nonzero_unsigned_is_power_of_two! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize }
1153
1154 macro_rules! nonzero_min_max_unsigned {
1155     ( $( $Ty: ident($Int: ident); )+ ) => {
1156         $(
1157             impl $Ty {
1158                 /// The smallest value that can be represented by this non-zero
1159                 /// integer type, 1.
1160                 ///
1161                 /// # Examples
1162                 ///
1163                 /// ```
1164                 /// #![feature(nonzero_min_max)]
1165                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1166                 ///
1167                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), 1", stringify!($Int), ");")]
1168                 /// ```
1169                 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1170                 pub const MIN: Self = Self::new(1).unwrap();
1171
1172                 /// The largest value that can be represented by this non-zero
1173                 /// integer type,
1174                 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1175                 ///
1176                 /// # Examples
1177                 ///
1178                 /// ```
1179                 /// #![feature(nonzero_min_max)]
1180                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1181                 ///
1182                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1183                 /// ```
1184                 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1185                 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1186             }
1187         )+
1188     }
1189 }
1190
1191 macro_rules! nonzero_min_max_signed {
1192     ( $( $Ty: ident($Int: ident); )+ ) => {
1193         $(
1194             impl $Ty {
1195                 /// The smallest value that can be represented by this non-zero
1196                 /// integer type,
1197                 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1198                 ///
1199                 /// Note: While most integer types are defined for every whole
1200                 /// number between `MIN` and `MAX`, signed non-zero integers are
1201                 /// a special case. They have a "gap" at 0.
1202                 ///
1203                 /// # Examples
1204                 ///
1205                 /// ```
1206                 /// #![feature(nonzero_min_max)]
1207                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1208                 ///
1209                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), ", stringify!($Int), "::MIN);")]
1210                 /// ```
1211                 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1212                 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1213
1214                 /// The largest value that can be represented by this non-zero
1215                 /// integer type,
1216                 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1217                 ///
1218                 /// Note: While most integer types are defined for every whole
1219                 /// number between `MIN` and `MAX`, signed non-zero integers are
1220                 /// a special case. They have a "gap" at 0.
1221                 ///
1222                 /// # Examples
1223                 ///
1224                 /// ```
1225                 /// #![feature(nonzero_min_max)]
1226                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1227                 ///
1228                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1229                 /// ```
1230                 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1231                 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1232             }
1233         )+
1234     }
1235 }
1236
1237 nonzero_min_max_unsigned! {
1238     NonZeroU8(u8);
1239     NonZeroU16(u16);
1240     NonZeroU32(u32);
1241     NonZeroU64(u64);
1242     NonZeroU128(u128);
1243     NonZeroUsize(usize);
1244 }
1245
1246 nonzero_min_max_signed! {
1247     NonZeroI8(i8);
1248     NonZeroI16(i16);
1249     NonZeroI32(i32);
1250     NonZeroI64(i64);
1251     NonZeroI128(i128);
1252     NonZeroIsize(isize);
1253 }
1254
1255 macro_rules! nonzero_bits {
1256     ( $( $Ty: ident($Int: ty); )+ ) => {
1257         $(
1258             impl $Ty {
1259                 /// The size of this non-zero integer type in bits.
1260                 ///
1261                 #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
1262                 ///
1263                 /// # Examples
1264                 ///
1265                 /// ```
1266                 /// #![feature(nonzero_bits)]
1267                 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1268                 ///
1269                 #[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
1270                 /// ```
1271                 #[unstable(feature = "nonzero_bits", issue = "94881")]
1272                 pub const BITS: u32 = <$Int>::BITS;
1273             }
1274         )+
1275     }
1276 }
1277
1278 nonzero_bits! {
1279     NonZeroU8(u8);
1280     NonZeroI8(i8);
1281     NonZeroU16(u16);
1282     NonZeroI16(i16);
1283     NonZeroU32(u32);
1284     NonZeroI32(i32);
1285     NonZeroU64(u64);
1286     NonZeroI64(i64);
1287     NonZeroU128(u128);
1288     NonZeroI128(i128);
1289     NonZeroUsize(usize);
1290     NonZeroIsize(isize);
1291 }