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