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 /// # use std::num::NonZero;
1377 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ").unwrap();")]
1378 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX).unwrap();")]
1379 /// assert_eq!(one.div_ceil(max), one);
1380 ///
1381 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ").unwrap();")]
1382 #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ").unwrap();")]
1383 /// assert_eq!(three.div_ceil(two), two);
1384 /// ```
1385 #[stable(feature = "unsigned_nonzero_div_ceil", since = "CURRENT_RUSTC_VERSION")]
1386 #[rustc_const_stable(
1387 feature = "unsigned_nonzero_div_ceil",
1388 since = "CURRENT_RUSTC_VERSION"
1389 )]
1390 #[must_use = "this returns the result of the operation, \
1391 without modifying the original"]
1392 #[inline]
1393 pub const fn div_ceil(self, rhs: Self) -> Self {
1394 let v = self.get().div_ceil(rhs.get());
1395 // SAFETY: ceiled division of two positive integers can never be zero.
1396 unsafe { Self::new_unchecked(v) }
1397 }
1398 }
1399 };
1400 // Impls for signed nonzero types only.
1401 (signed $Int:ty) => {
1402 #[stable(feature = "signed_nonzero_neg", since = "1.71.0")]
1403 #[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1404 impl const Neg for NonZero<$Int> {
1405 type Output = Self;
1406
1407 #[inline]
1408 fn neg(self) -> Self {
1409 // SAFETY: negation of nonzero cannot yield zero values.
1410 unsafe { Self::new_unchecked(self.get().neg()) }
1411 }
1412 }
1413
1414 forward_ref_unop! { impl Neg, neg for NonZero<$Int>,
1415 #[stable(feature = "signed_nonzero_neg", since = "1.71.0")]
1416 #[rustc_const_unstable(feature = "const_ops", issue = "143802")] }
1417 };
1418}
1419
1420#[rustfmt::skip] // https://github.com/rust-lang/rustfmt/issues/5974
1421macro_rules! nonzero_integer_signedness_dependent_methods {
1422 // Associated items for unsigned nonzero types only.
1423 (
1424 Primitive = unsigned $Int:ident,
1425 SignedPrimitive = $Sint:ty,
1426 UnsignedPrimitive = $Uint:ty,
1427 ) => {
1428 /// The smallest value that can be represented by this non-zero
1429 /// integer type, 1.
1430 ///
1431 /// # Examples
1432 ///
1433 /// ```
1434 /// # use std::num::NonZero;
1435 /// #
1436 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MIN.get(), 1", stringify!($Int), ");")]
1437 /// ```
1438 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1439 pub const MIN: Self = Self::new(1).unwrap();
1440
1441 /// The largest value that can be represented by this non-zero
1442 /// integer type,
1443 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1444 ///
1445 /// # Examples
1446 ///
1447 /// ```
1448 /// # use std::num::NonZero;
1449 /// #
1450 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MAX.get(), ", stringify!($Int), "::MAX);")]
1451 /// ```
1452 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1453 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1454
1455 /// Adds an unsigned integer to a non-zero value.
1456 /// Checks for overflow and returns [`None`] on overflow.
1457 /// As a consequence, the result cannot wrap to zero.
1458 ///
1459 ///
1460 /// # Examples
1461 ///
1462 /// ```
1463 /// # use std::num::NonZero;
1464 /// #
1465 /// # fn main() { test().unwrap(); }
1466 /// # fn test() -> Option<()> {
1467 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1468 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1469 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1470 ///
1471 /// assert_eq!(Some(two), one.checked_add(1));
1472 /// assert_eq!(None, max.checked_add(1));
1473 /// # Some(())
1474 /// # }
1475 /// ```
1476 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1477 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1478 #[must_use = "this returns the result of the operation, \
1479 without modifying the original"]
1480 #[inline]
1481 pub const fn checked_add(self, other: $Int) -> Option<Self> {
1482 if let Some(result) = self.get().checked_add(other) {
1483 // SAFETY:
1484 // - `checked_add` returns `None` on overflow
1485 // - `self` is non-zero
1486 // - the only way to get zero from an addition without overflow is for both
1487 // sides to be zero
1488 //
1489 // So the result cannot be zero.
1490 Some(unsafe { Self::new_unchecked(result) })
1491 } else {
1492 None
1493 }
1494 }
1495
1496 /// Adds an unsigned integer to a non-zero value.
1497 #[doc = concat!("Return [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")]
1498 ///
1499 /// # Examples
1500 ///
1501 /// ```
1502 /// # use std::num::NonZero;
1503 /// #
1504 /// # fn main() { test().unwrap(); }
1505 /// # fn test() -> Option<()> {
1506 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1507 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1508 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1509 ///
1510 /// assert_eq!(two, one.saturating_add(1));
1511 /// assert_eq!(max, max.saturating_add(1));
1512 /// # Some(())
1513 /// # }
1514 /// ```
1515 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1516 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1517 #[must_use = "this returns the result of the operation, \
1518 without modifying the original"]
1519 #[inline]
1520 pub const fn saturating_add(self, other: $Int) -> Self {
1521 // SAFETY:
1522 // - `saturating_add` returns `u*::MAX` on overflow, which is non-zero
1523 // - `self` is non-zero
1524 // - the only way to get zero from an addition without overflow is for both
1525 // sides to be zero
1526 //
1527 // So the result cannot be zero.
1528 unsafe { Self::new_unchecked(self.get().saturating_add(other)) }
1529 }
1530
1531 /// Adds an unsigned integer to a non-zero value,
1532 /// assuming overflow cannot occur.
1533 /// Overflow is unchecked, and it is undefined behavior to overflow
1534 /// *even if the result would wrap to a non-zero value*.
1535 /// The behavior is undefined as soon as
1536 #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
1537 ///
1538 /// # Examples
1539 ///
1540 /// ```
1541 /// #![feature(nonzero_ops)]
1542 ///
1543 /// # use std::num::NonZero;
1544 /// #
1545 /// # fn main() { test().unwrap(); }
1546 /// # fn test() -> Option<()> {
1547 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1548 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1549 ///
1550 /// assert_eq!(two, unsafe { one.unchecked_add(1) });
1551 /// # Some(())
1552 /// # }
1553 /// ```
1554 #[unstable(feature = "nonzero_ops", issue = "84186")]
1555 #[must_use = "this returns the result of the operation, \
1556 without modifying the original"]
1557 #[inline]
1558 pub const unsafe fn unchecked_add(self, other: $Int) -> Self {
1559 // SAFETY: The caller ensures there is no overflow.
1560 unsafe { Self::new_unchecked(self.get().unchecked_add(other)) }
1561 }
1562
1563 /// Returns the smallest power of two greater than or equal to `self`.
1564 /// Checks for overflow and returns [`None`]
1565 /// if the next power of two is greater than the type’s maximum value.
1566 /// As a consequence, the result cannot wrap to zero.
1567 ///
1568 /// # Examples
1569 ///
1570 /// ```
1571 /// # use std::num::NonZero;
1572 /// #
1573 /// # fn main() { test().unwrap(); }
1574 /// # fn test() -> Option<()> {
1575 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1576 #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1577 #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1578 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1579 ///
1580 /// assert_eq!(Some(two), two.checked_next_power_of_two() );
1581 /// assert_eq!(Some(four), three.checked_next_power_of_two() );
1582 /// assert_eq!(None, max.checked_next_power_of_two() );
1583 /// # Some(())
1584 /// # }
1585 /// ```
1586 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1587 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1588 #[must_use = "this returns the result of the operation, \
1589 without modifying the original"]
1590 #[inline]
1591 pub const fn checked_next_power_of_two(self) -> Option<Self> {
1592 if let Some(nz) = self.get().checked_next_power_of_two() {
1593 // SAFETY: The next power of two is positive
1594 // and overflow is checked.
1595 Some(unsafe { Self::new_unchecked(nz) })
1596 } else {
1597 None
1598 }
1599 }
1600
1601 /// Returns the base 2 logarithm of the number, rounded down.
1602 ///
1603 /// This is the same operation as
1604 #[doc = concat!("[`", stringify!($Int), "::ilog2`],")]
1605 /// except that it has no failure cases to worry about
1606 /// since this value can never be zero.
1607 ///
1608 /// # Examples
1609 ///
1610 /// ```
1611 /// # use std::num::NonZero;
1612 /// #
1613 /// # fn main() { test().unwrap(); }
1614 /// # fn test() -> Option<()> {
1615 #[doc = concat!("assert_eq!(NonZero::new(7", stringify!($Int), ")?.ilog2(), 2);")]
1616 #[doc = concat!("assert_eq!(NonZero::new(8", stringify!($Int), ")?.ilog2(), 3);")]
1617 #[doc = concat!("assert_eq!(NonZero::new(9", stringify!($Int), ")?.ilog2(), 3);")]
1618 /// # Some(())
1619 /// # }
1620 /// ```
1621 #[stable(feature = "int_log", since = "1.67.0")]
1622 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1623 #[must_use = "this returns the result of the operation, \
1624 without modifying the original"]
1625 #[inline]
1626 pub const fn ilog2(self) -> u32 {
1627 Self::BITS - 1 - self.leading_zeros()
1628 }
1629
1630 /// Returns the base 10 logarithm of the number, rounded down.
1631 ///
1632 /// This is the same operation as
1633 #[doc = concat!("[`", stringify!($Int), "::ilog10`],")]
1634 /// except that it has no failure cases to worry about
1635 /// since this value can never be zero.
1636 ///
1637 /// # Examples
1638 ///
1639 /// ```
1640 /// # use std::num::NonZero;
1641 /// #
1642 /// # fn main() { test().unwrap(); }
1643 /// # fn test() -> Option<()> {
1644 #[doc = concat!("assert_eq!(NonZero::new(99", stringify!($Int), ")?.ilog10(), 1);")]
1645 #[doc = concat!("assert_eq!(NonZero::new(100", stringify!($Int), ")?.ilog10(), 2);")]
1646 #[doc = concat!("assert_eq!(NonZero::new(101", stringify!($Int), ")?.ilog10(), 2);")]
1647 /// # Some(())
1648 /// # }
1649 /// ```
1650 #[stable(feature = "int_log", since = "1.67.0")]
1651 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1652 #[must_use = "this returns the result of the operation, \
1653 without modifying the original"]
1654 #[inline]
1655 pub const fn ilog10(self) -> u32 {
1656 super::int_log10::$Int(self.get())
1657 }
1658
1659 /// Calculates the midpoint (average) between `self` and `rhs`.
1660 ///
1661 /// `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a
1662 /// sufficiently-large signed integral type. This implies that the result is
1663 /// always rounded towards negative infinity and that no overflow will ever occur.
1664 ///
1665 /// # Examples
1666 ///
1667 /// ```
1668 /// # use std::num::NonZero;
1669 /// #
1670 /// # fn main() { test().unwrap(); }
1671 /// # fn test() -> Option<()> {
1672 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1673 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1674 #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1675 ///
1676 /// assert_eq!(one.midpoint(four), two);
1677 /// assert_eq!(four.midpoint(one), two);
1678 /// # Some(())
1679 /// # }
1680 /// ```
1681 #[stable(feature = "num_midpoint", since = "1.85.0")]
1682 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1683 #[must_use = "this returns the result of the operation, \
1684 without modifying the original"]
1685 #[doc(alias = "average_floor")]
1686 #[doc(alias = "average")]
1687 #[inline]
1688 pub const fn midpoint(self, rhs: Self) -> Self {
1689 // SAFETY: The only way to get `0` with midpoint is to have two opposite or
1690 // near opposite numbers: (-5, 5), (0, 1), (0, 0) which is impossible because
1691 // of the unsignedness of this number and also because `Self` is guaranteed to
1692 // never being 0.
1693 unsafe { Self::new_unchecked(self.get().midpoint(rhs.get())) }
1694 }
1695
1696 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
1697 ///
1698 /// On many architectures, this function can perform better than `is_power_of_two()`
1699 /// on the underlying integer type, as special handling of zero can be avoided.
1700 ///
1701 /// # Examples
1702 ///
1703 /// ```
1704 /// # use std::num::NonZero;
1705 /// #
1706 /// # fn main() { test().unwrap(); }
1707 /// # fn test() -> Option<()> {
1708 #[doc = concat!("let eight = NonZero::new(8", stringify!($Int), ")?;")]
1709 /// assert!(eight.is_power_of_two());
1710 #[doc = concat!("let ten = NonZero::new(10", stringify!($Int), ")?;")]
1711 /// assert!(!ten.is_power_of_two());
1712 /// # Some(())
1713 /// # }
1714 /// ```
1715 #[must_use]
1716 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1717 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1718 #[inline]
1719 pub const fn is_power_of_two(self) -> bool {
1720 // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
1721 // On the basic x86-64 target, this saves 3 instructions for the zero check.
1722 // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
1723 // compared to the `POPCNT` implementation on the underlying integer type.
1724
1725 intrinsics::ctpop(self.get()) < 2
1726 }
1727
1728 /// Returns the square root of the number, rounded down.
1729 ///
1730 /// # Examples
1731 ///
1732 /// ```
1733 /// # use std::num::NonZero;
1734 /// #
1735 /// # fn main() { test().unwrap(); }
1736 /// # fn test() -> Option<()> {
1737 #[doc = concat!("let ten = NonZero::new(10", stringify!($Int), ")?;")]
1738 #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1739 ///
1740 /// assert_eq!(ten.isqrt(), three);
1741 /// # Some(())
1742 /// # }
1743 /// ```
1744 #[stable(feature = "isqrt", since = "1.84.0")]
1745 #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
1746 #[must_use = "this returns the result of the operation, \
1747 without modifying the original"]
1748 #[inline]
1749 pub const fn isqrt(self) -> Self {
1750 let result = self.get().isqrt();
1751
1752 // SAFETY: Integer square root is a monotonically nondecreasing
1753 // function, which means that increasing the input will never cause
1754 // the output to decrease. Thus, since the input for nonzero
1755 // unsigned integers has a lower bound of 1, the lower bound of the
1756 // results will be sqrt(1), which is 1, so a result can't be zero.
1757 unsafe { Self::new_unchecked(result) }
1758 }
1759
1760 /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
1761 ///
1762 /// # Examples
1763 ///
1764 /// ```
1765 /// # use std::num::NonZero;
1766 ///
1767 #[doc = concat!("let n = NonZero::<", stringify!($Int), ">::MAX;")]
1768 ///
1769 #[doc = concat!("assert_eq!(n.cast_signed(), NonZero::new(-1", stringify!($Sint), ").unwrap());")]
1770 /// ```
1771 #[stable(feature = "integer_sign_cast", since = "1.87.0")]
1772 #[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
1773 #[must_use = "this returns the result of the operation, \
1774 without modifying the original"]
1775 #[inline(always)]
1776 pub const fn cast_signed(self) -> NonZero<$Sint> {
1777 // SAFETY: `self.get()` can't be zero
1778 unsafe { NonZero::new_unchecked(self.get().cast_signed()) }
1779 }
1780 };
1781
1782 // Associated items for signed nonzero types only.
1783 (
1784 Primitive = signed $Int:ident,
1785 SignedPrimitive = $Sint:ty,
1786 UnsignedPrimitive = $Uint:ty,
1787 ) => {
1788 /// The smallest value that can be represented by this non-zero
1789 /// integer type,
1790 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1791 ///
1792 /// Note: While most integer types are defined for every whole
1793 /// number between `MIN` and `MAX`, signed non-zero integers are
1794 /// a special case. They have a "gap" at 0.
1795 ///
1796 /// # Examples
1797 ///
1798 /// ```
1799 /// # use std::num::NonZero;
1800 /// #
1801 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MIN.get(), ", stringify!($Int), "::MIN);")]
1802 /// ```
1803 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1804 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1805
1806 /// The largest value that can be represented by this non-zero
1807 /// integer type,
1808 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1809 ///
1810 /// Note: While most integer types are defined for every whole
1811 /// number between `MIN` and `MAX`, signed non-zero integers are
1812 /// a special case. They have a "gap" at 0.
1813 ///
1814 /// # Examples
1815 ///
1816 /// ```
1817 /// # use std::num::NonZero;
1818 /// #
1819 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MAX.get(), ", stringify!($Int), "::MAX);")]
1820 /// ```
1821 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1822 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1823
1824 /// Computes the absolute value of self.
1825 #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
1826 /// for documentation on overflow behavior.
1827 ///
1828 /// # Example
1829 ///
1830 /// ```
1831 /// # use std::num::NonZero;
1832 /// #
1833 /// # fn main() { test().unwrap(); }
1834 /// # fn test() -> Option<()> {
1835 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1836 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1837 ///
1838 /// assert_eq!(pos, pos.abs());
1839 /// assert_eq!(pos, neg.abs());
1840 /// # Some(())
1841 /// # }
1842 /// ```
1843 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1844 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1845 #[must_use = "this returns the result of the operation, \
1846 without modifying the original"]
1847 #[inline]
1848 pub const fn abs(self) -> Self {
1849 // SAFETY: This cannot overflow to zero.
1850 unsafe { Self::new_unchecked(self.get().abs()) }
1851 }
1852
1853 /// Checked absolute value.
1854 /// Checks for overflow and returns [`None`] if
1855 #[doc = concat!("`self == NonZero::<", stringify!($Int), ">::MIN`.")]
1856 /// The result cannot be zero.
1857 ///
1858 /// # Example
1859 ///
1860 /// ```
1861 /// # use std::num::NonZero;
1862 /// #
1863 /// # fn main() { test().unwrap(); }
1864 /// # fn test() -> Option<()> {
1865 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1866 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1867 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1868 ///
1869 /// assert_eq!(Some(pos), neg.checked_abs());
1870 /// assert_eq!(None, min.checked_abs());
1871 /// # Some(())
1872 /// # }
1873 /// ```
1874 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1875 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1876 #[must_use = "this returns the result of the operation, \
1877 without modifying the original"]
1878 #[inline]
1879 pub const fn checked_abs(self) -> Option<Self> {
1880 if let Some(nz) = self.get().checked_abs() {
1881 // SAFETY: absolute value of nonzero cannot yield zero values.
1882 Some(unsafe { Self::new_unchecked(nz) })
1883 } else {
1884 None
1885 }
1886 }
1887
1888 /// Computes the absolute value of self,
1889 /// with overflow information, see
1890 #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
1891 ///
1892 /// # Example
1893 ///
1894 /// ```
1895 /// # use std::num::NonZero;
1896 /// #
1897 /// # fn main() { test().unwrap(); }
1898 /// # fn test() -> Option<()> {
1899 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1900 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1901 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1902 ///
1903 /// assert_eq!((pos, false), pos.overflowing_abs());
1904 /// assert_eq!((pos, false), neg.overflowing_abs());
1905 /// assert_eq!((min, true), min.overflowing_abs());
1906 /// # Some(())
1907 /// # }
1908 /// ```
1909 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1910 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1911 #[must_use = "this returns the result of the operation, \
1912 without modifying the original"]
1913 #[inline]
1914 pub const fn overflowing_abs(self) -> (Self, bool) {
1915 let (nz, flag) = self.get().overflowing_abs();
1916 (
1917 // SAFETY: absolute value of nonzero cannot yield zero values.
1918 unsafe { Self::new_unchecked(nz) },
1919 flag,
1920 )
1921 }
1922
1923 /// Saturating absolute value, see
1924 #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
1925 ///
1926 /// # Example
1927 ///
1928 /// ```
1929 /// # use std::num::NonZero;
1930 /// #
1931 /// # fn main() { test().unwrap(); }
1932 /// # fn test() -> Option<()> {
1933 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1934 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1935 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1936 #[doc = concat!("let min_plus = NonZero::new(", stringify!($Int), "::MIN + 1)?;")]
1937 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1938 ///
1939 /// assert_eq!(pos, pos.saturating_abs());
1940 /// assert_eq!(pos, neg.saturating_abs());
1941 /// assert_eq!(max, min.saturating_abs());
1942 /// assert_eq!(max, min_plus.saturating_abs());
1943 /// # Some(())
1944 /// # }
1945 /// ```
1946 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1947 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1948 #[must_use = "this returns the result of the operation, \
1949 without modifying the original"]
1950 #[inline]
1951 pub const fn saturating_abs(self) -> Self {
1952 // SAFETY: absolute value of nonzero cannot yield zero values.
1953 unsafe { Self::new_unchecked(self.get().saturating_abs()) }
1954 }
1955
1956 /// Wrapping absolute value, see
1957 #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
1958 ///
1959 /// # Example
1960 ///
1961 /// ```
1962 /// # use std::num::NonZero;
1963 /// #
1964 /// # fn main() { test().unwrap(); }
1965 /// # fn test() -> Option<()> {
1966 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1967 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1968 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1969 #[doc = concat!("# let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1970 ///
1971 /// assert_eq!(pos, pos.wrapping_abs());
1972 /// assert_eq!(pos, neg.wrapping_abs());
1973 /// assert_eq!(min, min.wrapping_abs());
1974 /// assert_eq!(max, (-max).wrapping_abs());
1975 /// # Some(())
1976 /// # }
1977 /// ```
1978 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1979 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1980 #[must_use = "this returns the result of the operation, \
1981 without modifying the original"]
1982 #[inline]
1983 pub const fn wrapping_abs(self) -> Self {
1984 // SAFETY: absolute value of nonzero cannot yield zero values.
1985 unsafe { Self::new_unchecked(self.get().wrapping_abs()) }
1986 }
1987
1988 /// Computes the absolute value of self
1989 /// without any wrapping or panicking.
1990 ///
1991 /// # Example
1992 ///
1993 /// ```
1994 /// # use std::num::NonZero;
1995 /// #
1996 /// # fn main() { test().unwrap(); }
1997 /// # fn test() -> Option<()> {
1998 #[doc = concat!("let u_pos = NonZero::new(1", stringify!($Uint), ")?;")]
1999 #[doc = concat!("let i_pos = NonZero::new(1", stringify!($Int), ")?;")]
2000 #[doc = concat!("let i_neg = NonZero::new(-1", stringify!($Int), ")?;")]
2001 #[doc = concat!("let i_min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2002 #[doc = concat!("let u_max = NonZero::new(", stringify!($Uint), "::MAX / 2 + 1)?;")]
2003 ///
2004 /// assert_eq!(u_pos, i_pos.unsigned_abs());
2005 /// assert_eq!(u_pos, i_neg.unsigned_abs());
2006 /// assert_eq!(u_max, i_min.unsigned_abs());
2007 /// # Some(())
2008 /// # }
2009 /// ```
2010 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
2011 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
2012 #[must_use = "this returns the result of the operation, \
2013 without modifying the original"]
2014 #[inline]
2015 pub const fn unsigned_abs(self) -> NonZero<$Uint> {
2016 // SAFETY: absolute value of nonzero cannot yield zero values.
2017 unsafe { NonZero::new_unchecked(self.get().unsigned_abs()) }
2018 }
2019
2020 /// Returns `true` if `self` is positive and `false` if the
2021 /// number is negative.
2022 ///
2023 /// # Example
2024 ///
2025 /// ```
2026 /// # use std::num::NonZero;
2027 /// #
2028 /// # fn main() { test().unwrap(); }
2029 /// # fn test() -> Option<()> {
2030 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2031 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2032 ///
2033 /// assert!(pos_five.is_positive());
2034 /// assert!(!neg_five.is_positive());
2035 /// # Some(())
2036 /// # }
2037 /// ```
2038 #[must_use]
2039 #[inline]
2040 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2041 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2042 pub const fn is_positive(self) -> bool {
2043 self.get().is_positive()
2044 }
2045
2046 /// Returns `true` if `self` is negative and `false` if the
2047 /// number is positive.
2048 ///
2049 /// # Example
2050 ///
2051 /// ```
2052 /// # use std::num::NonZero;
2053 /// #
2054 /// # fn main() { test().unwrap(); }
2055 /// # fn test() -> Option<()> {
2056 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2057 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2058 ///
2059 /// assert!(neg_five.is_negative());
2060 /// assert!(!pos_five.is_negative());
2061 /// # Some(())
2062 /// # }
2063 /// ```
2064 #[must_use]
2065 #[inline]
2066 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2067 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2068 pub const fn is_negative(self) -> bool {
2069 self.get().is_negative()
2070 }
2071
2072 /// Checked negation. Computes `-self`,
2073 #[doc = concat!("returning `None` if `self == NonZero::<", stringify!($Int), ">::MIN`.")]
2074 ///
2075 /// # Example
2076 ///
2077 /// ```
2078 /// # use std::num::NonZero;
2079 /// #
2080 /// # fn main() { test().unwrap(); }
2081 /// # fn test() -> Option<()> {
2082 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2083 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2084 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2085 ///
2086 /// assert_eq!(pos_five.checked_neg(), Some(neg_five));
2087 /// assert_eq!(min.checked_neg(), None);
2088 /// # Some(())
2089 /// # }
2090 /// ```
2091 #[inline]
2092 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2093 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2094 pub const fn checked_neg(self) -> Option<Self> {
2095 if let Some(result) = self.get().checked_neg() {
2096 // SAFETY: negation of nonzero cannot yield zero values.
2097 return Some(unsafe { Self::new_unchecked(result) });
2098 }
2099 None
2100 }
2101
2102 /// Negates self, overflowing if this is equal to the minimum value.
2103 ///
2104 #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")]
2105 /// for documentation on overflow behavior.
2106 ///
2107 /// # Example
2108 ///
2109 /// ```
2110 /// # use std::num::NonZero;
2111 /// #
2112 /// # fn main() { test().unwrap(); }
2113 /// # fn test() -> Option<()> {
2114 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2115 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2116 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2117 ///
2118 /// assert_eq!(pos_five.overflowing_neg(), (neg_five, false));
2119 /// assert_eq!(min.overflowing_neg(), (min, true));
2120 /// # Some(())
2121 /// # }
2122 /// ```
2123 #[inline]
2124 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2125 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2126 pub const fn overflowing_neg(self) -> (Self, bool) {
2127 let (result, overflow) = self.get().overflowing_neg();
2128 // SAFETY: negation of nonzero cannot yield zero values.
2129 ((unsafe { Self::new_unchecked(result) }), overflow)
2130 }
2131
2132 /// Saturating negation. Computes `-self`,
2133 #[doc = concat!("returning [`NonZero::<", stringify!($Int), ">::MAX`]")]
2134 #[doc = concat!("if `self == NonZero::<", stringify!($Int), ">::MIN`")]
2135 /// instead of overflowing.
2136 ///
2137 /// # Example
2138 ///
2139 /// ```
2140 /// # use std::num::NonZero;
2141 /// #
2142 /// # fn main() { test().unwrap(); }
2143 /// # fn test() -> Option<()> {
2144 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2145 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2146 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2147 #[doc = concat!("let min_plus_one = NonZero::new(", stringify!($Int), "::MIN + 1)?;")]
2148 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
2149 ///
2150 /// assert_eq!(pos_five.saturating_neg(), neg_five);
2151 /// assert_eq!(min.saturating_neg(), max);
2152 /// assert_eq!(max.saturating_neg(), min_plus_one);
2153 /// # Some(())
2154 /// # }
2155 /// ```
2156 #[inline]
2157 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2158 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2159 pub const fn saturating_neg(self) -> Self {
2160 if let Some(result) = self.checked_neg() {
2161 return result;
2162 }
2163 Self::MAX
2164 }
2165
2166 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
2167 /// of the type.
2168 ///
2169 #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")]
2170 /// for documentation on overflow behavior.
2171 ///
2172 /// # Example
2173 ///
2174 /// ```
2175 /// # use std::num::NonZero;
2176 /// #
2177 /// # fn main() { test().unwrap(); }
2178 /// # fn test() -> Option<()> {
2179 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2180 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2181 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2182 ///
2183 /// assert_eq!(pos_five.wrapping_neg(), neg_five);
2184 /// assert_eq!(min.wrapping_neg(), min);
2185 /// # Some(())
2186 /// # }
2187 /// ```
2188 #[inline]
2189 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2190 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2191 pub const fn wrapping_neg(self) -> Self {
2192 let result = self.get().wrapping_neg();
2193 // SAFETY: negation of nonzero cannot yield zero values.
2194 unsafe { Self::new_unchecked(result) }
2195 }
2196
2197 /// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
2198 ///
2199 /// # Examples
2200 ///
2201 /// ```
2202 /// # use std::num::NonZero;
2203 ///
2204 #[doc = concat!("let n = NonZero::new(-1", stringify!($Int), ").unwrap();")]
2205 ///
2206 #[doc = concat!("assert_eq!(n.cast_unsigned(), NonZero::<", stringify!($Uint), ">::MAX);")]
2207 /// ```
2208 #[stable(feature = "integer_sign_cast", since = "1.87.0")]
2209 #[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
2210 #[must_use = "this returns the result of the operation, \
2211 without modifying the original"]
2212 #[inline(always)]
2213 pub const fn cast_unsigned(self) -> NonZero<$Uint> {
2214 // SAFETY: `self.get()` can't be zero
2215 unsafe { NonZero::new_unchecked(self.get().cast_unsigned()) }
2216 }
2217
2218 };
2219}
2220
2221nonzero_integer! {
2222 Self = NonZeroU8,
2223 Primitive = unsigned u8,
2224 SignedPrimitive = i8,
2225 rot = 2,
2226 rot_op = "0x82",
2227 rot_result = "0xa",
2228 swap_op = "0x12",
2229 swapped = "0x12",
2230 reversed = "0x48",
2231}
2232
2233nonzero_integer! {
2234 Self = NonZeroU16,
2235 Primitive = unsigned u16,
2236 SignedPrimitive = i16,
2237 rot = 4,
2238 rot_op = "0xa003",
2239 rot_result = "0x3a",
2240 swap_op = "0x1234",
2241 swapped = "0x3412",
2242 reversed = "0x2c48",
2243}
2244
2245nonzero_integer! {
2246 Self = NonZeroU32,
2247 Primitive = unsigned u32,
2248 SignedPrimitive = i32,
2249 rot = 8,
2250 rot_op = "0x10000b3",
2251 rot_result = "0xb301",
2252 swap_op = "0x12345678",
2253 swapped = "0x78563412",
2254 reversed = "0x1e6a2c48",
2255}
2256
2257nonzero_integer! {
2258 Self = NonZeroU64,
2259 Primitive = unsigned u64,
2260 SignedPrimitive = i64,
2261 rot = 12,
2262 rot_op = "0xaa00000000006e1",
2263 rot_result = "0x6e10aa",
2264 swap_op = "0x1234567890123456",
2265 swapped = "0x5634129078563412",
2266 reversed = "0x6a2c48091e6a2c48",
2267}
2268
2269nonzero_integer! {
2270 Self = NonZeroU128,
2271 Primitive = unsigned u128,
2272 SignedPrimitive = i128,
2273 rot = 16,
2274 rot_op = "0x13f40000000000000000000000004f76",
2275 rot_result = "0x4f7613f4",
2276 swap_op = "0x12345678901234567890123456789012",
2277 swapped = "0x12907856341290785634129078563412",
2278 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
2279}
2280
2281#[cfg(target_pointer_width = "16")]
2282nonzero_integer! {
2283 Self = NonZeroUsize,
2284 Primitive = unsigned usize,
2285 SignedPrimitive = isize,
2286 rot = 4,
2287 rot_op = "0xa003",
2288 rot_result = "0x3a",
2289 swap_op = "0x1234",
2290 swapped = "0x3412",
2291 reversed = "0x2c48",
2292}
2293
2294#[cfg(target_pointer_width = "32")]
2295nonzero_integer! {
2296 Self = NonZeroUsize,
2297 Primitive = unsigned usize,
2298 SignedPrimitive = isize,
2299 rot = 8,
2300 rot_op = "0x10000b3",
2301 rot_result = "0xb301",
2302 swap_op = "0x12345678",
2303 swapped = "0x78563412",
2304 reversed = "0x1e6a2c48",
2305}
2306
2307#[cfg(target_pointer_width = "64")]
2308nonzero_integer! {
2309 Self = NonZeroUsize,
2310 Primitive = unsigned usize,
2311 SignedPrimitive = isize,
2312 rot = 12,
2313 rot_op = "0xaa00000000006e1",
2314 rot_result = "0x6e10aa",
2315 swap_op = "0x1234567890123456",
2316 swapped = "0x5634129078563412",
2317 reversed = "0x6a2c48091e6a2c48",
2318}
2319
2320nonzero_integer! {
2321 Self = NonZeroI8,
2322 Primitive = signed i8,
2323 UnsignedPrimitive = u8,
2324 rot = 2,
2325 rot_op = "-0x7e",
2326 rot_result = "0xa",
2327 swap_op = "0x12",
2328 swapped = "0x12",
2329 reversed = "0x48",
2330}
2331
2332nonzero_integer! {
2333 Self = NonZeroI16,
2334 Primitive = signed i16,
2335 UnsignedPrimitive = u16,
2336 rot = 4,
2337 rot_op = "-0x5ffd",
2338 rot_result = "0x3a",
2339 swap_op = "0x1234",
2340 swapped = "0x3412",
2341 reversed = "0x2c48",
2342}
2343
2344nonzero_integer! {
2345 Self = NonZeroI32,
2346 Primitive = signed i32,
2347 UnsignedPrimitive = u32,
2348 rot = 8,
2349 rot_op = "0x10000b3",
2350 rot_result = "0xb301",
2351 swap_op = "0x12345678",
2352 swapped = "0x78563412",
2353 reversed = "0x1e6a2c48",
2354}
2355
2356nonzero_integer! {
2357 Self = NonZeroI64,
2358 Primitive = signed i64,
2359 UnsignedPrimitive = u64,
2360 rot = 12,
2361 rot_op = "0xaa00000000006e1",
2362 rot_result = "0x6e10aa",
2363 swap_op = "0x1234567890123456",
2364 swapped = "0x5634129078563412",
2365 reversed = "0x6a2c48091e6a2c48",
2366}
2367
2368nonzero_integer! {
2369 Self = NonZeroI128,
2370 Primitive = signed i128,
2371 UnsignedPrimitive = u128,
2372 rot = 16,
2373 rot_op = "0x13f40000000000000000000000004f76",
2374 rot_result = "0x4f7613f4",
2375 swap_op = "0x12345678901234567890123456789012",
2376 swapped = "0x12907856341290785634129078563412",
2377 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
2378}
2379
2380#[cfg(target_pointer_width = "16")]
2381nonzero_integer! {
2382 Self = NonZeroIsize,
2383 Primitive = signed isize,
2384 UnsignedPrimitive = usize,
2385 rot = 4,
2386 rot_op = "-0x5ffd",
2387 rot_result = "0x3a",
2388 swap_op = "0x1234",
2389 swapped = "0x3412",
2390 reversed = "0x2c48",
2391}
2392
2393#[cfg(target_pointer_width = "32")]
2394nonzero_integer! {
2395 Self = NonZeroIsize,
2396 Primitive = signed isize,
2397 UnsignedPrimitive = usize,
2398 rot = 8,
2399 rot_op = "0x10000b3",
2400 rot_result = "0xb301",
2401 swap_op = "0x12345678",
2402 swapped = "0x78563412",
2403 reversed = "0x1e6a2c48",
2404}
2405
2406#[cfg(target_pointer_width = "64")]
2407nonzero_integer! {
2408 Self = NonZeroIsize,
2409 Primitive = signed isize,
2410 UnsignedPrimitive = usize,
2411 rot = 12,
2412 rot_op = "0xaa00000000006e1",
2413 rot_result = "0x6e10aa",
2414 swap_op = "0x1234567890123456",
2415 swapped = "0x5634129078563412",
2416 reversed = "0x6a2c48091e6a2c48",
2417}