Skip to main content

core/num/
nonzero.rs

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