Skip to main content

core/num/
nonzero.rs

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