core/num/
nonzero.rs

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