Skip to main content

core/num/
nonzero.rs

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