1 //! Definitions of integer that is known not to equal zero.
4 use crate::ops::{BitOr, BitOrAssign, Div, Rem};
5 use crate::str::FromStr;
7 use super::from_str_radix;
8 use super::{IntErrorKind, ParseIntError};
11 macro_rules! impl_nonzero_fmt {
12 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
15 impl fmt::$Trait for $Ty {
17 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 macro_rules! nonzero_integers {
26 ( $( #[$stability: meta] #[$const_new_unchecked_stability: meta] $Ty: ident($Int: ty); )+ ) => {
28 /// An integer that is known not to equal zero.
30 /// This enables some memory layout optimization.
31 #[doc = concat!("For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:")]
34 /// use std::mem::size_of;
35 #[doc = concat!("assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int), ">());")]
38 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
40 #[rustc_layout_scalar_valid_range_start(1)]
41 #[rustc_nonnull_optimization_guaranteed]
45 /// Creates a non-zero without checking whether the value is non-zero.
46 /// This results in undefined behaviour if the value is zero.
50 /// The value must not be zero.
52 #[$const_new_unchecked_stability]
55 #[rustc_allow_const_fn_unstable(const_fn_fn_ptr_basics)] // required by assert_unsafe_precondition
56 pub const unsafe fn new_unchecked(n: $Int) -> Self {
57 // SAFETY: this is guaranteed to be safe by the caller.
59 core::intrinsics::assert_unsafe_precondition!(n != 0);
64 /// Creates a non-zero if the given value is not zero.
66 #[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
69 pub const fn new(n: $Int) -> Option<Self> {
71 // SAFETY: we just checked that there's no `0`
72 Some(unsafe { Self(n) })
78 /// Returns the value as a primitive type.
81 #[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
82 pub const fn get(self) -> $Int {
88 #[stable(feature = "from_nonzero", since = "1.31.0")]
89 #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")]
90 impl const From<$Ty> for $Int {
91 #[doc = concat!("Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`")]
93 fn from(nonzero: $Ty) -> Self {
98 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
99 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
100 impl const BitOr for $Ty {
103 fn bitor(self, rhs: Self) -> Self::Output {
104 // SAFETY: since `self` and `rhs` are both nonzero, the
105 // result of the bitwise-or will be nonzero.
106 unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
110 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
111 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
112 impl const BitOr<$Int> for $Ty {
115 fn bitor(self, rhs: $Int) -> Self::Output {
116 // SAFETY: since `self` is nonzero, the result of the
117 // bitwise-or will be nonzero regardless of the value of
119 unsafe { $Ty::new_unchecked(self.get() | rhs) }
123 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
124 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
125 impl const BitOr<$Ty> for $Int {
128 fn bitor(self, rhs: $Ty) -> Self::Output {
129 // SAFETY: since `rhs` is nonzero, the result of the
130 // bitwise-or will be nonzero regardless of the value of
132 unsafe { $Ty::new_unchecked(self | rhs.get()) }
136 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
137 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
138 impl const BitOrAssign for $Ty {
140 fn bitor_assign(&mut self, rhs: Self) {
145 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
146 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
147 impl const BitOrAssign<$Int> for $Ty {
149 fn bitor_assign(&mut self, rhs: $Int) {
155 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
162 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
163 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
164 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
165 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
166 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
167 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
168 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
169 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
170 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
171 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
172 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
173 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
176 macro_rules! from_str_radix_nzint_impl {
178 #[stable(feature = "nonzero_parse", since = "1.35.0")]
179 impl FromStr for $t {
180 type Err = ParseIntError;
181 fn from_str(src: &str) -> Result<Self, Self::Err> {
182 Self::new(from_str_radix(src, 10)?)
183 .ok_or(ParseIntError {
184 kind: IntErrorKind::Zero
191 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
192 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
194 macro_rules! nonzero_leading_trailing_zeros {
195 ( $( $Ty: ident($Uint: ty) , $LeadingTestExpr:expr ;)+ ) => {
198 /// Returns the number of leading zeros in the binary representation of `self`.
200 /// On many architectures, this function can perform better than `leading_zeros()` on the underlying integer type, as special handling of zero can be avoided.
207 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(", stringify!($LeadingTestExpr), ").unwrap();")]
209 /// assert_eq!(n.leading_zeros(), 0);
211 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
212 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
213 #[must_use = "this returns the result of the operation, \
214 without modifying the original"]
216 pub const fn leading_zeros(self) -> u32 {
217 // SAFETY: since `self` can not be zero it is safe to call ctlz_nonzero
218 unsafe { intrinsics::ctlz_nonzero(self.0 as $Uint) as u32 }
221 /// Returns the number of trailing zeros in the binary representation
224 /// On many architectures, this function can perform better than `trailing_zeros()` on the underlying integer type, as special handling of zero can be avoided.
231 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(0b0101000).unwrap();")]
233 /// assert_eq!(n.trailing_zeros(), 3);
235 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
236 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
237 #[must_use = "this returns the result of the operation, \
238 without modifying the original"]
240 pub const fn trailing_zeros(self) -> u32 {
241 // SAFETY: since `self` can not be zero it is safe to call cttz_nonzero
242 unsafe { intrinsics::cttz_nonzero(self.0 as $Uint) as u32 }
250 nonzero_leading_trailing_zeros! {
251 NonZeroU8(u8), u8::MAX;
252 NonZeroU16(u16), u16::MAX;
253 NonZeroU32(u32), u32::MAX;
254 NonZeroU64(u64), u64::MAX;
255 NonZeroU128(u128), u128::MAX;
256 NonZeroUsize(usize), usize::MAX;
258 NonZeroI16(u16), -1i16;
259 NonZeroI32(u32), -1i32;
260 NonZeroI64(u64), -1i64;
261 NonZeroI128(u128), -1i128;
262 NonZeroIsize(usize), -1isize;
265 macro_rules! nonzero_integers_div {
266 ( $( $Ty: ident($Int: ty); )+ ) => {
268 #[stable(feature = "nonzero_div", since = "1.51.0")]
269 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
270 impl const Div<$Ty> for $Int {
272 /// This operation rounds towards zero,
273 /// truncating any fractional part of the exact result, and cannot panic.
275 fn div(self, other: $Ty) -> $Int {
276 // SAFETY: div by zero is checked because `other` is a nonzero,
277 // and MIN/-1 is checked because `self` is an unsigned int.
278 unsafe { crate::intrinsics::unchecked_div(self, other.get()) }
282 #[stable(feature = "nonzero_div", since = "1.51.0")]
283 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
284 impl const Rem<$Ty> for $Int {
286 /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
288 fn rem(self, other: $Ty) -> $Int {
289 // SAFETY: rem by zero is checked because `other` is a nonzero,
290 // and MIN/-1 is checked because `self` is an unsigned int.
291 unsafe { crate::intrinsics::unchecked_rem(self, other.get()) }
298 nonzero_integers_div! {
307 // A bunch of methods for unsigned nonzero types only.
308 macro_rules! nonzero_unsigned_operations {
309 ( $( $Ty: ident($Int: ident); )+ ) => {
312 /// Add an unsigned integer to a non-zero value.
313 /// Check for overflow and return [`None`] on overflow
314 /// As a consequence, the result cannot wrap to zero.
320 /// #![feature(nonzero_ops)]
321 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
323 /// # fn main() { test().unwrap(); }
324 /// # fn test() -> Option<()> {
325 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
326 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
327 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
328 stringify!($Int), "::MAX)?;")]
330 /// assert_eq!(Some(two), one.checked_add(1));
331 /// assert_eq!(None, max.checked_add(1));
335 #[unstable(feature = "nonzero_ops", issue = "84186")]
336 #[must_use = "this returns the result of the operation, \
337 without modifying the original"]
339 pub const fn checked_add(self, other: $Int) -> Option<$Ty> {
340 if let Some(result) = self.get().checked_add(other) {
341 // SAFETY: $Int::checked_add returns None on overflow
342 // so the result cannot be zero.
343 Some(unsafe { $Ty::new_unchecked(result) })
349 /// Add an unsigned integer to a non-zero value.
350 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
355 /// #![feature(nonzero_ops)]
356 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
358 /// # fn main() { test().unwrap(); }
359 /// # fn test() -> Option<()> {
360 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
361 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
362 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
363 stringify!($Int), "::MAX)?;")]
365 /// assert_eq!(two, one.saturating_add(1));
366 /// assert_eq!(max, max.saturating_add(1));
370 #[unstable(feature = "nonzero_ops", issue = "84186")]
371 #[must_use = "this returns the result of the operation, \
372 without modifying the original"]
374 pub const fn saturating_add(self, other: $Int) -> $Ty {
375 // SAFETY: $Int::saturating_add returns $Int::MAX on overflow
376 // so the result cannot be zero.
377 unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
380 /// Add an unsigned integer to a non-zero value,
381 /// assuming overflow cannot occur.
382 /// Overflow is unchecked, and it is undefined behaviour to overflow
383 /// *even if the result would wrap to a non-zero value*.
384 /// The behaviour is undefined as soon as
385 #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
390 /// #![feature(nonzero_ops)]
391 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
393 /// # fn main() { test().unwrap(); }
394 /// # fn test() -> Option<()> {
395 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
396 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
398 /// assert_eq!(two, unsafe { one.unchecked_add(1) });
402 #[unstable(feature = "nonzero_ops", issue = "84186")]
403 #[must_use = "this returns the result of the operation, \
404 without modifying the original"]
406 pub const unsafe fn unchecked_add(self, other: $Int) -> $Ty {
407 // SAFETY: The caller ensures there is no overflow.
408 unsafe { $Ty::new_unchecked(self.get().unchecked_add(other)) }
411 /// Returns the smallest power of two greater than or equal to n.
412 /// Check for overflow and return [`None`]
413 /// if the next power of two is greater than the type’s maximum value.
414 /// As a consequence, the result cannot wrap to zero.
419 /// #![feature(nonzero_ops)]
420 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
422 /// # fn main() { test().unwrap(); }
423 /// # fn test() -> Option<()> {
424 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
425 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
426 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
427 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
428 stringify!($Int), "::MAX)?;")]
430 /// assert_eq!(Some(two), two.checked_next_power_of_two() );
431 /// assert_eq!(Some(four), three.checked_next_power_of_two() );
432 /// assert_eq!(None, max.checked_next_power_of_two() );
436 #[unstable(feature = "nonzero_ops", issue = "84186")]
437 #[must_use = "this returns the result of the operation, \
438 without modifying the original"]
440 pub const fn checked_next_power_of_two(self) -> Option<$Ty> {
441 if let Some(nz) = self.get().checked_next_power_of_two() {
442 // SAFETY: The next power of two is positive
443 // and overflow is checked.
444 Some(unsafe { $Ty::new_unchecked(nz) })
450 /// Returns the base 2 logarithm of the number, rounded down.
452 /// This is the same operation as
453 #[doc = concat!("[`", stringify!($Int), "::log2`],")]
454 /// except that it has no failure cases to worry about
455 /// since this value can never be zero.
460 /// #![feature(int_log)]
461 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
463 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(7).unwrap().log2(), 2);")]
464 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(8).unwrap().log2(), 3);")]
465 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(9).unwrap().log2(), 3);")]
467 #[unstable(feature = "int_log", issue = "70887")]
468 #[must_use = "this returns the result of the operation, \
469 without modifying the original"]
471 pub const fn log2(self) -> u32 {
472 Self::BITS - 1 - self.leading_zeros()
475 /// Returns the base 10 logarithm of the number, rounded down.
477 /// This is the same operation as
478 #[doc = concat!("[`", stringify!($Int), "::log10`],")]
479 /// except that it has no failure cases to worry about
480 /// since this value can never be zero.
485 /// #![feature(int_log)]
486 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
488 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(99).unwrap().log10(), 1);")]
489 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(100).unwrap().log10(), 2);")]
490 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(101).unwrap().log10(), 2);")]
492 #[unstable(feature = "int_log", issue = "70887")]
493 #[must_use = "this returns the result of the operation, \
494 without modifying the original"]
496 pub const fn log10(self) -> u32 {
497 super::int_log10::$Int(self.0)
504 nonzero_unsigned_operations! {
513 // A bunch of methods for signed nonzero types only.
514 macro_rules! nonzero_signed_operations {
515 ( $( $Ty: ident($Int: ty) -> $Uty: ident($Uint: ty); )+ ) => {
518 /// Computes the absolute value of self.
519 #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
520 /// for documentation on overflow behaviour.
525 /// #![feature(nonzero_ops)]
526 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
528 /// # fn main() { test().unwrap(); }
529 /// # fn test() -> Option<()> {
530 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
531 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
533 /// assert_eq!(pos, pos.abs());
534 /// assert_eq!(pos, neg.abs());
538 #[unstable(feature = "nonzero_ops", issue = "84186")]
539 #[must_use = "this returns the result of the operation, \
540 without modifying the original"]
542 pub const fn abs(self) -> $Ty {
543 // SAFETY: This cannot overflow to zero.
544 unsafe { $Ty::new_unchecked(self.get().abs()) }
547 /// Checked absolute value.
548 /// Check for overflow and returns [`None`] if
549 #[doc = concat!("`self == ", stringify!($Int), "::MIN`.")]
550 /// The result cannot be zero.
555 /// #![feature(nonzero_ops)]
556 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
558 /// # fn main() { test().unwrap(); }
559 /// # fn test() -> Option<()> {
560 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
561 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
562 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
563 stringify!($Int), "::MIN)?;")]
565 /// assert_eq!(Some(pos), neg.checked_abs());
566 /// assert_eq!(None, min.checked_abs());
570 #[unstable(feature = "nonzero_ops", issue = "84186")]
571 #[must_use = "this returns the result of the operation, \
572 without modifying the original"]
574 pub const fn checked_abs(self) -> Option<$Ty> {
575 if let Some(nz) = self.get().checked_abs() {
576 // SAFETY: absolute value of nonzero cannot yield zero values.
577 Some(unsafe { $Ty::new_unchecked(nz) })
583 /// Computes the absolute value of self,
584 /// with overflow information, see
585 #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
590 /// #![feature(nonzero_ops)]
591 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
593 /// # fn main() { test().unwrap(); }
594 /// # fn test() -> Option<()> {
595 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
596 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
597 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
598 stringify!($Int), "::MIN)?;")]
600 /// assert_eq!((pos, false), pos.overflowing_abs());
601 /// assert_eq!((pos, false), neg.overflowing_abs());
602 /// assert_eq!((min, true), min.overflowing_abs());
606 #[unstable(feature = "nonzero_ops", issue = "84186")]
607 #[must_use = "this returns the result of the operation, \
608 without modifying the original"]
610 pub const fn overflowing_abs(self) -> ($Ty, bool) {
611 let (nz, flag) = self.get().overflowing_abs();
613 // SAFETY: absolute value of nonzero cannot yield zero values.
614 unsafe { $Ty::new_unchecked(nz) },
619 /// Saturating absolute value, see
620 #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
625 /// #![feature(nonzero_ops)]
626 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
628 /// # fn main() { test().unwrap(); }
629 /// # fn test() -> Option<()> {
630 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
631 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
632 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
633 stringify!($Int), "::MIN)?;")]
634 #[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
635 stringify!($Int), "::MIN + 1)?;")]
636 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
637 stringify!($Int), "::MAX)?;")]
639 /// assert_eq!(pos, pos.saturating_abs());
640 /// assert_eq!(pos, neg.saturating_abs());
641 /// assert_eq!(max, min.saturating_abs());
642 /// assert_eq!(max, min_plus.saturating_abs());
646 #[unstable(feature = "nonzero_ops", issue = "84186")]
647 #[must_use = "this returns the result of the operation, \
648 without modifying the original"]
650 pub const fn saturating_abs(self) -> $Ty {
651 // SAFETY: absolute value of nonzero cannot yield zero values.
652 unsafe { $Ty::new_unchecked(self.get().saturating_abs()) }
655 /// Wrapping absolute value, see
656 #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
661 /// #![feature(nonzero_ops)]
662 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
664 /// # fn main() { test().unwrap(); }
665 /// # fn test() -> Option<()> {
666 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
667 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
668 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
669 stringify!($Int), "::MIN)?;")]
670 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
671 stringify!($Int), "::MAX)?;")]
673 /// assert_eq!(pos, pos.wrapping_abs());
674 /// assert_eq!(pos, neg.wrapping_abs());
675 /// assert_eq!(min, min.wrapping_abs());
676 /// # // FIXME: add once Neg is implemented?
677 /// # // assert_eq!(max, (-max).wrapping_abs());
681 #[unstable(feature = "nonzero_ops", issue = "84186")]
682 #[must_use = "this returns the result of the operation, \
683 without modifying the original"]
685 pub const fn wrapping_abs(self) -> $Ty {
686 // SAFETY: absolute value of nonzero cannot yield zero values.
687 unsafe { $Ty::new_unchecked(self.get().wrapping_abs()) }
690 /// Computes the absolute value of self
691 /// without any wrapping or panicking.
696 /// #![feature(nonzero_ops)]
697 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
698 #[doc = concat!("# use std::num::", stringify!($Uty), ";")]
700 /// # fn main() { test().unwrap(); }
701 /// # fn test() -> Option<()> {
702 #[doc = concat!("let u_pos = ", stringify!($Uty), "::new(1)?;")]
703 #[doc = concat!("let i_pos = ", stringify!($Ty), "::new(1)?;")]
704 #[doc = concat!("let i_neg = ", stringify!($Ty), "::new(-1)?;")]
705 #[doc = concat!("let i_min = ", stringify!($Ty), "::new(",
706 stringify!($Int), "::MIN)?;")]
707 #[doc = concat!("let u_max = ", stringify!($Uty), "::new(",
708 stringify!($Uint), "::MAX / 2 + 1)?;")]
710 /// assert_eq!(u_pos, i_pos.unsigned_abs());
711 /// assert_eq!(u_pos, i_neg.unsigned_abs());
712 /// assert_eq!(u_max, i_min.unsigned_abs());
716 #[unstable(feature = "nonzero_ops", issue = "84186")]
717 #[must_use = "this returns the result of the operation, \
718 without modifying the original"]
720 pub const fn unsigned_abs(self) -> $Uty {
721 // SAFETY: absolute value of nonzero cannot yield zero values.
722 unsafe { $Uty::new_unchecked(self.get().unsigned_abs()) }
729 nonzero_signed_operations! {
730 NonZeroI8(i8) -> NonZeroU8(u8);
731 NonZeroI16(i16) -> NonZeroU16(u16);
732 NonZeroI32(i32) -> NonZeroU32(u32);
733 NonZeroI64(i64) -> NonZeroU64(u64);
734 NonZeroI128(i128) -> NonZeroU128(u128);
735 NonZeroIsize(isize) -> NonZeroUsize(usize);
738 // A bunch of methods for both signed and unsigned nonzero types.
739 macro_rules! nonzero_unsigned_signed_operations {
740 ( $( $signedness:ident $Ty: ident($Int: ty); )+ ) => {
743 /// Multiply two non-zero integers together.
744 /// Check for overflow and return [`None`] on overflow.
745 /// As a consequence, the result cannot wrap to zero.
750 /// #![feature(nonzero_ops)]
751 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
753 /// # fn main() { test().unwrap(); }
754 /// # fn test() -> Option<()> {
755 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
756 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
757 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
758 stringify!($Int), "::MAX)?;")]
760 /// assert_eq!(Some(four), two.checked_mul(two));
761 /// assert_eq!(None, max.checked_mul(two));
765 #[unstable(feature = "nonzero_ops", issue = "84186")]
766 #[must_use = "this returns the result of the operation, \
767 without modifying the original"]
769 pub const fn checked_mul(self, other: $Ty) -> Option<$Ty> {
770 if let Some(result) = self.get().checked_mul(other.get()) {
771 // SAFETY: checked_mul returns None on overflow
772 // and `other` is also non-null
773 // so the result cannot be zero.
774 Some(unsafe { $Ty::new_unchecked(result) })
780 /// Multiply two non-zero integers together.
781 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
786 /// #![feature(nonzero_ops)]
787 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
789 /// # fn main() { test().unwrap(); }
790 /// # fn test() -> Option<()> {
791 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
792 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
793 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
794 stringify!($Int), "::MAX)?;")]
796 /// assert_eq!(four, two.saturating_mul(two));
797 /// assert_eq!(max, four.saturating_mul(max));
801 #[unstable(feature = "nonzero_ops", issue = "84186")]
802 #[must_use = "this returns the result of the operation, \
803 without modifying the original"]
805 pub const fn saturating_mul(self, other: $Ty) -> $Ty {
806 // SAFETY: saturating_mul returns u*::MAX on overflow
807 // and `other` is also non-null
808 // so the result cannot be zero.
809 unsafe { $Ty::new_unchecked(self.get().saturating_mul(other.get())) }
812 /// Multiply two non-zero integers together,
813 /// assuming overflow cannot occur.
814 /// Overflow is unchecked, and it is undefined behaviour to overflow
815 /// *even if the result would wrap to a non-zero value*.
816 /// The behaviour is undefined as soon as
817 #[doc = sign_dependent_expr!{
820 concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
821 "or `self * rhs < ", stringify!($Int), "::MIN`.")
824 concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
831 /// #![feature(nonzero_ops)]
832 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
834 /// # fn main() { test().unwrap(); }
835 /// # fn test() -> Option<()> {
836 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
837 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
839 /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
843 #[unstable(feature = "nonzero_ops", issue = "84186")]
844 #[must_use = "this returns the result of the operation, \
845 without modifying the original"]
847 pub const unsafe fn unchecked_mul(self, other: $Ty) -> $Ty {
848 // SAFETY: The caller ensures there is no overflow.
849 unsafe { $Ty::new_unchecked(self.get().unchecked_mul(other.get())) }
852 /// Raise non-zero value to an integer power.
853 /// Check for overflow and return [`None`] on overflow.
854 /// As a consequence, the result cannot wrap to zero.
859 /// #![feature(nonzero_ops)]
860 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
862 /// # fn main() { test().unwrap(); }
863 /// # fn test() -> Option<()> {
864 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
865 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
866 #[doc = concat!("let half_max = ", stringify!($Ty), "::new(",
867 stringify!($Int), "::MAX / 2)?;")]
869 /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
870 /// assert_eq!(None, half_max.checked_pow(3));
874 #[unstable(feature = "nonzero_ops", issue = "84186")]
875 #[must_use = "this returns the result of the operation, \
876 without modifying the original"]
878 pub const fn checked_pow(self, other: u32) -> Option<$Ty> {
879 if let Some(result) = self.get().checked_pow(other) {
880 // SAFETY: checked_pow returns None on overflow
881 // so the result cannot be zero.
882 Some(unsafe { $Ty::new_unchecked(result) })
888 /// Raise non-zero value to an integer power.
889 #[doc = sign_dependent_expr!{
892 concat!("Return [`", stringify!($Int), "::MIN`] ",
893 "or [`", stringify!($Int), "::MAX`] on overflow.")
896 concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")
903 /// #![feature(nonzero_ops)]
904 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
906 /// # fn main() { test().unwrap(); }
907 /// # fn test() -> Option<()> {
908 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
909 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
910 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
911 stringify!($Int), "::MAX)?;")]
913 /// assert_eq!(twenty_seven, three.saturating_pow(3));
914 /// assert_eq!(max, max.saturating_pow(3));
918 #[unstable(feature = "nonzero_ops", issue = "84186")]
919 #[must_use = "this returns the result of the operation, \
920 without modifying the original"]
922 pub const fn saturating_pow(self, other: u32) -> $Ty {
923 // SAFETY: saturating_pow returns u*::MAX on overflow
924 // so the result cannot be zero.
925 unsafe { $Ty::new_unchecked(self.get().saturating_pow(other)) }
932 // Use this when the generated code should differ between signed and unsigned types.
933 macro_rules! sign_dependent_expr {
934 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
937 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
942 nonzero_unsigned_signed_operations! {
943 unsigned NonZeroU8(u8);
944 unsigned NonZeroU16(u16);
945 unsigned NonZeroU32(u32);
946 unsigned NonZeroU64(u64);
947 unsigned NonZeroU128(u128);
948 unsigned NonZeroUsize(usize);
949 signed NonZeroI8(i8);
950 signed NonZeroI16(i16);
951 signed NonZeroI32(i32);
952 signed NonZeroI64(i64);
953 signed NonZeroI128(i128);
954 signed NonZeroIsize(isize);
957 macro_rules! nonzero_unsigned_is_power_of_two {
958 ( $( $Ty: ident )+ ) => {
962 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
964 /// On many architectures, this function can perform better than `is_power_of_two()`
965 /// on the underlying integer type, as special handling of zero can be avoided.
972 #[doc = concat!("let eight = std::num::", stringify!($Ty), "::new(8).unwrap();")]
973 /// assert!(eight.is_power_of_two());
974 #[doc = concat!("let ten = std::num::", stringify!($Ty), "::new(10).unwrap();")]
975 /// assert!(!ten.is_power_of_two());
978 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
979 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
981 pub const fn is_power_of_two(self) -> bool {
982 // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
983 // On the basic x86-64 target, this saves 3 instructions for the zero check.
984 // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
985 // compared to the `POPCNT` implementation on the underlying integer type.
987 intrinsics::ctpop(self.get()) < 2
995 nonzero_unsigned_is_power_of_two! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize }
997 macro_rules! nonzero_min_max_unsigned {
998 ( $( $Ty: ident($Int: ident); )+ ) => {
1001 /// The smallest value that can be represented by this non-zero
1002 /// integer type, 1.
1007 /// #![feature(nonzero_min_max)]
1008 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1010 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), 1", stringify!($Int), ");")]
1012 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1013 pub const MIN: Self = Self::new(1).unwrap();
1015 /// The largest value that can be represented by this non-zero
1017 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1022 /// #![feature(nonzero_min_max)]
1023 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1025 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1027 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1028 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1034 macro_rules! nonzero_min_max_signed {
1035 ( $( $Ty: ident($Int: ident); )+ ) => {
1038 /// The smallest value that can be represented by this non-zero
1040 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1042 /// Note: While most integer types are defined for every whole
1043 /// number between `MIN` and `MAX`, signed non-zero integers are
1044 /// a special case. They have a "gap" at 0.
1049 /// #![feature(nonzero_min_max)]
1050 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1052 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), ", stringify!($Int), "::MIN);")]
1054 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1055 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1057 /// The largest value that can be represented by this non-zero
1059 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1061 /// Note: While most integer types are defined for every whole
1062 /// number between `MIN` and `MAX`, signed non-zero integers are
1063 /// a special case. They have a "gap" at 0.
1068 /// #![feature(nonzero_min_max)]
1069 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1071 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1073 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1074 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1080 nonzero_min_max_unsigned! {
1086 NonZeroUsize(usize);
1089 nonzero_min_max_signed! {
1095 NonZeroIsize(isize);
1098 macro_rules! nonzero_bits {
1099 ( $( $Ty: ident($Int: ty); )+ ) => {
1102 /// The size of this non-zero integer type in bits.
1104 #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
1109 /// #![feature(nonzero_bits)]
1110 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1112 #[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
1114 #[unstable(feature = "nonzero_bits", issue = "94881")]
1115 pub const BITS: u32 = <$Int>::BITS;
1132 NonZeroUsize(usize);
1133 NonZeroIsize(isize);