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