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