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]
42 #[rustc_diagnostic_item = stringify!($Ty)]
46 /// Creates a non-zero without checking whether the value is non-zero.
47 /// This results in undefined behaviour if the value is zero.
51 /// The value must not be zero.
53 #[$const_new_unchecked_stability]
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!(
60 concat!(stringify!($Ty), "::new_unchecked requires a non-zero argument"),
67 /// Creates a non-zero if the given value is not zero.
69 #[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
72 pub const fn new(n: $Int) -> Option<Self> {
74 // SAFETY: we just checked that there's no `0`
75 Some(unsafe { Self(n) })
81 /// Returns the value as a primitive type.
84 #[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
85 pub const fn get(self) -> $Int {
91 #[stable(feature = "from_nonzero", since = "1.31.0")]
92 #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")]
93 impl const From<$Ty> for $Int {
94 #[doc = concat!("Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`")]
96 fn from(nonzero: $Ty) -> Self {
101 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
102 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
103 impl const BitOr for $Ty {
106 fn bitor(self, rhs: Self) -> Self::Output {
107 // SAFETY: since `self` and `rhs` are both nonzero, the
108 // result of the bitwise-or will be nonzero.
109 unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
113 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
114 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
115 impl const BitOr<$Int> for $Ty {
118 fn bitor(self, rhs: $Int) -> Self::Output {
119 // SAFETY: since `self` is nonzero, the result of the
120 // bitwise-or will be nonzero regardless of the value of
122 unsafe { $Ty::new_unchecked(self.get() | rhs) }
126 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
127 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
128 impl const BitOr<$Ty> for $Int {
131 fn bitor(self, rhs: $Ty) -> Self::Output {
132 // SAFETY: since `rhs` is nonzero, the result of the
133 // bitwise-or will be nonzero regardless of the value of
135 unsafe { $Ty::new_unchecked(self | rhs.get()) }
139 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
140 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
141 impl const BitOrAssign for $Ty {
143 fn bitor_assign(&mut self, rhs: Self) {
148 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
149 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
150 impl const BitOrAssign<$Int> for $Ty {
152 fn bitor_assign(&mut self, rhs: $Int) {
158 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
165 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
166 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
167 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
168 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
169 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
170 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
171 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
172 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
173 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
174 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
175 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
176 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
179 macro_rules! from_str_radix_nzint_impl {
181 #[stable(feature = "nonzero_parse", since = "1.35.0")]
182 impl FromStr for $t {
183 type Err = ParseIntError;
184 fn from_str(src: &str) -> Result<Self, Self::Err> {
185 Self::new(from_str_radix(src, 10)?)
186 .ok_or(ParseIntError {
187 kind: IntErrorKind::Zero
194 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
195 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
197 macro_rules! nonzero_leading_trailing_zeros {
198 ( $( $Ty: ident($Uint: ty) , $LeadingTestExpr:expr ;)+ ) => {
201 /// Returns the number of leading zeros in the binary representation of `self`.
203 /// On many architectures, this function can perform better than `leading_zeros()` on the underlying integer type, as special handling of zero can be avoided.
210 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(", stringify!($LeadingTestExpr), ").unwrap();")]
212 /// assert_eq!(n.leading_zeros(), 0);
214 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
215 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
216 #[must_use = "this returns the result of the operation, \
217 without modifying the original"]
219 pub const fn leading_zeros(self) -> u32 {
220 // SAFETY: since `self` cannot be zero, it is safe to call `ctlz_nonzero`.
221 unsafe { intrinsics::ctlz_nonzero(self.0 as $Uint) as u32 }
224 /// Returns the number of trailing zeros in the binary representation
227 /// On many architectures, this function can perform better than `trailing_zeros()` on the underlying integer type, as special handling of zero can be avoided.
234 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(0b0101000).unwrap();")]
236 /// assert_eq!(n.trailing_zeros(), 3);
238 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
239 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
240 #[must_use = "this returns the result of the operation, \
241 without modifying the original"]
243 pub const fn trailing_zeros(self) -> u32 {
244 // SAFETY: since `self` cannot be zero, it is safe to call `cttz_nonzero`.
245 unsafe { intrinsics::cttz_nonzero(self.0 as $Uint) as u32 }
253 nonzero_leading_trailing_zeros! {
254 NonZeroU8(u8), u8::MAX;
255 NonZeroU16(u16), u16::MAX;
256 NonZeroU32(u32), u32::MAX;
257 NonZeroU64(u64), u64::MAX;
258 NonZeroU128(u128), u128::MAX;
259 NonZeroUsize(usize), usize::MAX;
261 NonZeroI16(u16), -1i16;
262 NonZeroI32(u32), -1i32;
263 NonZeroI64(u64), -1i64;
264 NonZeroI128(u128), -1i128;
265 NonZeroIsize(usize), -1isize;
268 macro_rules! nonzero_integers_div {
269 ( $( $Ty: ident($Int: ty); )+ ) => {
271 #[stable(feature = "nonzero_div", since = "1.51.0")]
272 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
273 impl const Div<$Ty> for $Int {
275 /// This operation rounds towards zero,
276 /// truncating any fractional part of the exact result, and cannot panic.
278 fn div(self, other: $Ty) -> $Int {
279 // SAFETY: div by zero is checked because `other` is a nonzero,
280 // and MIN/-1 is checked because `self` is an unsigned int.
281 unsafe { crate::intrinsics::unchecked_div(self, other.get()) }
285 #[stable(feature = "nonzero_div", since = "1.51.0")]
286 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
287 impl const Rem<$Ty> for $Int {
289 /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
291 fn rem(self, other: $Ty) -> $Int {
292 // SAFETY: rem by zero is checked because `other` is a nonzero,
293 // and MIN/-1 is checked because `self` is an unsigned int.
294 unsafe { crate::intrinsics::unchecked_rem(self, other.get()) }
301 nonzero_integers_div! {
310 // A bunch of methods for unsigned nonzero types only.
311 macro_rules! nonzero_unsigned_operations {
312 ( $( $Ty: ident($Int: ident); )+ ) => {
315 /// Adds an unsigned integer to a non-zero value.
316 /// Checks for overflow and returns [`None`] on overflow.
317 /// As a consequence, the result cannot wrap to zero.
323 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
325 /// # fn main() { test().unwrap(); }
326 /// # fn test() -> Option<()> {
327 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
328 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
329 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
330 stringify!($Int), "::MAX)?;")]
332 /// assert_eq!(Some(two), one.checked_add(1));
333 /// assert_eq!(None, max.checked_add(1));
337 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
338 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
339 #[must_use = "this returns the result of the operation, \
340 without modifying the original"]
342 pub const fn checked_add(self, other: $Int) -> Option<$Ty> {
343 if let Some(result) = self.get().checked_add(other) {
344 // SAFETY: $Int::checked_add returns None on overflow
345 // so the result cannot be zero.
346 Some(unsafe { $Ty::new_unchecked(result) })
352 /// Adds an unsigned integer to a non-zero value.
353 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
358 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
360 /// # fn main() { test().unwrap(); }
361 /// # fn test() -> Option<()> {
362 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
363 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
364 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
365 stringify!($Int), "::MAX)?;")]
367 /// assert_eq!(two, one.saturating_add(1));
368 /// assert_eq!(max, max.saturating_add(1));
372 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
373 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
374 #[must_use = "this returns the result of the operation, \
375 without modifying the original"]
377 pub const fn saturating_add(self, other: $Int) -> $Ty {
378 // SAFETY: $Int::saturating_add returns $Int::MAX on overflow
379 // so the result cannot be zero.
380 unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
383 /// Adds an unsigned integer to a non-zero value,
384 /// assuming overflow cannot occur.
385 /// Overflow is unchecked, and it is undefined behaviour to overflow
386 /// *even if the result would wrap to a non-zero value*.
387 /// The behaviour is undefined as soon as
388 #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
393 /// #![feature(nonzero_ops)]
394 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
396 /// # fn main() { test().unwrap(); }
397 /// # fn test() -> Option<()> {
398 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
399 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
401 /// assert_eq!(two, unsafe { one.unchecked_add(1) });
405 #[unstable(feature = "nonzero_ops", issue = "84186")]
406 #[must_use = "this returns the result of the operation, \
407 without modifying the original"]
409 pub const unsafe fn unchecked_add(self, other: $Int) -> $Ty {
410 // SAFETY: The caller ensures there is no overflow.
411 unsafe { $Ty::new_unchecked(self.get().unchecked_add(other)) }
414 /// Returns the smallest power of two greater than or equal to n.
415 /// Checks for overflow and returns [`None`]
416 /// if the next power of two is greater than the type’s maximum value.
417 /// As a consequence, the result cannot wrap to zero.
422 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
424 /// # fn main() { test().unwrap(); }
425 /// # fn test() -> Option<()> {
426 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
427 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
428 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
429 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
430 stringify!($Int), "::MAX)?;")]
432 /// assert_eq!(Some(two), two.checked_next_power_of_two() );
433 /// assert_eq!(Some(four), three.checked_next_power_of_two() );
434 /// assert_eq!(None, max.checked_next_power_of_two() );
438 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
439 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
440 #[must_use = "this returns the result of the operation, \
441 without modifying the original"]
443 pub const fn checked_next_power_of_two(self) -> Option<$Ty> {
444 if let Some(nz) = self.get().checked_next_power_of_two() {
445 // SAFETY: The next power of two is positive
446 // and overflow is checked.
447 Some(unsafe { $Ty::new_unchecked(nz) })
453 /// Returns the base 2 logarithm of the number, rounded down.
455 /// This is the same operation as
456 #[doc = concat!("[`", stringify!($Int), "::ilog2`],")]
457 /// except that it has no failure cases to worry about
458 /// since this value can never be zero.
463 /// #![feature(int_log)]
464 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
466 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(7).unwrap().ilog2(), 2);")]
467 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(8).unwrap().ilog2(), 3);")]
468 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(9).unwrap().ilog2(), 3);")]
470 #[unstable(feature = "int_log", issue = "70887")]
471 #[must_use = "this returns the result of the operation, \
472 without modifying the original"]
474 pub const fn ilog2(self) -> u32 {
475 Self::BITS - 1 - self.leading_zeros()
478 /// Returns the base 10 logarithm of the number, rounded down.
480 /// This is the same operation as
481 #[doc = concat!("[`", stringify!($Int), "::ilog10`],")]
482 /// except that it has no failure cases to worry about
483 /// since this value can never be zero.
488 /// #![feature(int_log)]
489 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
491 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(99).unwrap().ilog10(), 1);")]
492 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(100).unwrap().ilog10(), 2);")]
493 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(101).unwrap().ilog10(), 2);")]
495 #[unstable(feature = "int_log", issue = "70887")]
496 #[must_use = "this returns the result of the operation, \
497 without modifying the original"]
499 pub const fn ilog10(self) -> u32 {
500 super::int_log10::$Int(self.0)
507 nonzero_unsigned_operations! {
516 // A bunch of methods for signed nonzero types only.
517 macro_rules! nonzero_signed_operations {
518 ( $( $Ty: ident($Int: ty) -> $Uty: ident($Uint: ty); )+ ) => {
521 /// Computes the absolute value of self.
522 #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
523 /// for documentation on overflow behaviour.
528 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
530 /// # fn main() { test().unwrap(); }
531 /// # fn test() -> Option<()> {
532 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
533 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
535 /// assert_eq!(pos, pos.abs());
536 /// assert_eq!(pos, neg.abs());
540 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
541 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
542 #[must_use = "this returns the result of the operation, \
543 without modifying the original"]
545 pub const fn abs(self) -> $Ty {
546 // SAFETY: This cannot overflow to zero.
547 unsafe { $Ty::new_unchecked(self.get().abs()) }
550 /// Checked absolute value.
551 /// Checks for overflow and returns [`None`] if
552 #[doc = concat!("`self == ", stringify!($Int), "::MIN`.")]
553 /// The result cannot be zero.
558 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
560 /// # fn main() { test().unwrap(); }
561 /// # fn test() -> Option<()> {
562 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
563 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
564 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
565 stringify!($Int), "::MIN)?;")]
567 /// assert_eq!(Some(pos), neg.checked_abs());
568 /// assert_eq!(None, min.checked_abs());
572 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
573 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
574 #[must_use = "this returns the result of the operation, \
575 without modifying the original"]
577 pub const fn checked_abs(self) -> Option<$Ty> {
578 if let Some(nz) = self.get().checked_abs() {
579 // SAFETY: absolute value of nonzero cannot yield zero values.
580 Some(unsafe { $Ty::new_unchecked(nz) })
586 /// Computes the absolute value of self,
587 /// with overflow information, see
588 #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
593 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
595 /// # fn main() { test().unwrap(); }
596 /// # fn test() -> Option<()> {
597 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
598 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
599 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
600 stringify!($Int), "::MIN)?;")]
602 /// assert_eq!((pos, false), pos.overflowing_abs());
603 /// assert_eq!((pos, false), neg.overflowing_abs());
604 /// assert_eq!((min, true), min.overflowing_abs());
608 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
609 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
610 #[must_use = "this returns the result of the operation, \
611 without modifying the original"]
613 pub const fn overflowing_abs(self) -> ($Ty, bool) {
614 let (nz, flag) = self.get().overflowing_abs();
616 // SAFETY: absolute value of nonzero cannot yield zero values.
617 unsafe { $Ty::new_unchecked(nz) },
622 /// Saturating absolute value, see
623 #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
628 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
630 /// # fn main() { test().unwrap(); }
631 /// # fn test() -> Option<()> {
632 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
633 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
634 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
635 stringify!($Int), "::MIN)?;")]
636 #[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
637 stringify!($Int), "::MIN + 1)?;")]
638 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
639 stringify!($Int), "::MAX)?;")]
641 /// assert_eq!(pos, pos.saturating_abs());
642 /// assert_eq!(pos, neg.saturating_abs());
643 /// assert_eq!(max, min.saturating_abs());
644 /// assert_eq!(max, min_plus.saturating_abs());
648 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
649 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
650 #[must_use = "this returns the result of the operation, \
651 without modifying the original"]
653 pub const fn saturating_abs(self) -> $Ty {
654 // SAFETY: absolute value of nonzero cannot yield zero values.
655 unsafe { $Ty::new_unchecked(self.get().saturating_abs()) }
658 /// Wrapping absolute value, see
659 #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
664 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
666 /// # fn main() { test().unwrap(); }
667 /// # fn test() -> Option<()> {
668 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
669 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
670 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
671 stringify!($Int), "::MIN)?;")]
672 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
673 stringify!($Int), "::MAX)?;")]
675 /// assert_eq!(pos, pos.wrapping_abs());
676 /// assert_eq!(pos, neg.wrapping_abs());
677 /// assert_eq!(min, min.wrapping_abs());
678 /// # // FIXME: add once Neg is implemented?
679 /// # // assert_eq!(max, (-max).wrapping_abs());
683 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
684 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
685 #[must_use = "this returns the result of the operation, \
686 without modifying the original"]
688 pub const fn wrapping_abs(self) -> $Ty {
689 // SAFETY: absolute value of nonzero cannot yield zero values.
690 unsafe { $Ty::new_unchecked(self.get().wrapping_abs()) }
693 /// Computes the absolute value of self
694 /// without any wrapping or panicking.
699 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
700 #[doc = concat!("# use std::num::", stringify!($Uty), ";")]
702 /// # fn main() { test().unwrap(); }
703 /// # fn test() -> Option<()> {
704 #[doc = concat!("let u_pos = ", stringify!($Uty), "::new(1)?;")]
705 #[doc = concat!("let i_pos = ", stringify!($Ty), "::new(1)?;")]
706 #[doc = concat!("let i_neg = ", stringify!($Ty), "::new(-1)?;")]
707 #[doc = concat!("let i_min = ", stringify!($Ty), "::new(",
708 stringify!($Int), "::MIN)?;")]
709 #[doc = concat!("let u_max = ", stringify!($Uty), "::new(",
710 stringify!($Uint), "::MAX / 2 + 1)?;")]
712 /// assert_eq!(u_pos, i_pos.unsigned_abs());
713 /// assert_eq!(u_pos, i_neg.unsigned_abs());
714 /// assert_eq!(u_max, i_min.unsigned_abs());
718 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
719 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
720 #[must_use = "this returns the result of the operation, \
721 without modifying the original"]
723 pub const fn unsigned_abs(self) -> $Uty {
724 // SAFETY: absolute value of nonzero cannot yield zero values.
725 unsafe { $Uty::new_unchecked(self.get().unsigned_abs()) }
728 /// Returns `true` if `self` is negative and `false` if the
729 /// number is positive.
734 /// #![feature(nonzero_negation_ops)]
736 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
737 /// # fn main() { test().unwrap(); }
738 /// # fn test() -> Option<()> {
739 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
740 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
742 /// assert!(neg_five.is_negative());
743 /// assert!(!pos_five.is_negative());
749 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
750 pub const fn is_negative(self) -> bool {
751 self.get().is_negative()
754 /// Checked negation. Computes `-self`, returning `None` if `self == i32::MIN`.
759 /// #![feature(nonzero_negation_ops)]
761 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
762 /// # fn main() { test().unwrap(); }
763 /// # fn test() -> Option<()> {
764 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
765 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
766 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
767 stringify!($Int), "::MIN)?;")]
769 /// assert_eq!(pos_five.checked_neg(), Some(neg_five));
770 /// assert_eq!(min.checked_neg(), None);
775 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
776 pub const fn checked_neg(self) -> Option<$Ty> {
777 if let Some(result) = self.get().checked_neg() {
778 // SAFETY: negation of nonzero cannot yield zero values.
779 return Some(unsafe { $Ty::new_unchecked(result) });
784 /// Negates self, overflowing if this is equal to the minimum value.
786 #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")]
787 /// for documentation on overflow behaviour.
792 /// #![feature(nonzero_negation_ops)]
794 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
795 /// # fn main() { test().unwrap(); }
796 /// # fn test() -> Option<()> {
797 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
798 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
799 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
800 stringify!($Int), "::MIN)?;")]
802 /// assert_eq!(pos_five.overflowing_neg(), (neg_five, false));
803 /// assert_eq!(min.overflowing_neg(), (min, true));
808 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
809 pub const fn overflowing_neg(self) -> ($Ty, bool) {
810 let (result, overflow) = self.get().overflowing_neg();
811 // SAFETY: negation of nonzero cannot yield zero values.
812 ((unsafe { $Ty::new_unchecked(result) }), overflow)
815 /// Saturating negation. Computes `-self`, returning `MAX` if
816 /// `self == i32::MIN` instead of overflowing.
821 /// #![feature(nonzero_negation_ops)]
823 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
824 /// # fn main() { test().unwrap(); }
825 /// # fn test() -> Option<()> {
826 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
827 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
828 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
829 stringify!($Int), "::MIN)?;")]
830 #[doc = concat!("let min_plus_one = ", stringify!($Ty), "::new(",
831 stringify!($Int), "::MIN + 1)?;")]
832 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
833 stringify!($Int), "::MAX)?;")]
835 /// assert_eq!(pos_five.saturating_neg(), neg_five);
836 /// assert_eq!(min.saturating_neg(), max);
837 /// assert_eq!(max.saturating_neg(), min_plus_one);
842 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
843 pub const fn saturating_neg(self) -> $Ty {
844 if let Some(result) = self.checked_neg() {
850 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
853 #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")]
854 /// for documentation on overflow behaviour.
859 /// #![feature(nonzero_negation_ops)]
861 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
862 /// # fn main() { test().unwrap(); }
863 /// # fn test() -> Option<()> {
864 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
865 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
866 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
867 stringify!($Int), "::MIN)?;")]
869 /// assert_eq!(pos_five.wrapping_neg(), neg_five);
870 /// assert_eq!(min.wrapping_neg(), min);
875 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
876 pub const fn wrapping_neg(self) -> $Ty {
877 let result = self.get().wrapping_neg();
878 // SAFETY: negation of nonzero cannot yield zero values.
879 unsafe { $Ty::new_unchecked(result) }
886 nonzero_signed_operations! {
887 NonZeroI8(i8) -> NonZeroU8(u8);
888 NonZeroI16(i16) -> NonZeroU16(u16);
889 NonZeroI32(i32) -> NonZeroU32(u32);
890 NonZeroI64(i64) -> NonZeroU64(u64);
891 NonZeroI128(i128) -> NonZeroU128(u128);
892 NonZeroIsize(isize) -> NonZeroUsize(usize);
895 // A bunch of methods for both signed and unsigned nonzero types.
896 macro_rules! nonzero_unsigned_signed_operations {
897 ( $( $signedness:ident $Ty: ident($Int: ty); )+ ) => {
900 /// Multiplies two non-zero integers together.
901 /// Checks for overflow and returns [`None`] on overflow.
902 /// As a consequence, the result cannot wrap to zero.
907 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
909 /// # fn main() { test().unwrap(); }
910 /// # fn test() -> Option<()> {
911 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
912 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
913 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
914 stringify!($Int), "::MAX)?;")]
916 /// assert_eq!(Some(four), two.checked_mul(two));
917 /// assert_eq!(None, max.checked_mul(two));
921 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
922 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
923 #[must_use = "this returns the result of the operation, \
924 without modifying the original"]
926 pub const fn checked_mul(self, other: $Ty) -> Option<$Ty> {
927 if let Some(result) = self.get().checked_mul(other.get()) {
928 // SAFETY: checked_mul returns None on overflow
929 // and `other` is also non-null
930 // so the result cannot be zero.
931 Some(unsafe { $Ty::new_unchecked(result) })
937 /// Multiplies two non-zero integers together.
938 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
943 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
945 /// # fn main() { test().unwrap(); }
946 /// # fn test() -> Option<()> {
947 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
948 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
949 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
950 stringify!($Int), "::MAX)?;")]
952 /// assert_eq!(four, two.saturating_mul(two));
953 /// assert_eq!(max, four.saturating_mul(max));
957 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
958 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
959 #[must_use = "this returns the result of the operation, \
960 without modifying the original"]
962 pub const fn saturating_mul(self, other: $Ty) -> $Ty {
963 // SAFETY: saturating_mul returns u*::MAX on overflow
964 // and `other` is also non-null
965 // so the result cannot be zero.
966 unsafe { $Ty::new_unchecked(self.get().saturating_mul(other.get())) }
969 /// Multiplies two non-zero integers together,
970 /// assuming overflow cannot occur.
971 /// Overflow is unchecked, and it is undefined behaviour to overflow
972 /// *even if the result would wrap to a non-zero value*.
973 /// The behaviour is undefined as soon as
974 #[doc = sign_dependent_expr!{
977 concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
978 "or `self * rhs < ", stringify!($Int), "::MIN`.")
981 concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
988 /// #![feature(nonzero_ops)]
989 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
991 /// # fn main() { test().unwrap(); }
992 /// # fn test() -> Option<()> {
993 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
994 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
996 /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
1000 #[unstable(feature = "nonzero_ops", issue = "84186")]
1001 #[must_use = "this returns the result of the operation, \
1002 without modifying the original"]
1004 pub const unsafe fn unchecked_mul(self, other: $Ty) -> $Ty {
1005 // SAFETY: The caller ensures there is no overflow.
1006 unsafe { $Ty::new_unchecked(self.get().unchecked_mul(other.get())) }
1009 /// Raises non-zero value to an integer power.
1010 /// Checks for overflow and returns [`None`] on overflow.
1011 /// As a consequence, the result cannot wrap to zero.
1016 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1018 /// # fn main() { test().unwrap(); }
1019 /// # fn test() -> Option<()> {
1020 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
1021 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
1022 #[doc = concat!("let half_max = ", stringify!($Ty), "::new(",
1023 stringify!($Int), "::MAX / 2)?;")]
1025 /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
1026 /// assert_eq!(None, half_max.checked_pow(3));
1030 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1031 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1032 #[must_use = "this returns the result of the operation, \
1033 without modifying the original"]
1035 pub const fn checked_pow(self, other: u32) -> Option<$Ty> {
1036 if let Some(result) = self.get().checked_pow(other) {
1037 // SAFETY: checked_pow returns None on overflow
1038 // so the result cannot be zero.
1039 Some(unsafe { $Ty::new_unchecked(result) })
1045 /// Raise non-zero value to an integer power.
1046 #[doc = sign_dependent_expr!{
1049 concat!("Return [`", stringify!($Int), "::MIN`] ",
1050 "or [`", stringify!($Int), "::MAX`] on overflow.")
1053 concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")
1060 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1062 /// # fn main() { test().unwrap(); }
1063 /// # fn test() -> Option<()> {
1064 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
1065 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
1066 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
1067 stringify!($Int), "::MAX)?;")]
1069 /// assert_eq!(twenty_seven, three.saturating_pow(3));
1070 /// assert_eq!(max, max.saturating_pow(3));
1074 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1075 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1076 #[must_use = "this returns the result of the operation, \
1077 without modifying the original"]
1079 pub const fn saturating_pow(self, other: u32) -> $Ty {
1080 // SAFETY: saturating_pow returns u*::MAX on overflow
1081 // so the result cannot be zero.
1082 unsafe { $Ty::new_unchecked(self.get().saturating_pow(other)) }
1089 // Use this when the generated code should differ between signed and unsigned types.
1090 macro_rules! sign_dependent_expr {
1091 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1094 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1099 nonzero_unsigned_signed_operations! {
1100 unsigned NonZeroU8(u8);
1101 unsigned NonZeroU16(u16);
1102 unsigned NonZeroU32(u32);
1103 unsigned NonZeroU64(u64);
1104 unsigned NonZeroU128(u128);
1105 unsigned NonZeroUsize(usize);
1106 signed NonZeroI8(i8);
1107 signed NonZeroI16(i16);
1108 signed NonZeroI32(i32);
1109 signed NonZeroI64(i64);
1110 signed NonZeroI128(i128);
1111 signed NonZeroIsize(isize);
1114 macro_rules! nonzero_unsigned_is_power_of_two {
1115 ( $( $Ty: ident )+ ) => {
1119 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
1121 /// On many architectures, this function can perform better than `is_power_of_two()`
1122 /// on the underlying integer type, as special handling of zero can be avoided.
1129 #[doc = concat!("let eight = std::num::", stringify!($Ty), "::new(8).unwrap();")]
1130 /// assert!(eight.is_power_of_two());
1131 #[doc = concat!("let ten = std::num::", stringify!($Ty), "::new(10).unwrap();")]
1132 /// assert!(!ten.is_power_of_two());
1135 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1136 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1138 pub const fn is_power_of_two(self) -> bool {
1139 // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
1140 // On the basic x86-64 target, this saves 3 instructions for the zero check.
1141 // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
1142 // compared to the `POPCNT` implementation on the underlying integer type.
1144 intrinsics::ctpop(self.get()) < 2
1152 nonzero_unsigned_is_power_of_two! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize }
1154 macro_rules! nonzero_min_max_unsigned {
1155 ( $( $Ty: ident($Int: ident); )+ ) => {
1158 /// The smallest value that can be represented by this non-zero
1159 /// integer type, 1.
1164 /// #![feature(nonzero_min_max)]
1165 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1167 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), 1", stringify!($Int), ");")]
1169 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1170 pub const MIN: Self = Self::new(1).unwrap();
1172 /// The largest value that can be represented by this non-zero
1174 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1179 /// #![feature(nonzero_min_max)]
1180 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1182 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1184 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1185 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1191 macro_rules! nonzero_min_max_signed {
1192 ( $( $Ty: ident($Int: ident); )+ ) => {
1195 /// The smallest value that can be represented by this non-zero
1197 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1199 /// Note: While most integer types are defined for every whole
1200 /// number between `MIN` and `MAX`, signed non-zero integers are
1201 /// a special case. They have a "gap" at 0.
1206 /// #![feature(nonzero_min_max)]
1207 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1209 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), ", stringify!($Int), "::MIN);")]
1211 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1212 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1214 /// The largest value that can be represented by this non-zero
1216 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1218 /// Note: While most integer types are defined for every whole
1219 /// number between `MIN` and `MAX`, signed non-zero integers are
1220 /// a special case. They have a "gap" at 0.
1225 /// #![feature(nonzero_min_max)]
1226 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1228 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1230 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1231 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1237 nonzero_min_max_unsigned! {
1243 NonZeroUsize(usize);
1246 nonzero_min_max_signed! {
1252 NonZeroIsize(isize);
1255 macro_rules! nonzero_bits {
1256 ( $( $Ty: ident($Int: ty); )+ ) => {
1259 /// The size of this non-zero integer type in bits.
1261 #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
1266 /// #![feature(nonzero_bits)]
1267 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1269 #[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
1271 #[unstable(feature = "nonzero_bits", issue = "94881")]
1272 pub const BITS: u32 = <$Int>::BITS;
1289 NonZeroUsize(usize);
1290 NonZeroIsize(isize);