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