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