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