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