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