core/num/
nonzero.rs

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