Skip to main content

core/num/
nonzero.rs

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