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