core/num/
nonzero.rs

1//! Definitions of integer that is known not to equal zero.
2
3use super::{IntErrorKind, ParseIntError};
4use crate::clone::UseCloned;
5use crate::cmp::Ordering;
6use crate::hash::{Hash, Hasher};
7use crate::marker::{Freeze, StructuralPartialEq};
8use crate::ops::{BitOr, BitOrAssign, Div, DivAssign, Neg, Rem, RemAssign};
9use crate::panic::{RefUnwindSafe, UnwindSafe};
10use crate::str::FromStr;
11use crate::{fmt, intrinsics, ptr, ub_checks};
12
13/// A marker trait for primitive types which can be zero.
14///
15/// This is an implementation detail for <code>[NonZero]\<T></code> which may disappear or be replaced at any time.
16///
17/// # Safety
18///
19/// Types implementing this trait must be primitives that are valid when zeroed.
20///
21/// The associated `Self::NonZeroInner` type must have the same size+align as `Self`,
22/// but with a niche and bit validity making it so the following `transmutes` are sound:
23///
24/// - `Self::NonZeroInner` to `Option<Self::NonZeroInner>`
25/// - `Option<Self::NonZeroInner>` to `Self`
26///
27/// (And, consequently, `Self::NonZeroInner` to `Self`.)
28#[unstable(
29    feature = "nonzero_internals",
30    reason = "implementation detail which may disappear or be replaced at any time",
31    issue = "none"
32)]
33pub unsafe trait ZeroablePrimitive: Sized + Copy + private::Sealed {
34    #[doc(hidden)]
35    type NonZeroInner: Sized + Copy;
36}
37
38macro_rules! impl_zeroable_primitive {
39    ($($NonZeroInner:ident ( $primitive:ty )),+ $(,)?) => {
40        mod private {
41            #[unstable(
42                feature = "nonzero_internals",
43                reason = "implementation detail which may disappear or be replaced at any time",
44                issue = "none"
45            )]
46            pub trait Sealed {}
47        }
48
49        $(
50            #[unstable(
51                feature = "nonzero_internals",
52                reason = "implementation detail which may disappear or be replaced at any time",
53                issue = "none"
54            )]
55            impl private::Sealed for $primitive {}
56
57            #[unstable(
58                feature = "nonzero_internals",
59                reason = "implementation detail which may disappear or be replaced at any time",
60                issue = "none"
61            )]
62            unsafe impl ZeroablePrimitive for $primitive {
63                type NonZeroInner = super::niche_types::$NonZeroInner;
64            }
65        )+
66    };
67}
68
69impl_zeroable_primitive!(
70    NonZeroU8Inner(u8),
71    NonZeroU16Inner(u16),
72    NonZeroU32Inner(u32),
73    NonZeroU64Inner(u64),
74    NonZeroU128Inner(u128),
75    NonZeroUsizeInner(usize),
76    NonZeroI8Inner(i8),
77    NonZeroI16Inner(i16),
78    NonZeroI32Inner(i32),
79    NonZeroI64Inner(i64),
80    NonZeroI128Inner(i128),
81    NonZeroIsizeInner(isize),
82    NonZeroCharInner(char),
83);
84
85/// A value that is known not to equal zero.
86///
87/// This enables some memory layout optimization.
88/// For example, `Option<NonZero<u32>>` is the same size as `u32`:
89///
90/// ```
91/// use core::{num::NonZero};
92///
93/// assert_eq!(size_of::<Option<NonZero<u32>>>(), size_of::<u32>());
94/// ```
95///
96/// # Layout
97///
98/// `NonZero<T>` is guaranteed to have the same layout and bit validity as `T`
99/// with the exception that the all-zero bit pattern is invalid.
100/// `Option<NonZero<T>>` is guaranteed to be compatible with `T`, including in
101/// FFI.
102///
103/// Thanks to the [null pointer optimization], `NonZero<T>` and
104/// `Option<NonZero<T>>` are guaranteed to have the same size and alignment:
105///
106/// ```
107/// use std::num::NonZero;
108///
109/// assert_eq!(size_of::<NonZero<u32>>(), size_of::<Option<NonZero<u32>>>());
110/// assert_eq!(align_of::<NonZero<u32>>(), align_of::<Option<NonZero<u32>>>());
111/// ```
112///
113/// [null pointer optimization]: crate::option#representation
114///
115/// # Note on generic usage
116///
117/// `NonZero<T>` can only be used with some standard library primitive types
118/// (such as `u8`, `i32`, and etc.). The type parameter `T` must implement the
119/// internal trait [`ZeroablePrimitive`], which is currently permanently unstable
120/// and cannot be implemented by users. Therefore, you cannot use `NonZero<T>`
121/// with your own types, nor can you implement traits for all `NonZero<T>`,
122/// only for concrete types.
123#[stable(feature = "generic_nonzero", since = "1.79.0")]
124#[repr(transparent)]
125#[rustc_nonnull_optimization_guaranteed]
126#[rustc_diagnostic_item = "NonZero"]
127pub struct NonZero<T: ZeroablePrimitive>(T::NonZeroInner);
128
129macro_rules! impl_nonzero_fmt {
130    ($(#[$Attribute:meta] $Trait:ident)*) => {
131        $(
132            #[$Attribute]
133            impl<T> fmt::$Trait for NonZero<T>
134            where
135                T: ZeroablePrimitive + fmt::$Trait,
136            {
137                #[inline]
138                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139                    self.get().fmt(f)
140                }
141            }
142        )*
143    };
144}
145
146impl_nonzero_fmt! {
147    #[stable(feature = "nonzero", since = "1.28.0")]
148    Debug
149    #[stable(feature = "nonzero", since = "1.28.0")]
150    Display
151    #[stable(feature = "nonzero", since = "1.28.0")]
152    Binary
153    #[stable(feature = "nonzero", since = "1.28.0")]
154    Octal
155    #[stable(feature = "nonzero", since = "1.28.0")]
156    LowerHex
157    #[stable(feature = "nonzero", since = "1.28.0")]
158    UpperHex
159    #[stable(feature = "nonzero_fmt_exp", since = "1.84.0")]
160    LowerExp
161    #[stable(feature = "nonzero_fmt_exp", since = "1.84.0")]
162    UpperExp
163}
164
165macro_rules! impl_nonzero_auto_trait {
166    (unsafe $Trait:ident) => {
167        #[stable(feature = "nonzero", since = "1.28.0")]
168        unsafe impl<T> $Trait for NonZero<T> where T: ZeroablePrimitive + $Trait {}
169    };
170    ($Trait:ident) => {
171        #[stable(feature = "nonzero", since = "1.28.0")]
172        impl<T> $Trait for NonZero<T> where T: ZeroablePrimitive + $Trait {}
173    };
174}
175
176// Implement auto-traits manually based on `T` to avoid docs exposing
177// the `ZeroablePrimitive::NonZeroInner` implementation detail.
178impl_nonzero_auto_trait!(unsafe Freeze);
179impl_nonzero_auto_trait!(RefUnwindSafe);
180impl_nonzero_auto_trait!(unsafe Send);
181impl_nonzero_auto_trait!(unsafe Sync);
182impl_nonzero_auto_trait!(Unpin);
183impl_nonzero_auto_trait!(UnwindSafe);
184
185#[stable(feature = "nonzero", since = "1.28.0")]
186impl<T> Clone for NonZero<T>
187where
188    T: ZeroablePrimitive,
189{
190    #[inline]
191    fn clone(&self) -> Self {
192        *self
193    }
194}
195
196#[unstable(feature = "ergonomic_clones", issue = "132290")]
197impl<T> UseCloned for NonZero<T> where T: ZeroablePrimitive {}
198
199#[stable(feature = "nonzero", since = "1.28.0")]
200impl<T> Copy for NonZero<T> where T: ZeroablePrimitive {}
201
202#[stable(feature = "nonzero", since = "1.28.0")]
203#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
204impl<T> const PartialEq for NonZero<T>
205where
206    T: ZeroablePrimitive + [const] PartialEq,
207{
208    #[inline]
209    fn eq(&self, other: &Self) -> bool {
210        self.get() == other.get()
211    }
212
213    #[inline]
214    fn ne(&self, other: &Self) -> bool {
215        self.get() != other.get()
216    }
217}
218
219#[unstable(feature = "structural_match", issue = "31434")]
220impl<T> StructuralPartialEq for NonZero<T> where T: ZeroablePrimitive + StructuralPartialEq {}
221
222#[stable(feature = "nonzero", since = "1.28.0")]
223impl<T> Eq for NonZero<T> where T: ZeroablePrimitive + Eq {}
224
225#[stable(feature = "nonzero", since = "1.28.0")]
226impl<T> PartialOrd for NonZero<T>
227where
228    T: ZeroablePrimitive + PartialOrd,
229{
230    #[inline]
231    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
232        self.get().partial_cmp(&other.get())
233    }
234
235    #[inline]
236    fn lt(&self, other: &Self) -> bool {
237        self.get() < other.get()
238    }
239
240    #[inline]
241    fn le(&self, other: &Self) -> bool {
242        self.get() <= other.get()
243    }
244
245    #[inline]
246    fn gt(&self, other: &Self) -> bool {
247        self.get() > other.get()
248    }
249
250    #[inline]
251    fn ge(&self, other: &Self) -> bool {
252        self.get() >= other.get()
253    }
254}
255
256#[stable(feature = "nonzero", since = "1.28.0")]
257impl<T> Ord for NonZero<T>
258where
259    T: ZeroablePrimitive + Ord,
260{
261    #[inline]
262    fn cmp(&self, other: &Self) -> Ordering {
263        self.get().cmp(&other.get())
264    }
265
266    #[inline]
267    fn max(self, other: Self) -> Self {
268        // SAFETY: The maximum of two non-zero values is still non-zero.
269        unsafe { Self::new_unchecked(self.get().max(other.get())) }
270    }
271
272    #[inline]
273    fn min(self, other: Self) -> Self {
274        // SAFETY: The minimum of two non-zero values is still non-zero.
275        unsafe { Self::new_unchecked(self.get().min(other.get())) }
276    }
277
278    #[inline]
279    fn clamp(self, min: Self, max: Self) -> Self {
280        // SAFETY: A non-zero value clamped between two non-zero values is still non-zero.
281        unsafe { Self::new_unchecked(self.get().clamp(min.get(), max.get())) }
282    }
283}
284
285#[stable(feature = "nonzero", since = "1.28.0")]
286impl<T> Hash for NonZero<T>
287where
288    T: ZeroablePrimitive + Hash,
289{
290    #[inline]
291    fn hash<H>(&self, state: &mut H)
292    where
293        H: Hasher,
294    {
295        self.get().hash(state)
296    }
297}
298
299#[stable(feature = "from_nonzero", since = "1.31.0")]
300#[rustc_const_unstable(feature = "const_try", issue = "74935")]
301impl<T> const From<NonZero<T>> for T
302where
303    T: ZeroablePrimitive,
304{
305    #[inline]
306    fn from(nonzero: NonZero<T>) -> Self {
307        // Call `get` method to keep range information.
308        nonzero.get()
309    }
310}
311
312#[stable(feature = "nonzero_bitor", since = "1.45.0")]
313#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
314impl<T> const BitOr for NonZero<T>
315where
316    T: ZeroablePrimitive + [const] BitOr<Output = T>,
317{
318    type Output = Self;
319
320    #[inline]
321    fn bitor(self, rhs: Self) -> Self::Output {
322        // SAFETY: Bitwise OR of two non-zero values is still non-zero.
323        unsafe { Self::new_unchecked(self.get() | rhs.get()) }
324    }
325}
326
327#[stable(feature = "nonzero_bitor", since = "1.45.0")]
328#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
329impl<T> const BitOr<T> for NonZero<T>
330where
331    T: ZeroablePrimitive + [const] BitOr<Output = T>,
332{
333    type Output = Self;
334
335    #[inline]
336    fn bitor(self, rhs: T) -> Self::Output {
337        // SAFETY: Bitwise OR of a non-zero value with anything is still non-zero.
338        unsafe { Self::new_unchecked(self.get() | rhs) }
339    }
340}
341
342#[stable(feature = "nonzero_bitor", since = "1.45.0")]
343#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
344impl<T> const BitOr<NonZero<T>> for T
345where
346    T: ZeroablePrimitive + [const] BitOr<Output = T>,
347{
348    type Output = NonZero<T>;
349
350    #[inline]
351    fn bitor(self, rhs: NonZero<T>) -> Self::Output {
352        // SAFETY: Bitwise OR of anything with a non-zero value is still non-zero.
353        unsafe { NonZero::new_unchecked(self | rhs.get()) }
354    }
355}
356
357#[stable(feature = "nonzero_bitor", since = "1.45.0")]
358#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
359impl<T> const BitOrAssign for NonZero<T>
360where
361    T: ZeroablePrimitive,
362    Self: [const] BitOr<Output = Self>,
363{
364    #[inline]
365    fn bitor_assign(&mut self, rhs: Self) {
366        *self = *self | rhs;
367    }
368}
369
370#[stable(feature = "nonzero_bitor", since = "1.45.0")]
371#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
372impl<T> const BitOrAssign<T> for NonZero<T>
373where
374    T: ZeroablePrimitive,
375    Self: [const] BitOr<T, Output = Self>,
376{
377    #[inline]
378    fn bitor_assign(&mut self, rhs: T) {
379        *self = *self | rhs;
380    }
381}
382
383impl<T> NonZero<T>
384where
385    T: ZeroablePrimitive,
386{
387    /// Creates a non-zero if the given value is not zero.
388    #[stable(feature = "nonzero", since = "1.28.0")]
389    #[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
390    #[must_use]
391    #[inline]
392    pub const fn new(n: T) -> Option<Self> {
393        // SAFETY: Memory layout optimization guarantees that `Option<NonZero<T>>` has
394        //         the same layout and size as `T`, with `0` representing `None`.
395        unsafe { intrinsics::transmute_unchecked(n) }
396    }
397
398    /// Creates a non-zero without checking whether the value is non-zero.
399    /// This results in undefined behavior if the value is zero.
400    ///
401    /// # Safety
402    ///
403    /// The value must not be zero.
404    #[stable(feature = "nonzero", since = "1.28.0")]
405    #[rustc_const_stable(feature = "nonzero", since = "1.28.0")]
406    #[must_use]
407    #[inline]
408    #[track_caller]
409    pub const unsafe fn new_unchecked(n: T) -> Self {
410        match Self::new(n) {
411            Some(n) => n,
412            None => {
413                // SAFETY: The caller guarantees that `n` is non-zero, so this is unreachable.
414                unsafe {
415                    ub_checks::assert_unsafe_precondition!(
416                        check_language_ub,
417                        "NonZero::new_unchecked requires the argument to be non-zero",
418                        () => false,
419                    );
420                    intrinsics::unreachable()
421                }
422            }
423        }
424    }
425
426    /// Converts a reference to a non-zero mutable reference
427    /// if the referenced value is not zero.
428    #[unstable(feature = "nonzero_from_mut", issue = "106290")]
429    #[must_use]
430    #[inline]
431    pub fn from_mut(n: &mut T) -> Option<&mut Self> {
432        // SAFETY: Memory layout optimization guarantees that `Option<NonZero<T>>` has
433        //         the same layout and size as `T`, with `0` representing `None`.
434        let opt_n = unsafe { &mut *(ptr::from_mut(n).cast::<Option<Self>>()) };
435
436        opt_n.as_mut()
437    }
438
439    /// Converts a mutable reference to a non-zero mutable reference
440    /// without checking whether the referenced value is non-zero.
441    /// This results in undefined behavior if the referenced value is zero.
442    ///
443    /// # Safety
444    ///
445    /// The referenced value must not be zero.
446    #[unstable(feature = "nonzero_from_mut", issue = "106290")]
447    #[must_use]
448    #[inline]
449    #[track_caller]
450    pub unsafe fn from_mut_unchecked(n: &mut T) -> &mut Self {
451        match Self::from_mut(n) {
452            Some(n) => n,
453            None => {
454                // SAFETY: The caller guarantees that `n` references a value that is non-zero, so this is unreachable.
455                unsafe {
456                    ub_checks::assert_unsafe_precondition!(
457                        check_library_ub,
458                        "NonZero::from_mut_unchecked requires the argument to dereference as non-zero",
459                        () => false,
460                    );
461                    intrinsics::unreachable()
462                }
463            }
464        }
465    }
466
467    /// Returns the contained value as a primitive type.
468    #[stable(feature = "nonzero", since = "1.28.0")]
469    #[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
470    #[inline]
471    pub const fn get(self) -> T {
472        // Rustc can set range metadata only if it loads `self` from
473        // memory somewhere. If the value of `self` was from by-value argument
474        // of some not-inlined function, LLVM don't have range metadata
475        // to understand that the value cannot be zero.
476        //
477        // Using the transmute `assume`s the range at runtime.
478        //
479        // Even once LLVM supports `!range` metadata for function arguments
480        // (see <https://github.com/llvm/llvm-project/issues/76628>), this can't
481        // be `.0` because MCP#807 bans field-projecting into `scalar_valid_range`
482        // types, and it arguably wouldn't want to be anyway because if this is
483        // MIR-inlined, there's no opportunity to put that argument metadata anywhere.
484        //
485        // The good answer here will eventually be pattern types, which will hopefully
486        // allow it to go back to `.0`, maybe with a cast of some sort.
487        //
488        // SAFETY: `ZeroablePrimitive` guarantees that the size and bit validity
489        // of `.0` is such that this transmute is sound.
490        unsafe { intrinsics::transmute_unchecked(self) }
491    }
492}
493
494macro_rules! nonzero_integer {
495    (
496        #[$stability:meta]
497        Self = $Ty:ident,
498        Primitive = $signedness:ident $Int:ident,
499        SignedPrimitive = $Sint:ty,
500        UnsignedPrimitive = $Uint:ty,
501
502        // Used in doc comments.
503        rot = $rot:literal,
504        rot_op = $rot_op:literal,
505        rot_result = $rot_result:literal,
506        swap_op = $swap_op:literal,
507        swapped = $swapped:literal,
508        reversed = $reversed:literal,
509        leading_zeros_test = $leading_zeros_test:expr,
510    ) => {
511        #[doc = sign_dependent_expr!{
512            $signedness ?
513            if signed {
514                concat!("An [`", stringify!($Int), "`] that is known not to equal zero.")
515            }
516            if unsigned {
517                concat!("A [`", stringify!($Int), "`] that is known not to equal zero.")
518            }
519        }]
520        ///
521        /// This enables some memory layout optimization.
522        #[doc = concat!("For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:")]
523        ///
524        /// ```rust
525        #[doc = concat!("assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int), ">());")]
526        /// ```
527        ///
528        /// # Layout
529        ///
530        #[doc = concat!("`", stringify!($Ty), "` is guaranteed to have the same layout and bit validity as `", stringify!($Int), "`")]
531        /// with the exception that `0` is not a valid instance.
532        #[doc = concat!("`Option<", stringify!($Ty), ">` is guaranteed to be compatible with `", stringify!($Int), "`,")]
533        /// including in FFI.
534        ///
535        /// Thanks to the [null pointer optimization],
536        #[doc = concat!("`", stringify!($Ty), "` and `Option<", stringify!($Ty), ">`")]
537        /// are guaranteed to have the same size and alignment:
538        ///
539        /// ```
540        #[doc = concat!("use std::num::", stringify!($Ty), ";")]
541        ///
542        #[doc = concat!("assert_eq!(size_of::<", stringify!($Ty), ">(), size_of::<Option<", stringify!($Ty), ">>());")]
543        #[doc = concat!("assert_eq!(align_of::<", stringify!($Ty), ">(), align_of::<Option<", stringify!($Ty), ">>());")]
544        /// ```
545        ///
546        /// [null pointer optimization]: crate::option#representation
547        #[$stability]
548        pub type $Ty = NonZero<$Int>;
549
550        impl NonZero<$Int> {
551            /// The size of this non-zero integer type in bits.
552            ///
553            #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
554            ///
555            /// # Examples
556            ///
557            /// ```
558            /// # use std::num::NonZero;
559            /// #
560            #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::BITS, ", stringify!($Int), "::BITS);")]
561            /// ```
562            #[stable(feature = "nonzero_bits", since = "1.67.0")]
563            pub const BITS: u32 = <$Int>::BITS;
564
565            /// Returns the number of leading zeros in the binary representation of `self`.
566            ///
567            /// On many architectures, this function can perform better than `leading_zeros()` on the underlying integer type, as special handling of zero can be avoided.
568            ///
569            /// # Examples
570            ///
571            /// ```
572            /// # use std::num::NonZero;
573            /// #
574            /// # fn main() { test().unwrap(); }
575            /// # fn test() -> Option<()> {
576            #[doc = concat!("let n = NonZero::<", stringify!($Int), ">::new(", $leading_zeros_test, ")?;")]
577            ///
578            /// assert_eq!(n.leading_zeros(), 0);
579            /// # Some(())
580            /// # }
581            /// ```
582            #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
583            #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
584            #[must_use = "this returns the result of the operation, \
585                          without modifying the original"]
586            #[inline]
587            pub const fn leading_zeros(self) -> u32 {
588                // SAFETY: since `self` cannot be zero, it is safe to call `ctlz_nonzero`.
589                unsafe {
590                    intrinsics::ctlz_nonzero(self.get() as $Uint)
591                }
592            }
593
594            /// Returns the number of trailing zeros in the binary representation
595            /// of `self`.
596            ///
597            /// On many architectures, this function can perform better than `trailing_zeros()` on the underlying integer type, as special handling of zero can be avoided.
598            ///
599            /// # Examples
600            ///
601            /// ```
602            /// # use std::num::NonZero;
603            /// #
604            /// # fn main() { test().unwrap(); }
605            /// # fn test() -> Option<()> {
606            #[doc = concat!("let n = NonZero::<", stringify!($Int), ">::new(0b0101000)?;")]
607            ///
608            /// assert_eq!(n.trailing_zeros(), 3);
609            /// # Some(())
610            /// # }
611            /// ```
612            #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
613            #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
614            #[must_use = "this returns the result of the operation, \
615                          without modifying the original"]
616            #[inline]
617            pub const fn trailing_zeros(self) -> u32 {
618                // SAFETY: since `self` cannot be zero, it is safe to call `cttz_nonzero`.
619                unsafe {
620                    intrinsics::cttz_nonzero(self.get() as $Uint)
621                }
622            }
623
624            /// Returns `self` with only the most significant bit set.
625            ///
626            /// # Example
627            ///
628            /// ```
629            /// #![feature(isolate_most_least_significant_one)]
630            ///
631            /// # use core::num::NonZero;
632            /// # fn main() { test().unwrap(); }
633            /// # fn test() -> Option<()> {
634            #[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b_01100100)?;")]
635            #[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b_01000000)?;")]
636            ///
637            /// assert_eq!(a.isolate_highest_one(), b);
638            /// # Some(())
639            /// # }
640            /// ```
641            #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")]
642            #[must_use = "this returns the result of the operation, \
643                        without modifying the original"]
644            #[inline(always)]
645            pub const fn isolate_highest_one(self) -> Self {
646                let n = self.get() & (((1 as $Int) << (<$Int>::BITS - 1)).wrapping_shr(self.leading_zeros()));
647
648                // SAFETY:
649                // `self` is non-zero, so masking to preserve only the most
650                // significant set bit will result in a non-zero `n`.
651                unsafe { NonZero::new_unchecked(n) }
652            }
653
654            /// Returns `self` with only the least significant bit set.
655            ///
656            /// # Example
657            ///
658            /// ```
659            /// #![feature(isolate_most_least_significant_one)]
660            ///
661            /// # use core::num::NonZero;
662            /// # fn main() { test().unwrap(); }
663            /// # fn test() -> Option<()> {
664            #[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b_01100100)?;")]
665            #[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b_00000100)?;")]
666            ///
667            /// assert_eq!(a.isolate_lowest_one(), b);
668            /// # Some(())
669            /// # }
670            /// ```
671            #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")]
672            #[must_use = "this returns the result of the operation, \
673                        without modifying the original"]
674            #[inline(always)]
675            pub const fn isolate_lowest_one(self) -> Self {
676                let n = self.get();
677                let n = n & n.wrapping_neg();
678
679                // SAFETY: `self` is non-zero, so `self` with only its least
680                // significant set bit will remain non-zero.
681                unsafe { NonZero::new_unchecked(n) }
682            }
683
684            /// Returns the index of the highest bit set to one in `self`.
685            ///
686            /// # Examples
687            ///
688            /// ```
689            /// #![feature(int_lowest_highest_one)]
690            ///
691            /// # use core::num::NonZero;
692            /// # fn main() { test().unwrap(); }
693            /// # fn test() -> Option<()> {
694            #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0x1)?.highest_one(), 0);")]
695            #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0x10)?.highest_one(), 4);")]
696            #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0x1f)?.highest_one(), 4);")]
697            /// # Some(())
698            /// # }
699            /// ```
700            #[unstable(feature = "int_lowest_highest_one", issue = "145203")]
701            #[must_use = "this returns the result of the operation, \
702                          without modifying the original"]
703            #[inline(always)]
704            pub const fn highest_one(self) -> u32 {
705                Self::BITS - 1 - self.leading_zeros()
706            }
707
708            /// Returns the index of the lowest bit set to one in `self`.
709            ///
710            /// # Examples
711            ///
712            /// ```
713            /// #![feature(int_lowest_highest_one)]
714            ///
715            /// # use core::num::NonZero;
716            /// # fn main() { test().unwrap(); }
717            /// # fn test() -> Option<()> {
718            #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0x1)?.lowest_one(), 0);")]
719            #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0x10)?.lowest_one(), 4);")]
720            #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::new(0x1f)?.lowest_one(), 0);")]
721            /// # Some(())
722            /// # }
723            /// ```
724            #[unstable(feature = "int_lowest_highest_one", issue = "145203")]
725            #[must_use = "this returns the result of the operation, \
726                          without modifying the original"]
727            #[inline(always)]
728            pub const fn lowest_one(self) -> u32 {
729                self.trailing_zeros()
730            }
731
732            /// Returns the number of ones in the binary representation of `self`.
733            ///
734            /// # Examples
735            ///
736            /// ```
737            /// # use std::num::NonZero;
738            /// #
739            /// # fn main() { test().unwrap(); }
740            /// # fn test() -> Option<()> {
741            #[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b100_0000)?;")]
742            #[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b100_0011)?;")]
743            ///
744            /// assert_eq!(a.count_ones(), NonZero::new(1)?);
745            /// assert_eq!(b.count_ones(), NonZero::new(3)?);
746            /// # Some(())
747            /// # }
748            /// ```
749            ///
750            #[stable(feature = "non_zero_count_ones", since = "1.86.0")]
751            #[rustc_const_stable(feature = "non_zero_count_ones", since = "1.86.0")]
752            #[doc(alias = "popcount")]
753            #[doc(alias = "popcnt")]
754            #[must_use = "this returns the result of the operation, \
755                        without modifying the original"]
756            #[inline(always)]
757            pub const fn count_ones(self) -> NonZero<u32> {
758                // SAFETY:
759                // `self` is non-zero, which means it has at least one bit set, which means
760                // that the result of `count_ones` is non-zero.
761                unsafe { NonZero::new_unchecked(self.get().count_ones()) }
762            }
763
764            /// Shifts the bits to the left by a specified amount, `n`,
765            /// wrapping the truncated bits to the end of the resulting integer.
766            ///
767            /// Please note this isn't the same operation as the `<<` shifting operator!
768            ///
769            /// # Examples
770            ///
771            /// ```
772            /// #![feature(nonzero_bitwise)]
773            /// # use std::num::NonZero;
774            /// #
775            /// # fn main() { test().unwrap(); }
776            /// # fn test() -> Option<()> {
777            #[doc = concat!("let n = NonZero::new(", $rot_op, stringify!($Int), ")?;")]
778            #[doc = concat!("let m = NonZero::new(", $rot_result, ")?;")]
779            ///
780            #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
781            /// # Some(())
782            /// # }
783            /// ```
784            #[unstable(feature = "nonzero_bitwise", issue = "128281")]
785            #[must_use = "this returns the result of the operation, \
786                        without modifying the original"]
787            #[inline(always)]
788            pub const fn rotate_left(self, n: u32) -> Self {
789                let result = self.get().rotate_left(n);
790                // SAFETY: Rotating bits preserves the property int > 0.
791                unsafe { Self::new_unchecked(result) }
792            }
793
794            /// Shifts the bits to the right by a specified amount, `n`,
795            /// wrapping the truncated bits to the beginning of the resulting
796            /// integer.
797            ///
798            /// Please note this isn't the same operation as the `>>` shifting operator!
799            ///
800            /// # Examples
801            ///
802            /// ```
803            /// #![feature(nonzero_bitwise)]
804            /// # use std::num::NonZero;
805            /// #
806            /// # fn main() { test().unwrap(); }
807            /// # fn test() -> Option<()> {
808            #[doc = concat!("let n = NonZero::new(", $rot_result, stringify!($Int), ")?;")]
809            #[doc = concat!("let m = NonZero::new(", $rot_op, ")?;")]
810            ///
811            #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
812            /// # Some(())
813            /// # }
814            /// ```
815            #[unstable(feature = "nonzero_bitwise", issue = "128281")]
816            #[must_use = "this returns the result of the operation, \
817                        without modifying the original"]
818            #[inline(always)]
819            pub const fn rotate_right(self, n: u32) -> Self {
820                let result = self.get().rotate_right(n);
821                // SAFETY: Rotating bits preserves the property int > 0.
822                unsafe { Self::new_unchecked(result) }
823            }
824
825            /// Reverses the byte order of the integer.
826            ///
827            /// # Examples
828            ///
829            /// ```
830            /// #![feature(nonzero_bitwise)]
831            /// # use std::num::NonZero;
832            /// #
833            /// # fn main() { test().unwrap(); }
834            /// # fn test() -> Option<()> {
835            #[doc = concat!("let n = NonZero::new(", $swap_op, stringify!($Int), ")?;")]
836            /// let m = n.swap_bytes();
837            ///
838            #[doc = concat!("assert_eq!(m, NonZero::new(", $swapped, ")?);")]
839            /// # Some(())
840            /// # }
841            /// ```
842            #[unstable(feature = "nonzero_bitwise", issue = "128281")]
843            #[must_use = "this returns the result of the operation, \
844                        without modifying the original"]
845            #[inline(always)]
846            pub const fn swap_bytes(self) -> Self {
847                let result = self.get().swap_bytes();
848                // SAFETY: Shuffling bytes preserves the property int > 0.
849                unsafe { Self::new_unchecked(result) }
850            }
851
852            /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
853            /// second least-significant bit becomes second most-significant bit, etc.
854            ///
855            /// # Examples
856            ///
857            /// ```
858            /// #![feature(nonzero_bitwise)]
859            /// # use std::num::NonZero;
860            /// #
861            /// # fn main() { test().unwrap(); }
862            /// # fn test() -> Option<()> {
863            #[doc = concat!("let n = NonZero::new(", $swap_op, stringify!($Int), ")?;")]
864            /// let m = n.reverse_bits();
865            ///
866            #[doc = concat!("assert_eq!(m, NonZero::new(", $reversed, ")?);")]
867            /// # Some(())
868            /// # }
869            /// ```
870            #[unstable(feature = "nonzero_bitwise", issue = "128281")]
871            #[must_use = "this returns the result of the operation, \
872                        without modifying the original"]
873            #[inline(always)]
874            pub const fn reverse_bits(self) -> Self {
875                let result = self.get().reverse_bits();
876                // SAFETY: Reversing bits preserves the property int > 0.
877                unsafe { Self::new_unchecked(result) }
878            }
879
880            /// Converts an integer from big endian to the target's endianness.
881            ///
882            /// On big endian this is a no-op. On little endian the bytes are
883            /// swapped.
884            ///
885            /// # Examples
886            ///
887            /// ```
888            /// #![feature(nonzero_bitwise)]
889            /// # use std::num::NonZero;
890            #[doc = concat!("use std::num::", stringify!($Ty), ";")]
891            /// #
892            /// # fn main() { test().unwrap(); }
893            /// # fn test() -> Option<()> {
894            #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")]
895            ///
896            /// if cfg!(target_endian = "big") {
897            #[doc = concat!("    assert_eq!(", stringify!($Ty), "::from_be(n), n)")]
898            /// } else {
899            #[doc = concat!("    assert_eq!(", stringify!($Ty), "::from_be(n), n.swap_bytes())")]
900            /// }
901            /// # Some(())
902            /// # }
903            /// ```
904            #[unstable(feature = "nonzero_bitwise", issue = "128281")]
905            #[must_use]
906            #[inline(always)]
907            pub const fn from_be(x: Self) -> Self {
908                let result = $Int::from_be(x.get());
909                // SAFETY: Shuffling bytes preserves the property int > 0.
910                unsafe { Self::new_unchecked(result) }
911            }
912
913            /// Converts an integer from little endian to the target's endianness.
914            ///
915            /// On little endian this is a no-op. On big endian the bytes are
916            /// swapped.
917            ///
918            /// # Examples
919            ///
920            /// ```
921            /// #![feature(nonzero_bitwise)]
922            /// # use std::num::NonZero;
923            #[doc = concat!("use std::num::", stringify!($Ty), ";")]
924            /// #
925            /// # fn main() { test().unwrap(); }
926            /// # fn test() -> Option<()> {
927            #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")]
928            ///
929            /// if cfg!(target_endian = "little") {
930            #[doc = concat!("    assert_eq!(", stringify!($Ty), "::from_le(n), n)")]
931            /// } else {
932            #[doc = concat!("    assert_eq!(", stringify!($Ty), "::from_le(n), n.swap_bytes())")]
933            /// }
934            /// # Some(())
935            /// # }
936            /// ```
937            #[unstable(feature = "nonzero_bitwise", issue = "128281")]
938            #[must_use]
939            #[inline(always)]
940            pub const fn from_le(x: Self) -> Self {
941                let result = $Int::from_le(x.get());
942                // SAFETY: Shuffling bytes preserves the property int > 0.
943                unsafe { Self::new_unchecked(result) }
944            }
945
946            /// Converts `self` to big endian from the target's endianness.
947            ///
948            /// On big endian this is a no-op. On little endian the bytes are
949            /// swapped.
950            ///
951            /// # Examples
952            ///
953            /// ```
954            /// #![feature(nonzero_bitwise)]
955            /// # use std::num::NonZero;
956            /// #
957            /// # fn main() { test().unwrap(); }
958            /// # fn test() -> Option<()> {
959            #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")]
960            ///
961            /// if cfg!(target_endian = "big") {
962            ///     assert_eq!(n.to_be(), n)
963            /// } else {
964            ///     assert_eq!(n.to_be(), n.swap_bytes())
965            /// }
966            /// # Some(())
967            /// # }
968            /// ```
969            #[unstable(feature = "nonzero_bitwise", issue = "128281")]
970            #[must_use = "this returns the result of the operation, \
971                        without modifying the original"]
972            #[inline(always)]
973            pub const fn to_be(self) -> Self {
974                let result = self.get().to_be();
975                // SAFETY: Shuffling bytes preserves the property int > 0.
976                unsafe { Self::new_unchecked(result) }
977            }
978
979            /// Converts `self` to little endian from the target's endianness.
980            ///
981            /// On little endian this is a no-op. On big endian the bytes are
982            /// swapped.
983            ///
984            /// # Examples
985            ///
986            /// ```
987            /// #![feature(nonzero_bitwise)]
988            /// # use std::num::NonZero;
989            /// #
990            /// # fn main() { test().unwrap(); }
991            /// # fn test() -> Option<()> {
992            #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")]
993            ///
994            /// if cfg!(target_endian = "little") {
995            ///     assert_eq!(n.to_le(), n)
996            /// } else {
997            ///     assert_eq!(n.to_le(), n.swap_bytes())
998            /// }
999            /// # Some(())
1000            /// # }
1001            /// ```
1002            #[unstable(feature = "nonzero_bitwise", issue = "128281")]
1003            #[must_use = "this returns the result of the operation, \
1004                        without modifying the original"]
1005            #[inline(always)]
1006            pub const fn to_le(self) -> Self {
1007                let result = self.get().to_le();
1008                // SAFETY: Shuffling bytes preserves the property int > 0.
1009                unsafe { Self::new_unchecked(result) }
1010            }
1011
1012            nonzero_integer_signedness_dependent_methods! {
1013                Primitive = $signedness $Int,
1014                SignedPrimitive = $Sint,
1015                UnsignedPrimitive = $Uint,
1016            }
1017
1018            /// Multiplies two non-zero integers together.
1019            /// Checks for overflow and returns [`None`] on overflow.
1020            /// As a consequence, the result cannot wrap to zero.
1021            ///
1022            /// # Examples
1023            ///
1024            /// ```
1025            /// # use std::num::NonZero;
1026            /// #
1027            /// # fn main() { test().unwrap(); }
1028            /// # fn test() -> Option<()> {
1029            #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1030            #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1031            #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1032            ///
1033            /// assert_eq!(Some(four), two.checked_mul(two));
1034            /// assert_eq!(None, max.checked_mul(two));
1035            /// # Some(())
1036            /// # }
1037            /// ```
1038            #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1039            #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1040            #[must_use = "this returns the result of the operation, \
1041                          without modifying the original"]
1042            #[inline]
1043            pub const fn checked_mul(self, other: Self) -> Option<Self> {
1044                if let Some(result) = self.get().checked_mul(other.get()) {
1045                    // SAFETY:
1046                    // - `checked_mul` returns `None` on overflow
1047                    // - `self` and `other` are non-zero
1048                    // - the only way to get zero from a multiplication without overflow is for one
1049                    //   of the sides to be zero
1050                    //
1051                    // So the result cannot be zero.
1052                    Some(unsafe { Self::new_unchecked(result) })
1053                } else {
1054                    None
1055                }
1056            }
1057
1058            /// Multiplies two non-zero integers together.
1059            #[doc = concat!("Return [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")]
1060            ///
1061            /// # Examples
1062            ///
1063            /// ```
1064            /// # use std::num::NonZero;
1065            /// #
1066            /// # fn main() { test().unwrap(); }
1067            /// # fn test() -> Option<()> {
1068            #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1069            #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1070            #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1071            ///
1072            /// assert_eq!(four, two.saturating_mul(two));
1073            /// assert_eq!(max, four.saturating_mul(max));
1074            /// # Some(())
1075            /// # }
1076            /// ```
1077            #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1078            #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1079            #[must_use = "this returns the result of the operation, \
1080                          without modifying the original"]
1081            #[inline]
1082            pub const fn saturating_mul(self, other: Self) -> Self {
1083                // SAFETY:
1084                // - `saturating_mul` returns `u*::MAX`/`i*::MAX`/`i*::MIN` on overflow/underflow,
1085                //   all of which are non-zero
1086                // - `self` and `other` are non-zero
1087                // - the only way to get zero from a multiplication without overflow is for one
1088                //   of the sides to be zero
1089                //
1090                // So the result cannot be zero.
1091                unsafe { Self::new_unchecked(self.get().saturating_mul(other.get())) }
1092            }
1093
1094            /// Multiplies two non-zero integers together,
1095            /// assuming overflow cannot occur.
1096            /// Overflow is unchecked, and it is undefined behavior to overflow
1097            /// *even if the result would wrap to a non-zero value*.
1098            /// The behavior is undefined as soon as
1099            #[doc = sign_dependent_expr!{
1100                $signedness ?
1101                if signed {
1102                    concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
1103                            "or `self * rhs < ", stringify!($Int), "::MIN`.")
1104                }
1105                if unsigned {
1106                    concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
1107                }
1108            }]
1109            ///
1110            /// # Examples
1111            ///
1112            /// ```
1113            /// #![feature(nonzero_ops)]
1114            ///
1115            /// # use std::num::NonZero;
1116            /// #
1117            /// # fn main() { test().unwrap(); }
1118            /// # fn test() -> Option<()> {
1119            #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1120            #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1121            ///
1122            /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
1123            /// # Some(())
1124            /// # }
1125            /// ```
1126            #[unstable(feature = "nonzero_ops", issue = "84186")]
1127            #[must_use = "this returns the result of the operation, \
1128                          without modifying the original"]
1129            #[inline]
1130            pub const unsafe fn unchecked_mul(self, other: Self) -> Self {
1131                // SAFETY: The caller ensures there is no overflow.
1132                unsafe { Self::new_unchecked(self.get().unchecked_mul(other.get())) }
1133            }
1134
1135            /// Raises non-zero value to an integer power.
1136            /// Checks for overflow and returns [`None`] on overflow.
1137            /// As a consequence, the result cannot wrap to zero.
1138            ///
1139            /// # Examples
1140            ///
1141            /// ```
1142            /// # use std::num::NonZero;
1143            /// #
1144            /// # fn main() { test().unwrap(); }
1145            /// # fn test() -> Option<()> {
1146            #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1147            #[doc = concat!("let twenty_seven = NonZero::new(27", stringify!($Int), ")?;")]
1148            #[doc = concat!("let half_max = NonZero::new(", stringify!($Int), "::MAX / 2)?;")]
1149            ///
1150            /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
1151            /// assert_eq!(None, half_max.checked_pow(3));
1152            /// # Some(())
1153            /// # }
1154            /// ```
1155            #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1156            #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1157            #[must_use = "this returns the result of the operation, \
1158                          without modifying the original"]
1159            #[inline]
1160            pub const fn checked_pow(self, other: u32) -> Option<Self> {
1161                if let Some(result) = self.get().checked_pow(other) {
1162                    // SAFETY:
1163                    // - `checked_pow` returns `None` on overflow/underflow
1164                    // - `self` is non-zero
1165                    // - the only way to get zero from an exponentiation without overflow is
1166                    //   for base to be zero
1167                    //
1168                    // So the result cannot be zero.
1169                    Some(unsafe { Self::new_unchecked(result) })
1170                } else {
1171                    None
1172                }
1173            }
1174
1175            /// Raise non-zero value to an integer power.
1176            #[doc = sign_dependent_expr!{
1177                $signedness ?
1178                if signed {
1179                    concat!("Return [`NonZero::<", stringify!($Int), ">::MIN`] ",
1180                                "or [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")
1181                }
1182                if unsigned {
1183                    concat!("Return [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")
1184                }
1185            }]
1186            ///
1187            /// # Examples
1188            ///
1189            /// ```
1190            /// # use std::num::NonZero;
1191            /// #
1192            /// # fn main() { test().unwrap(); }
1193            /// # fn test() -> Option<()> {
1194            #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1195            #[doc = concat!("let twenty_seven = NonZero::new(27", stringify!($Int), ")?;")]
1196            #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1197            ///
1198            /// assert_eq!(twenty_seven, three.saturating_pow(3));
1199            /// assert_eq!(max, max.saturating_pow(3));
1200            /// # Some(())
1201            /// # }
1202            /// ```
1203            #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1204            #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1205            #[must_use = "this returns the result of the operation, \
1206                          without modifying the original"]
1207            #[inline]
1208            pub const fn saturating_pow(self, other: u32) -> Self {
1209                // SAFETY:
1210                // - `saturating_pow` returns `u*::MAX`/`i*::MAX`/`i*::MIN` on overflow/underflow,
1211                //   all of which are non-zero
1212                // - `self` is non-zero
1213                // - the only way to get zero from an exponentiation without overflow is
1214                //   for base to be zero
1215                //
1216                // So the result cannot be zero.
1217                unsafe { Self::new_unchecked(self.get().saturating_pow(other)) }
1218            }
1219        }
1220
1221        #[stable(feature = "nonzero_parse", since = "1.35.0")]
1222        impl FromStr for NonZero<$Int> {
1223            type Err = ParseIntError;
1224            fn from_str(src: &str) -> Result<Self, Self::Err> {
1225                Self::new(<$Int>::from_str_radix(src, 10)?)
1226                    .ok_or(ParseIntError {
1227                        kind: IntErrorKind::Zero
1228                    })
1229            }
1230        }
1231
1232        nonzero_integer_signedness_dependent_impls!($signedness $Int);
1233    };
1234
1235    (
1236        Self = $Ty:ident,
1237        Primitive = unsigned $Int:ident,
1238        SignedPrimitive = $Sint:ident,
1239        rot = $rot:literal,
1240        rot_op = $rot_op:literal,
1241        rot_result = $rot_result:literal,
1242        swap_op = $swap_op:literal,
1243        swapped = $swapped:literal,
1244        reversed = $reversed:literal,
1245        $(,)?
1246    ) => {
1247        nonzero_integer! {
1248            #[stable(feature = "nonzero", since = "1.28.0")]
1249            Self = $Ty,
1250            Primitive = unsigned $Int,
1251            SignedPrimitive = $Sint,
1252            UnsignedPrimitive = $Int,
1253            rot = $rot,
1254            rot_op = $rot_op,
1255            rot_result = $rot_result,
1256            swap_op = $swap_op,
1257            swapped = $swapped,
1258            reversed = $reversed,
1259            leading_zeros_test = concat!(stringify!($Int), "::MAX"),
1260        }
1261    };
1262
1263    (
1264        Self = $Ty:ident,
1265        Primitive = signed $Int:ident,
1266        UnsignedPrimitive = $Uint:ident,
1267        rot = $rot:literal,
1268        rot_op = $rot_op:literal,
1269        rot_result = $rot_result:literal,
1270        swap_op = $swap_op:literal,
1271        swapped = $swapped:literal,
1272        reversed = $reversed:literal,
1273    ) => {
1274        nonzero_integer! {
1275            #[stable(feature = "signed_nonzero", since = "1.34.0")]
1276            Self = $Ty,
1277            Primitive = signed $Int,
1278            SignedPrimitive = $Int,
1279            UnsignedPrimitive = $Uint,
1280            rot = $rot,
1281            rot_op = $rot_op,
1282            rot_result = $rot_result,
1283            swap_op = $swap_op,
1284            swapped = $swapped,
1285            reversed = $reversed,
1286            leading_zeros_test = concat!("-1", stringify!($Int)),
1287        }
1288    };
1289}
1290
1291macro_rules! nonzero_integer_signedness_dependent_impls {
1292    // Impls for unsigned nonzero types only.
1293    (unsigned $Int:ty) => {
1294        #[stable(feature = "nonzero_div", since = "1.51.0")]
1295        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1296        impl const Div<NonZero<$Int>> for $Int {
1297            type Output = $Int;
1298
1299            /// Same as `self / other.get()`, but because `other` is a `NonZero<_>`,
1300            /// there's never a runtime check for division-by-zero.
1301            ///
1302            /// This operation rounds towards zero, truncating any fractional
1303            /// part of the exact result, and cannot panic.
1304            #[doc(alias = "unchecked_div")]
1305            #[inline]
1306            fn div(self, other: NonZero<$Int>) -> $Int {
1307                // SAFETY: Division by zero is checked because `other` is non-zero,
1308                // and MIN/-1 is checked because `self` is an unsigned int.
1309                unsafe { intrinsics::unchecked_div(self, other.get()) }
1310            }
1311        }
1312
1313        #[stable(feature = "nonzero_div_assign", since = "1.79.0")]
1314        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1315        impl const DivAssign<NonZero<$Int>> for $Int {
1316            /// Same as `self /= other.get()`, but because `other` is a `NonZero<_>`,
1317            /// there's never a runtime check for division-by-zero.
1318            ///
1319            /// This operation rounds towards zero, truncating any fractional
1320            /// part of the exact result, and cannot panic.
1321            #[inline]
1322            fn div_assign(&mut self, other: NonZero<$Int>) {
1323                *self = *self / other;
1324            }
1325        }
1326
1327        #[stable(feature = "nonzero_div", since = "1.51.0")]
1328        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1329        impl const Rem<NonZero<$Int>> for $Int {
1330            type Output = $Int;
1331
1332            /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
1333            #[inline]
1334            fn rem(self, other: NonZero<$Int>) -> $Int {
1335                // SAFETY: Remainder by zero is checked because `other` is non-zero,
1336                // and MIN/-1 is checked because `self` is an unsigned int.
1337                unsafe { intrinsics::unchecked_rem(self, other.get()) }
1338            }
1339        }
1340
1341        #[stable(feature = "nonzero_div_assign", since = "1.79.0")]
1342        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1343        impl const RemAssign<NonZero<$Int>> for $Int {
1344            /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
1345            #[inline]
1346            fn rem_assign(&mut self, other: NonZero<$Int>) {
1347                *self = *self % other;
1348            }
1349        }
1350
1351        impl NonZero<$Int> {
1352            /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
1353            ///
1354            /// The result is guaranteed to be non-zero.
1355            ///
1356            /// # Examples
1357            ///
1358            /// ```
1359            /// # #![feature(unsigned_nonzero_div_ceil)]
1360            /// # use std::num::NonZero;
1361            #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ").unwrap();")]
1362            #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX).unwrap();")]
1363            /// assert_eq!(one.div_ceil(max), one);
1364            ///
1365            #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ").unwrap();")]
1366            #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ").unwrap();")]
1367            /// assert_eq!(three.div_ceil(two), two);
1368            /// ```
1369            #[unstable(feature = "unsigned_nonzero_div_ceil", issue = "132968")]
1370            #[must_use = "this returns the result of the operation, \
1371                          without modifying the original"]
1372            #[inline]
1373            pub const fn div_ceil(self, rhs: Self) -> Self {
1374                let v = self.get().div_ceil(rhs.get());
1375                // SAFETY: ceiled division of two positive integers can never be zero.
1376                unsafe { Self::new_unchecked(v) }
1377            }
1378        }
1379    };
1380    // Impls for signed nonzero types only.
1381    (signed $Int:ty) => {
1382        #[stable(feature = "signed_nonzero_neg", since = "1.71.0")]
1383        #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1384        impl const Neg for NonZero<$Int> {
1385            type Output = Self;
1386
1387            #[inline]
1388            fn neg(self) -> Self {
1389                // SAFETY: negation of nonzero cannot yield zero values.
1390                unsafe { Self::new_unchecked(self.get().neg()) }
1391            }
1392        }
1393
1394        forward_ref_unop! { impl Neg, neg for NonZero<$Int>,
1395        #[stable(feature = "signed_nonzero_neg", since = "1.71.0")]
1396        #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
1397    };
1398}
1399
1400#[rustfmt::skip] // https://github.com/rust-lang/rustfmt/issues/5974
1401macro_rules! nonzero_integer_signedness_dependent_methods {
1402    // Associated items for unsigned nonzero types only.
1403    (
1404        Primitive = unsigned $Int:ident,
1405        SignedPrimitive = $Sint:ty,
1406        UnsignedPrimitive = $Uint:ty,
1407    ) => {
1408        /// The smallest value that can be represented by this non-zero
1409        /// integer type, 1.
1410        ///
1411        /// # Examples
1412        ///
1413        /// ```
1414        /// # use std::num::NonZero;
1415        /// #
1416        #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MIN.get(), 1", stringify!($Int), ");")]
1417        /// ```
1418        #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1419        pub const MIN: Self = Self::new(1).unwrap();
1420
1421        /// The largest value that can be represented by this non-zero
1422        /// integer type,
1423        #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1424        ///
1425        /// # Examples
1426        ///
1427        /// ```
1428        /// # use std::num::NonZero;
1429        /// #
1430        #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MAX.get(), ", stringify!($Int), "::MAX);")]
1431        /// ```
1432        #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1433        pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1434
1435        /// Adds an unsigned integer to a non-zero value.
1436        /// Checks for overflow and returns [`None`] on overflow.
1437        /// As a consequence, the result cannot wrap to zero.
1438        ///
1439        ///
1440        /// # Examples
1441        ///
1442        /// ```
1443        /// # use std::num::NonZero;
1444        /// #
1445        /// # fn main() { test().unwrap(); }
1446        /// # fn test() -> Option<()> {
1447        #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1448        #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1449        #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1450        ///
1451        /// assert_eq!(Some(two), one.checked_add(1));
1452        /// assert_eq!(None, max.checked_add(1));
1453        /// # Some(())
1454        /// # }
1455        /// ```
1456        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1457        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1458        #[must_use = "this returns the result of the operation, \
1459                      without modifying the original"]
1460        #[inline]
1461        pub const fn checked_add(self, other: $Int) -> Option<Self> {
1462            if let Some(result) = self.get().checked_add(other) {
1463                // SAFETY:
1464                // - `checked_add` returns `None` on overflow
1465                // - `self` is non-zero
1466                // - the only way to get zero from an addition without overflow is for both
1467                //   sides to be zero
1468                //
1469                // So the result cannot be zero.
1470                Some(unsafe { Self::new_unchecked(result) })
1471            } else {
1472                None
1473            }
1474        }
1475
1476        /// Adds an unsigned integer to a non-zero value.
1477        #[doc = concat!("Return [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")]
1478        ///
1479        /// # Examples
1480        ///
1481        /// ```
1482        /// # use std::num::NonZero;
1483        /// #
1484        /// # fn main() { test().unwrap(); }
1485        /// # fn test() -> Option<()> {
1486        #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1487        #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1488        #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1489        ///
1490        /// assert_eq!(two, one.saturating_add(1));
1491        /// assert_eq!(max, max.saturating_add(1));
1492        /// # Some(())
1493        /// # }
1494        /// ```
1495        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1496        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1497        #[must_use = "this returns the result of the operation, \
1498                      without modifying the original"]
1499        #[inline]
1500        pub const fn saturating_add(self, other: $Int) -> Self {
1501            // SAFETY:
1502            // - `saturating_add` returns `u*::MAX` on overflow, which is non-zero
1503            // - `self` is non-zero
1504            // - the only way to get zero from an addition without overflow is for both
1505            //   sides to be zero
1506            //
1507            // So the result cannot be zero.
1508            unsafe { Self::new_unchecked(self.get().saturating_add(other)) }
1509        }
1510
1511        /// Adds an unsigned integer to a non-zero value,
1512        /// assuming overflow cannot occur.
1513        /// Overflow is unchecked, and it is undefined behavior to overflow
1514        /// *even if the result would wrap to a non-zero value*.
1515        /// The behavior is undefined as soon as
1516        #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
1517        ///
1518        /// # Examples
1519        ///
1520        /// ```
1521        /// #![feature(nonzero_ops)]
1522        ///
1523        /// # use std::num::NonZero;
1524        /// #
1525        /// # fn main() { test().unwrap(); }
1526        /// # fn test() -> Option<()> {
1527        #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1528        #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1529        ///
1530        /// assert_eq!(two, unsafe { one.unchecked_add(1) });
1531        /// # Some(())
1532        /// # }
1533        /// ```
1534        #[unstable(feature = "nonzero_ops", issue = "84186")]
1535        #[must_use = "this returns the result of the operation, \
1536                      without modifying the original"]
1537        #[inline]
1538        pub const unsafe fn unchecked_add(self, other: $Int) -> Self {
1539            // SAFETY: The caller ensures there is no overflow.
1540            unsafe { Self::new_unchecked(self.get().unchecked_add(other)) }
1541        }
1542
1543        /// Returns the smallest power of two greater than or equal to `self`.
1544        /// Checks for overflow and returns [`None`]
1545        /// if the next power of two is greater than the type’s maximum value.
1546        /// As a consequence, the result cannot wrap to zero.
1547        ///
1548        /// # Examples
1549        ///
1550        /// ```
1551        /// # use std::num::NonZero;
1552        /// #
1553        /// # fn main() { test().unwrap(); }
1554        /// # fn test() -> Option<()> {
1555        #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1556        #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1557        #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1558        #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1559        ///
1560        /// assert_eq!(Some(two), two.checked_next_power_of_two() );
1561        /// assert_eq!(Some(four), three.checked_next_power_of_two() );
1562        /// assert_eq!(None, max.checked_next_power_of_two() );
1563        /// # Some(())
1564        /// # }
1565        /// ```
1566        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1567        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1568        #[must_use = "this returns the result of the operation, \
1569                      without modifying the original"]
1570        #[inline]
1571        pub const fn checked_next_power_of_two(self) -> Option<Self> {
1572            if let Some(nz) = self.get().checked_next_power_of_two() {
1573                // SAFETY: The next power of two is positive
1574                // and overflow is checked.
1575                Some(unsafe { Self::new_unchecked(nz) })
1576            } else {
1577                None
1578            }
1579        }
1580
1581        /// Returns the base 2 logarithm of the number, rounded down.
1582        ///
1583        /// This is the same operation as
1584        #[doc = concat!("[`", stringify!($Int), "::ilog2`],")]
1585        /// except that it has no failure cases to worry about
1586        /// since this value can never be zero.
1587        ///
1588        /// # Examples
1589        ///
1590        /// ```
1591        /// # use std::num::NonZero;
1592        /// #
1593        /// # fn main() { test().unwrap(); }
1594        /// # fn test() -> Option<()> {
1595        #[doc = concat!("assert_eq!(NonZero::new(7", stringify!($Int), ")?.ilog2(), 2);")]
1596        #[doc = concat!("assert_eq!(NonZero::new(8", stringify!($Int), ")?.ilog2(), 3);")]
1597        #[doc = concat!("assert_eq!(NonZero::new(9", stringify!($Int), ")?.ilog2(), 3);")]
1598        /// # Some(())
1599        /// # }
1600        /// ```
1601        #[stable(feature = "int_log", since = "1.67.0")]
1602        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1603        #[must_use = "this returns the result of the operation, \
1604                      without modifying the original"]
1605        #[inline]
1606        pub const fn ilog2(self) -> u32 {
1607            Self::BITS - 1 - self.leading_zeros()
1608        }
1609
1610        /// Returns the base 10 logarithm of the number, rounded down.
1611        ///
1612        /// This is the same operation as
1613        #[doc = concat!("[`", stringify!($Int), "::ilog10`],")]
1614        /// except that it has no failure cases to worry about
1615        /// since this value can never be zero.
1616        ///
1617        /// # Examples
1618        ///
1619        /// ```
1620        /// # use std::num::NonZero;
1621        /// #
1622        /// # fn main() { test().unwrap(); }
1623        /// # fn test() -> Option<()> {
1624        #[doc = concat!("assert_eq!(NonZero::new(99", stringify!($Int), ")?.ilog10(), 1);")]
1625        #[doc = concat!("assert_eq!(NonZero::new(100", stringify!($Int), ")?.ilog10(), 2);")]
1626        #[doc = concat!("assert_eq!(NonZero::new(101", stringify!($Int), ")?.ilog10(), 2);")]
1627        /// # Some(())
1628        /// # }
1629        /// ```
1630        #[stable(feature = "int_log", since = "1.67.0")]
1631        #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1632        #[must_use = "this returns the result of the operation, \
1633                      without modifying the original"]
1634        #[inline]
1635        pub const fn ilog10(self) -> u32 {
1636            super::int_log10::$Int(self.get())
1637        }
1638
1639        /// Calculates the midpoint (average) between `self` and `rhs`.
1640        ///
1641        /// `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a
1642        /// sufficiently-large signed integral type. This implies that the result is
1643        /// always rounded towards negative infinity and that no overflow will ever occur.
1644        ///
1645        /// # Examples
1646        ///
1647        /// ```
1648        /// # use std::num::NonZero;
1649        /// #
1650        /// # fn main() { test().unwrap(); }
1651        /// # fn test() -> Option<()> {
1652        #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1653        #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1654        #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1655        ///
1656        /// assert_eq!(one.midpoint(four), two);
1657        /// assert_eq!(four.midpoint(one), two);
1658        /// # Some(())
1659        /// # }
1660        /// ```
1661        #[stable(feature = "num_midpoint", since = "1.85.0")]
1662        #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1663        #[must_use = "this returns the result of the operation, \
1664                      without modifying the original"]
1665        #[doc(alias = "average_floor")]
1666        #[doc(alias = "average")]
1667        #[inline]
1668        pub const fn midpoint(self, rhs: Self) -> Self {
1669            // SAFETY: The only way to get `0` with midpoint is to have two opposite or
1670            // near opposite numbers: (-5, 5), (0, 1), (0, 0) which is impossible because
1671            // of the unsignedness of this number and also because `Self` is guaranteed to
1672            // never being 0.
1673            unsafe { Self::new_unchecked(self.get().midpoint(rhs.get())) }
1674        }
1675
1676        /// Returns `true` if and only if `self == (1 << k)` for some `k`.
1677        ///
1678        /// On many architectures, this function can perform better than `is_power_of_two()`
1679        /// on the underlying integer type, as special handling of zero can be avoided.
1680        ///
1681        /// # Examples
1682        ///
1683        /// ```
1684        /// # use std::num::NonZero;
1685        /// #
1686        /// # fn main() { test().unwrap(); }
1687        /// # fn test() -> Option<()> {
1688        #[doc = concat!("let eight = NonZero::new(8", stringify!($Int), ")?;")]
1689        /// assert!(eight.is_power_of_two());
1690        #[doc = concat!("let ten = NonZero::new(10", stringify!($Int), ")?;")]
1691        /// assert!(!ten.is_power_of_two());
1692        /// # Some(())
1693        /// # }
1694        /// ```
1695        #[must_use]
1696        #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1697        #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1698        #[inline]
1699        pub const fn is_power_of_two(self) -> bool {
1700            // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
1701            // On the basic x86-64 target, this saves 3 instructions for the zero check.
1702            // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
1703            // compared to the `POPCNT` implementation on the underlying integer type.
1704
1705            intrinsics::ctpop(self.get()) < 2
1706        }
1707
1708        /// Returns the square root of the number, rounded down.
1709        ///
1710        /// # Examples
1711        ///
1712        /// ```
1713        /// # use std::num::NonZero;
1714        /// #
1715        /// # fn main() { test().unwrap(); }
1716        /// # fn test() -> Option<()> {
1717        #[doc = concat!("let ten = NonZero::new(10", stringify!($Int), ")?;")]
1718        #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1719        ///
1720        /// assert_eq!(ten.isqrt(), three);
1721        /// # Some(())
1722        /// # }
1723        /// ```
1724        #[stable(feature = "isqrt", since = "1.84.0")]
1725        #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
1726        #[must_use = "this returns the result of the operation, \
1727                      without modifying the original"]
1728        #[inline]
1729        pub const fn isqrt(self) -> Self {
1730            let result = self.get().isqrt();
1731
1732            // SAFETY: Integer square root is a monotonically nondecreasing
1733            // function, which means that increasing the input will never cause
1734            // the output to decrease. Thus, since the input for nonzero
1735            // unsigned integers has a lower bound of 1, the lower bound of the
1736            // results will be sqrt(1), which is 1, so a result can't be zero.
1737            unsafe { Self::new_unchecked(result) }
1738        }
1739
1740        /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
1741        ///
1742        /// # Examples
1743        ///
1744        /// ```
1745        /// # use std::num::NonZero;
1746        ///
1747        #[doc = concat!("let n = NonZero::<", stringify!($Int), ">::MAX;")]
1748        ///
1749        #[doc = concat!("assert_eq!(n.cast_signed(), NonZero::new(-1", stringify!($Sint), ").unwrap());")]
1750        /// ```
1751        #[stable(feature = "integer_sign_cast", since = "1.87.0")]
1752        #[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
1753        #[must_use = "this returns the result of the operation, \
1754                      without modifying the original"]
1755        #[inline(always)]
1756        pub const fn cast_signed(self) -> NonZero<$Sint> {
1757            // SAFETY: `self.get()` can't be zero
1758            unsafe { NonZero::new_unchecked(self.get().cast_signed()) }
1759        }
1760    };
1761
1762    // Associated items for signed nonzero types only.
1763    (
1764        Primitive = signed $Int:ident,
1765        SignedPrimitive = $Sint:ty,
1766        UnsignedPrimitive = $Uint:ty,
1767    ) => {
1768        /// The smallest value that can be represented by this non-zero
1769        /// integer type,
1770        #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1771        ///
1772        /// Note: While most integer types are defined for every whole
1773        /// number between `MIN` and `MAX`, signed non-zero integers are
1774        /// a special case. They have a "gap" at 0.
1775        ///
1776        /// # Examples
1777        ///
1778        /// ```
1779        /// # use std::num::NonZero;
1780        /// #
1781        #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MIN.get(), ", stringify!($Int), "::MIN);")]
1782        /// ```
1783        #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1784        pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1785
1786        /// The largest value that can be represented by this non-zero
1787        /// integer type,
1788        #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1789        ///
1790        /// Note: While most integer types are defined for every whole
1791        /// number between `MIN` and `MAX`, signed non-zero integers are
1792        /// a special case. They have a "gap" at 0.
1793        ///
1794        /// # Examples
1795        ///
1796        /// ```
1797        /// # use std::num::NonZero;
1798        /// #
1799        #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MAX.get(), ", stringify!($Int), "::MAX);")]
1800        /// ```
1801        #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1802        pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1803
1804        /// Computes the absolute value of self.
1805        #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
1806        /// for documentation on overflow behavior.
1807        ///
1808        /// # Example
1809        ///
1810        /// ```
1811        /// # use std::num::NonZero;
1812        /// #
1813        /// # fn main() { test().unwrap(); }
1814        /// # fn test() -> Option<()> {
1815        #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1816        #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1817        ///
1818        /// assert_eq!(pos, pos.abs());
1819        /// assert_eq!(pos, neg.abs());
1820        /// # Some(())
1821        /// # }
1822        /// ```
1823        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1824        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1825        #[must_use = "this returns the result of the operation, \
1826                      without modifying the original"]
1827        #[inline]
1828        pub const fn abs(self) -> Self {
1829            // SAFETY: This cannot overflow to zero.
1830            unsafe { Self::new_unchecked(self.get().abs()) }
1831        }
1832
1833        /// Checked absolute value.
1834        /// Checks for overflow and returns [`None`] if
1835        #[doc = concat!("`self == NonZero::<", stringify!($Int), ">::MIN`.")]
1836        /// The result cannot be zero.
1837        ///
1838        /// # Example
1839        ///
1840        /// ```
1841        /// # use std::num::NonZero;
1842        /// #
1843        /// # fn main() { test().unwrap(); }
1844        /// # fn test() -> Option<()> {
1845        #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1846        #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1847        #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1848        ///
1849        /// assert_eq!(Some(pos), neg.checked_abs());
1850        /// assert_eq!(None, min.checked_abs());
1851        /// # Some(())
1852        /// # }
1853        /// ```
1854        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1855        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1856        #[must_use = "this returns the result of the operation, \
1857                      without modifying the original"]
1858        #[inline]
1859        pub const fn checked_abs(self) -> Option<Self> {
1860            if let Some(nz) = self.get().checked_abs() {
1861                // SAFETY: absolute value of nonzero cannot yield zero values.
1862                Some(unsafe { Self::new_unchecked(nz) })
1863            } else {
1864                None
1865            }
1866        }
1867
1868        /// Computes the absolute value of self,
1869        /// with overflow information, see
1870        #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
1871        ///
1872        /// # Example
1873        ///
1874        /// ```
1875        /// # use std::num::NonZero;
1876        /// #
1877        /// # fn main() { test().unwrap(); }
1878        /// # fn test() -> Option<()> {
1879        #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1880        #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1881        #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1882        ///
1883        /// assert_eq!((pos, false), pos.overflowing_abs());
1884        /// assert_eq!((pos, false), neg.overflowing_abs());
1885        /// assert_eq!((min, true), min.overflowing_abs());
1886        /// # Some(())
1887        /// # }
1888        /// ```
1889        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1890        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1891        #[must_use = "this returns the result of the operation, \
1892                      without modifying the original"]
1893        #[inline]
1894        pub const fn overflowing_abs(self) -> (Self, bool) {
1895            let (nz, flag) = self.get().overflowing_abs();
1896            (
1897                // SAFETY: absolute value of nonzero cannot yield zero values.
1898                unsafe { Self::new_unchecked(nz) },
1899                flag,
1900            )
1901        }
1902
1903        /// Saturating absolute value, see
1904        #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
1905        ///
1906        /// # Example
1907        ///
1908        /// ```
1909        /// # use std::num::NonZero;
1910        /// #
1911        /// # fn main() { test().unwrap(); }
1912        /// # fn test() -> Option<()> {
1913        #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1914        #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1915        #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1916        #[doc = concat!("let min_plus = NonZero::new(", stringify!($Int), "::MIN + 1)?;")]
1917        #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1918        ///
1919        /// assert_eq!(pos, pos.saturating_abs());
1920        /// assert_eq!(pos, neg.saturating_abs());
1921        /// assert_eq!(max, min.saturating_abs());
1922        /// assert_eq!(max, min_plus.saturating_abs());
1923        /// # Some(())
1924        /// # }
1925        /// ```
1926        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1927        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1928        #[must_use = "this returns the result of the operation, \
1929                      without modifying the original"]
1930        #[inline]
1931        pub const fn saturating_abs(self) -> Self {
1932            // SAFETY: absolute value of nonzero cannot yield zero values.
1933            unsafe { Self::new_unchecked(self.get().saturating_abs()) }
1934        }
1935
1936        /// Wrapping absolute value, see
1937        #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
1938        ///
1939        /// # Example
1940        ///
1941        /// ```
1942        /// # use std::num::NonZero;
1943        /// #
1944        /// # fn main() { test().unwrap(); }
1945        /// # fn test() -> Option<()> {
1946        #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1947        #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1948        #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1949        #[doc = concat!("# let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1950        ///
1951        /// assert_eq!(pos, pos.wrapping_abs());
1952        /// assert_eq!(pos, neg.wrapping_abs());
1953        /// assert_eq!(min, min.wrapping_abs());
1954        /// assert_eq!(max, (-max).wrapping_abs());
1955        /// # Some(())
1956        /// # }
1957        /// ```
1958        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1959        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1960        #[must_use = "this returns the result of the operation, \
1961                      without modifying the original"]
1962        #[inline]
1963        pub const fn wrapping_abs(self) -> Self {
1964            // SAFETY: absolute value of nonzero cannot yield zero values.
1965            unsafe { Self::new_unchecked(self.get().wrapping_abs()) }
1966        }
1967
1968        /// Computes the absolute value of self
1969        /// without any wrapping or panicking.
1970        ///
1971        /// # Example
1972        ///
1973        /// ```
1974        /// # use std::num::NonZero;
1975        /// #
1976        /// # fn main() { test().unwrap(); }
1977        /// # fn test() -> Option<()> {
1978        #[doc = concat!("let u_pos = NonZero::new(1", stringify!($Uint), ")?;")]
1979        #[doc = concat!("let i_pos = NonZero::new(1", stringify!($Int), ")?;")]
1980        #[doc = concat!("let i_neg = NonZero::new(-1", stringify!($Int), ")?;")]
1981        #[doc = concat!("let i_min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1982        #[doc = concat!("let u_max = NonZero::new(", stringify!($Uint), "::MAX / 2 + 1)?;")]
1983        ///
1984        /// assert_eq!(u_pos, i_pos.unsigned_abs());
1985        /// assert_eq!(u_pos, i_neg.unsigned_abs());
1986        /// assert_eq!(u_max, i_min.unsigned_abs());
1987        /// # Some(())
1988        /// # }
1989        /// ```
1990        #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1991        #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1992        #[must_use = "this returns the result of the operation, \
1993                      without modifying the original"]
1994        #[inline]
1995        pub const fn unsigned_abs(self) -> NonZero<$Uint> {
1996            // SAFETY: absolute value of nonzero cannot yield zero values.
1997            unsafe { NonZero::new_unchecked(self.get().unsigned_abs()) }
1998        }
1999
2000        /// Returns `true` if `self` is positive and `false` if the
2001        /// number is negative.
2002        ///
2003        /// # Example
2004        ///
2005        /// ```
2006        /// # use std::num::NonZero;
2007        /// #
2008        /// # fn main() { test().unwrap(); }
2009        /// # fn test() -> Option<()> {
2010        #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2011        #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2012        ///
2013        /// assert!(pos_five.is_positive());
2014        /// assert!(!neg_five.is_positive());
2015        /// # Some(())
2016        /// # }
2017        /// ```
2018        #[must_use]
2019        #[inline]
2020        #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2021        #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2022        pub const fn is_positive(self) -> bool {
2023            self.get().is_positive()
2024        }
2025
2026        /// Returns `true` if `self` is negative and `false` if the
2027        /// number is positive.
2028        ///
2029        /// # Example
2030        ///
2031        /// ```
2032        /// # use std::num::NonZero;
2033        /// #
2034        /// # fn main() { test().unwrap(); }
2035        /// # fn test() -> Option<()> {
2036        #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2037        #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2038        ///
2039        /// assert!(neg_five.is_negative());
2040        /// assert!(!pos_five.is_negative());
2041        /// # Some(())
2042        /// # }
2043        /// ```
2044        #[must_use]
2045        #[inline]
2046        #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2047        #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2048        pub const fn is_negative(self) -> bool {
2049            self.get().is_negative()
2050        }
2051
2052        /// Checked negation. Computes `-self`,
2053        #[doc = concat!("returning `None` if `self == NonZero::<", stringify!($Int), ">::MIN`.")]
2054        ///
2055        /// # Example
2056        ///
2057        /// ```
2058        /// # use std::num::NonZero;
2059        /// #
2060        /// # fn main() { test().unwrap(); }
2061        /// # fn test() -> Option<()> {
2062        #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2063        #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2064        #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2065        ///
2066        /// assert_eq!(pos_five.checked_neg(), Some(neg_five));
2067        /// assert_eq!(min.checked_neg(), None);
2068        /// # Some(())
2069        /// # }
2070        /// ```
2071        #[inline]
2072        #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2073        #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2074        pub const fn checked_neg(self) -> Option<Self> {
2075            if let Some(result) = self.get().checked_neg() {
2076                // SAFETY: negation of nonzero cannot yield zero values.
2077                return Some(unsafe { Self::new_unchecked(result) });
2078            }
2079            None
2080        }
2081
2082        /// Negates self, overflowing if this is equal to the minimum value.
2083        ///
2084        #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")]
2085        /// for documentation on overflow behavior.
2086        ///
2087        /// # Example
2088        ///
2089        /// ```
2090        /// # use std::num::NonZero;
2091        /// #
2092        /// # fn main() { test().unwrap(); }
2093        /// # fn test() -> Option<()> {
2094        #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2095        #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2096        #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2097        ///
2098        /// assert_eq!(pos_five.overflowing_neg(), (neg_five, false));
2099        /// assert_eq!(min.overflowing_neg(), (min, true));
2100        /// # Some(())
2101        /// # }
2102        /// ```
2103        #[inline]
2104        #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2105        #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2106        pub const fn overflowing_neg(self) -> (Self, bool) {
2107            let (result, overflow) = self.get().overflowing_neg();
2108            // SAFETY: negation of nonzero cannot yield zero values.
2109            ((unsafe { Self::new_unchecked(result) }), overflow)
2110        }
2111
2112        /// Saturating negation. Computes `-self`,
2113        #[doc = concat!("returning [`NonZero::<", stringify!($Int), ">::MAX`]")]
2114        #[doc = concat!("if `self == NonZero::<", stringify!($Int), ">::MIN`")]
2115        /// instead of overflowing.
2116        ///
2117        /// # Example
2118        ///
2119        /// ```
2120        /// # use std::num::NonZero;
2121        /// #
2122        /// # fn main() { test().unwrap(); }
2123        /// # fn test() -> Option<()> {
2124        #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2125        #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2126        #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2127        #[doc = concat!("let min_plus_one = NonZero::new(", stringify!($Int), "::MIN + 1)?;")]
2128        #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
2129        ///
2130        /// assert_eq!(pos_five.saturating_neg(), neg_five);
2131        /// assert_eq!(min.saturating_neg(), max);
2132        /// assert_eq!(max.saturating_neg(), min_plus_one);
2133        /// # Some(())
2134        /// # }
2135        /// ```
2136        #[inline]
2137        #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2138        #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2139        pub const fn saturating_neg(self) -> Self {
2140            if let Some(result) = self.checked_neg() {
2141                return result;
2142            }
2143            Self::MAX
2144        }
2145
2146        /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
2147        /// of the type.
2148        ///
2149        #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")]
2150        /// for documentation on overflow behavior.
2151        ///
2152        /// # Example
2153        ///
2154        /// ```
2155        /// # use std::num::NonZero;
2156        /// #
2157        /// # fn main() { test().unwrap(); }
2158        /// # fn test() -> Option<()> {
2159        #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2160        #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2161        #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2162        ///
2163        /// assert_eq!(pos_five.wrapping_neg(), neg_five);
2164        /// assert_eq!(min.wrapping_neg(), min);
2165        /// # Some(())
2166        /// # }
2167        /// ```
2168        #[inline]
2169        #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2170        #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2171        pub const fn wrapping_neg(self) -> Self {
2172            let result = self.get().wrapping_neg();
2173            // SAFETY: negation of nonzero cannot yield zero values.
2174            unsafe { Self::new_unchecked(result) }
2175        }
2176
2177        /// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
2178        ///
2179        /// # Examples
2180        ///
2181        /// ```
2182        /// # use std::num::NonZero;
2183        ///
2184        #[doc = concat!("let n = NonZero::new(-1", stringify!($Int), ").unwrap();")]
2185        ///
2186        #[doc = concat!("assert_eq!(n.cast_unsigned(), NonZero::<", stringify!($Uint), ">::MAX);")]
2187        /// ```
2188        #[stable(feature = "integer_sign_cast", since = "1.87.0")]
2189        #[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
2190        #[must_use = "this returns the result of the operation, \
2191                      without modifying the original"]
2192        #[inline(always)]
2193        pub const fn cast_unsigned(self) -> NonZero<$Uint> {
2194            // SAFETY: `self.get()` can't be zero
2195            unsafe { NonZero::new_unchecked(self.get().cast_unsigned()) }
2196        }
2197
2198    };
2199}
2200
2201nonzero_integer! {
2202    Self = NonZeroU8,
2203    Primitive = unsigned u8,
2204    SignedPrimitive = i8,
2205    rot = 2,
2206    rot_op = "0x82",
2207    rot_result = "0xa",
2208    swap_op = "0x12",
2209    swapped = "0x12",
2210    reversed = "0x48",
2211}
2212
2213nonzero_integer! {
2214    Self = NonZeroU16,
2215    Primitive = unsigned u16,
2216    SignedPrimitive = i16,
2217    rot = 4,
2218    rot_op = "0xa003",
2219    rot_result = "0x3a",
2220    swap_op = "0x1234",
2221    swapped = "0x3412",
2222    reversed = "0x2c48",
2223}
2224
2225nonzero_integer! {
2226    Self = NonZeroU32,
2227    Primitive = unsigned u32,
2228    SignedPrimitive = i32,
2229    rot = 8,
2230    rot_op = "0x10000b3",
2231    rot_result = "0xb301",
2232    swap_op = "0x12345678",
2233    swapped = "0x78563412",
2234    reversed = "0x1e6a2c48",
2235}
2236
2237nonzero_integer! {
2238    Self = NonZeroU64,
2239    Primitive = unsigned u64,
2240    SignedPrimitive = i64,
2241    rot = 12,
2242    rot_op = "0xaa00000000006e1",
2243    rot_result = "0x6e10aa",
2244    swap_op = "0x1234567890123456",
2245    swapped = "0x5634129078563412",
2246    reversed = "0x6a2c48091e6a2c48",
2247}
2248
2249nonzero_integer! {
2250    Self = NonZeroU128,
2251    Primitive = unsigned u128,
2252    SignedPrimitive = i128,
2253    rot = 16,
2254    rot_op = "0x13f40000000000000000000000004f76",
2255    rot_result = "0x4f7613f4",
2256    swap_op = "0x12345678901234567890123456789012",
2257    swapped = "0x12907856341290785634129078563412",
2258    reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
2259}
2260
2261#[cfg(target_pointer_width = "16")]
2262nonzero_integer! {
2263    Self = NonZeroUsize,
2264    Primitive = unsigned usize,
2265    SignedPrimitive = isize,
2266    rot = 4,
2267    rot_op = "0xa003",
2268    rot_result = "0x3a",
2269    swap_op = "0x1234",
2270    swapped = "0x3412",
2271    reversed = "0x2c48",
2272}
2273
2274#[cfg(target_pointer_width = "32")]
2275nonzero_integer! {
2276    Self = NonZeroUsize,
2277    Primitive = unsigned usize,
2278    SignedPrimitive = isize,
2279    rot = 8,
2280    rot_op = "0x10000b3",
2281    rot_result = "0xb301",
2282    swap_op = "0x12345678",
2283    swapped = "0x78563412",
2284    reversed = "0x1e6a2c48",
2285}
2286
2287#[cfg(target_pointer_width = "64")]
2288nonzero_integer! {
2289    Self = NonZeroUsize,
2290    Primitive = unsigned usize,
2291    SignedPrimitive = isize,
2292    rot = 12,
2293    rot_op = "0xaa00000000006e1",
2294    rot_result = "0x6e10aa",
2295    swap_op = "0x1234567890123456",
2296    swapped = "0x5634129078563412",
2297    reversed = "0x6a2c48091e6a2c48",
2298}
2299
2300nonzero_integer! {
2301    Self = NonZeroI8,
2302    Primitive = signed i8,
2303    UnsignedPrimitive = u8,
2304    rot = 2,
2305    rot_op = "-0x7e",
2306    rot_result = "0xa",
2307    swap_op = "0x12",
2308    swapped = "0x12",
2309    reversed = "0x48",
2310}
2311
2312nonzero_integer! {
2313    Self = NonZeroI16,
2314    Primitive = signed i16,
2315    UnsignedPrimitive = u16,
2316    rot = 4,
2317    rot_op = "-0x5ffd",
2318    rot_result = "0x3a",
2319    swap_op = "0x1234",
2320    swapped = "0x3412",
2321    reversed = "0x2c48",
2322}
2323
2324nonzero_integer! {
2325    Self = NonZeroI32,
2326    Primitive = signed i32,
2327    UnsignedPrimitive = u32,
2328    rot = 8,
2329    rot_op = "0x10000b3",
2330    rot_result = "0xb301",
2331    swap_op = "0x12345678",
2332    swapped = "0x78563412",
2333    reversed = "0x1e6a2c48",
2334}
2335
2336nonzero_integer! {
2337    Self = NonZeroI64,
2338    Primitive = signed i64,
2339    UnsignedPrimitive = u64,
2340    rot = 12,
2341    rot_op = "0xaa00000000006e1",
2342    rot_result = "0x6e10aa",
2343    swap_op = "0x1234567890123456",
2344    swapped = "0x5634129078563412",
2345    reversed = "0x6a2c48091e6a2c48",
2346}
2347
2348nonzero_integer! {
2349    Self = NonZeroI128,
2350    Primitive = signed i128,
2351    UnsignedPrimitive = u128,
2352    rot = 16,
2353    rot_op = "0x13f40000000000000000000000004f76",
2354    rot_result = "0x4f7613f4",
2355    swap_op = "0x12345678901234567890123456789012",
2356    swapped = "0x12907856341290785634129078563412",
2357    reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
2358}
2359
2360#[cfg(target_pointer_width = "16")]
2361nonzero_integer! {
2362    Self = NonZeroIsize,
2363    Primitive = signed isize,
2364    UnsignedPrimitive = usize,
2365    rot = 4,
2366    rot_op = "-0x5ffd",
2367    rot_result = "0x3a",
2368    swap_op = "0x1234",
2369    swapped = "0x3412",
2370    reversed = "0x2c48",
2371}
2372
2373#[cfg(target_pointer_width = "32")]
2374nonzero_integer! {
2375    Self = NonZeroIsize,
2376    Primitive = signed isize,
2377    UnsignedPrimitive = usize,
2378    rot = 8,
2379    rot_op = "0x10000b3",
2380    rot_result = "0xb301",
2381    swap_op = "0x12345678",
2382    swapped = "0x78563412",
2383    reversed = "0x1e6a2c48",
2384}
2385
2386#[cfg(target_pointer_width = "64")]
2387nonzero_integer! {
2388    Self = NonZeroIsize,
2389    Primitive = signed isize,
2390    UnsignedPrimitive = usize,
2391    rot = 12,
2392    rot_op = "0xaa00000000006e1",
2393    rot_result = "0x6e10aa",
2394    swap_op = "0x1234567890123456",
2395    swapped = "0x5634129078563412",
2396    reversed = "0x6a2c48091e6a2c48",
2397}