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