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