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!((n: $Int) => 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` cannot 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` cannot 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 /// Adds an unsigned integer to a non-zero value.
313 /// Checks for overflow and returns [`None`] on overflow.
314 /// As a consequence, the result cannot wrap to zero.
320 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
322 /// # fn main() { test().unwrap(); }
323 /// # fn test() -> Option<()> {
324 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
325 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
326 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
327 stringify!($Int), "::MAX)?;")]
329 /// assert_eq!(Some(two), one.checked_add(1));
330 /// assert_eq!(None, max.checked_add(1));
334 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
335 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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 /// Adds an unsigned integer to a non-zero value.
350 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
355 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
357 /// # fn main() { test().unwrap(); }
358 /// # fn test() -> Option<()> {
359 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
360 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
361 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
362 stringify!($Int), "::MAX)?;")]
364 /// assert_eq!(two, one.saturating_add(1));
365 /// assert_eq!(max, max.saturating_add(1));
369 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
370 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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 /// Adds 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 /// Checks for overflow and returns [`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 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
421 /// # fn main() { test().unwrap(); }
422 /// # fn test() -> Option<()> {
423 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
424 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
425 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
426 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
427 stringify!($Int), "::MAX)?;")]
429 /// assert_eq!(Some(two), two.checked_next_power_of_two() );
430 /// assert_eq!(Some(four), three.checked_next_power_of_two() );
431 /// assert_eq!(None, max.checked_next_power_of_two() );
435 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
436 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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), "::ilog2`],")]
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().ilog2(), 2);")]
464 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(8).unwrap().ilog2(), 3);")]
465 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(9).unwrap().ilog2(), 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 ilog2(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), "::ilog10`],")]
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().ilog10(), 1);")]
489 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(100).unwrap().ilog10(), 2);")]
490 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(101).unwrap().ilog10(), 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 ilog10(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 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
527 /// # fn main() { test().unwrap(); }
528 /// # fn test() -> Option<()> {
529 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
530 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
532 /// assert_eq!(pos, pos.abs());
533 /// assert_eq!(pos, neg.abs());
537 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
538 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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 /// Checks for overflow and returns [`None`] if
549 #[doc = concat!("`self == ", stringify!($Int), "::MIN`.")]
550 /// The result cannot be zero.
555 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
557 /// # fn main() { test().unwrap(); }
558 /// # fn test() -> Option<()> {
559 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
560 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
561 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
562 stringify!($Int), "::MIN)?;")]
564 /// assert_eq!(Some(pos), neg.checked_abs());
565 /// assert_eq!(None, min.checked_abs());
569 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
570 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
592 /// # fn main() { test().unwrap(); }
593 /// # fn test() -> Option<()> {
594 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
595 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
596 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
597 stringify!($Int), "::MIN)?;")]
599 /// assert_eq!((pos, false), pos.overflowing_abs());
600 /// assert_eq!((pos, false), neg.overflowing_abs());
601 /// assert_eq!((min, true), min.overflowing_abs());
605 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
606 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
627 /// # fn main() { test().unwrap(); }
628 /// # fn test() -> Option<()> {
629 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
630 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
631 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
632 stringify!($Int), "::MIN)?;")]
633 #[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
634 stringify!($Int), "::MIN + 1)?;")]
635 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
636 stringify!($Int), "::MAX)?;")]
638 /// assert_eq!(pos, pos.saturating_abs());
639 /// assert_eq!(pos, neg.saturating_abs());
640 /// assert_eq!(max, min.saturating_abs());
641 /// assert_eq!(max, min_plus.saturating_abs());
645 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
646 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
663 /// # fn main() { test().unwrap(); }
664 /// # fn test() -> Option<()> {
665 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
666 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
667 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
668 stringify!($Int), "::MIN)?;")]
669 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
670 stringify!($Int), "::MAX)?;")]
672 /// assert_eq!(pos, pos.wrapping_abs());
673 /// assert_eq!(pos, neg.wrapping_abs());
674 /// assert_eq!(min, min.wrapping_abs());
675 /// # // FIXME: add once Neg is implemented?
676 /// # // assert_eq!(max, (-max).wrapping_abs());
680 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
681 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
697 #[doc = concat!("# use std::num::", stringify!($Uty), ";")]
699 /// # fn main() { test().unwrap(); }
700 /// # fn test() -> Option<()> {
701 #[doc = concat!("let u_pos = ", stringify!($Uty), "::new(1)?;")]
702 #[doc = concat!("let i_pos = ", stringify!($Ty), "::new(1)?;")]
703 #[doc = concat!("let i_neg = ", stringify!($Ty), "::new(-1)?;")]
704 #[doc = concat!("let i_min = ", stringify!($Ty), "::new(",
705 stringify!($Int), "::MIN)?;")]
706 #[doc = concat!("let u_max = ", stringify!($Uty), "::new(",
707 stringify!($Uint), "::MAX / 2 + 1)?;")]
709 /// assert_eq!(u_pos, i_pos.unsigned_abs());
710 /// assert_eq!(u_pos, i_neg.unsigned_abs());
711 /// assert_eq!(u_max, i_min.unsigned_abs());
715 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
716 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
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()) }
725 /// Returns `true` if `self` is negative and `false` if the
726 /// number is positive.
731 /// #![feature(nonzero_negation_ops)]
733 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
734 /// # fn main() { test().unwrap(); }
735 /// # fn test() -> Option<()> {
736 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
737 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
739 /// assert!(neg_five.is_negative());
740 /// assert!(!pos_five.is_negative());
746 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
747 pub const fn is_negative(self) -> bool {
748 self.get().is_negative()
751 /// Checked negation. Computes `-self`, returning `None` if `self == i32::MIN`.
756 /// #![feature(nonzero_negation_ops)]
758 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
759 /// # fn main() { test().unwrap(); }
760 /// # fn test() -> Option<()> {
761 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
762 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
763 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
764 stringify!($Int), "::MIN)?;")]
766 /// assert_eq!(pos_five.checked_neg(), Some(neg_five));
767 /// assert_eq!(min.checked_neg(), None);
772 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
773 pub const fn checked_neg(self) -> Option<$Ty> {
774 if let Some(result) = self.get().checked_neg() {
775 // SAFETY: negation of nonzero cannot yield zero values.
776 return Some(unsafe { $Ty::new_unchecked(result) });
781 /// Negates self, overflowing if this is equal to the minimum value.
783 #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")]
784 /// for documentation on overflow behaviour.
789 /// #![feature(nonzero_negation_ops)]
791 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
792 /// # fn main() { test().unwrap(); }
793 /// # fn test() -> Option<()> {
794 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
795 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
796 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
797 stringify!($Int), "::MIN)?;")]
799 /// assert_eq!(pos_five.overflowing_neg(), (neg_five, false));
800 /// assert_eq!(min.overflowing_neg(), (min, true));
805 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
806 pub const fn overflowing_neg(self) -> ($Ty, bool) {
807 let (result, overflow) = self.get().overflowing_neg();
808 // SAFETY: negation of nonzero cannot yield zero values.
809 ((unsafe { $Ty::new_unchecked(result) }), overflow)
812 /// Saturating negation. Computes `-self`, returning `MAX` if
813 /// `self == i32::MIN` instead of overflowing.
818 /// #![feature(nonzero_negation_ops)]
820 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
821 /// # fn main() { test().unwrap(); }
822 /// # fn test() -> Option<()> {
823 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
824 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
825 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
826 stringify!($Int), "::MIN)?;")]
827 #[doc = concat!("let min_plus_one = ", stringify!($Ty), "::new(",
828 stringify!($Int), "::MIN + 1)?;")]
829 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
830 stringify!($Int), "::MAX)?;")]
832 /// assert_eq!(pos_five.saturating_neg(), neg_five);
833 /// assert_eq!(min.saturating_neg(), max);
834 /// assert_eq!(max.saturating_neg(), min_plus_one);
839 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
840 pub const fn saturating_neg(self) -> $Ty {
841 if let Some(result) = self.checked_neg() {
847 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
850 #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")]
851 /// for documentation on overflow behaviour.
856 /// #![feature(nonzero_negation_ops)]
858 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
859 /// # fn main() { test().unwrap(); }
860 /// # fn test() -> Option<()> {
861 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
862 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
863 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
864 stringify!($Int), "::MIN)?;")]
866 /// assert_eq!(pos_five.wrapping_neg(), neg_five);
867 /// assert_eq!(min.wrapping_neg(), min);
872 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
873 pub const fn wrapping_neg(self) -> $Ty {
874 let result = self.get().wrapping_neg();
875 // SAFETY: negation of nonzero cannot yield zero values.
876 unsafe { $Ty::new_unchecked(result) }
883 nonzero_signed_operations! {
884 NonZeroI8(i8) -> NonZeroU8(u8);
885 NonZeroI16(i16) -> NonZeroU16(u16);
886 NonZeroI32(i32) -> NonZeroU32(u32);
887 NonZeroI64(i64) -> NonZeroU64(u64);
888 NonZeroI128(i128) -> NonZeroU128(u128);
889 NonZeroIsize(isize) -> NonZeroUsize(usize);
892 // A bunch of methods for both signed and unsigned nonzero types.
893 macro_rules! nonzero_unsigned_signed_operations {
894 ( $( $signedness:ident $Ty: ident($Int: ty); )+ ) => {
897 /// Multiplies two non-zero integers together.
898 /// Checks for overflow and returns [`None`] on overflow.
899 /// As a consequence, the result cannot wrap to zero.
904 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
906 /// # fn main() { test().unwrap(); }
907 /// # fn test() -> Option<()> {
908 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
909 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
910 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
911 stringify!($Int), "::MAX)?;")]
913 /// assert_eq!(Some(four), two.checked_mul(two));
914 /// assert_eq!(None, max.checked_mul(two));
918 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
919 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
920 #[must_use = "this returns the result of the operation, \
921 without modifying the original"]
923 pub const fn checked_mul(self, other: $Ty) -> Option<$Ty> {
924 if let Some(result) = self.get().checked_mul(other.get()) {
925 // SAFETY: checked_mul returns None on overflow
926 // and `other` is also non-null
927 // so the result cannot be zero.
928 Some(unsafe { $Ty::new_unchecked(result) })
934 /// Multiplies two non-zero integers together.
935 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
940 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
942 /// # fn main() { test().unwrap(); }
943 /// # fn test() -> Option<()> {
944 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
945 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
946 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
947 stringify!($Int), "::MAX)?;")]
949 /// assert_eq!(four, two.saturating_mul(two));
950 /// assert_eq!(max, four.saturating_mul(max));
954 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
955 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
956 #[must_use = "this returns the result of the operation, \
957 without modifying the original"]
959 pub const fn saturating_mul(self, other: $Ty) -> $Ty {
960 // SAFETY: saturating_mul returns u*::MAX on overflow
961 // and `other` is also non-null
962 // so the result cannot be zero.
963 unsafe { $Ty::new_unchecked(self.get().saturating_mul(other.get())) }
966 /// Multiplies two non-zero integers together,
967 /// assuming overflow cannot occur.
968 /// Overflow is unchecked, and it is undefined behaviour to overflow
969 /// *even if the result would wrap to a non-zero value*.
970 /// The behaviour is undefined as soon as
971 #[doc = sign_dependent_expr!{
974 concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
975 "or `self * rhs < ", stringify!($Int), "::MIN`.")
978 concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
985 /// #![feature(nonzero_ops)]
986 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
988 /// # fn main() { test().unwrap(); }
989 /// # fn test() -> Option<()> {
990 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
991 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
993 /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
997 #[unstable(feature = "nonzero_ops", issue = "84186")]
998 #[must_use = "this returns the result of the operation, \
999 without modifying the original"]
1001 pub const unsafe fn unchecked_mul(self, other: $Ty) -> $Ty {
1002 // SAFETY: The caller ensures there is no overflow.
1003 unsafe { $Ty::new_unchecked(self.get().unchecked_mul(other.get())) }
1006 /// Raises non-zero value to an integer power.
1007 /// Checks for overflow and returns [`None`] on overflow.
1008 /// As a consequence, the result cannot wrap to zero.
1013 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1015 /// # fn main() { test().unwrap(); }
1016 /// # fn test() -> Option<()> {
1017 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
1018 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
1019 #[doc = concat!("let half_max = ", stringify!($Ty), "::new(",
1020 stringify!($Int), "::MAX / 2)?;")]
1022 /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
1023 /// assert_eq!(None, half_max.checked_pow(3));
1027 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1028 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1029 #[must_use = "this returns the result of the operation, \
1030 without modifying the original"]
1032 pub const fn checked_pow(self, other: u32) -> Option<$Ty> {
1033 if let Some(result) = self.get().checked_pow(other) {
1034 // SAFETY: checked_pow returns None on overflow
1035 // so the result cannot be zero.
1036 Some(unsafe { $Ty::new_unchecked(result) })
1042 /// Raise non-zero value to an integer power.
1043 #[doc = sign_dependent_expr!{
1046 concat!("Return [`", stringify!($Int), "::MIN`] ",
1047 "or [`", stringify!($Int), "::MAX`] on overflow.")
1050 concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")
1057 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1059 /// # fn main() { test().unwrap(); }
1060 /// # fn test() -> Option<()> {
1061 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
1062 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
1063 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
1064 stringify!($Int), "::MAX)?;")]
1066 /// assert_eq!(twenty_seven, three.saturating_pow(3));
1067 /// assert_eq!(max, max.saturating_pow(3));
1071 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1072 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1073 #[must_use = "this returns the result of the operation, \
1074 without modifying the original"]
1076 pub const fn saturating_pow(self, other: u32) -> $Ty {
1077 // SAFETY: saturating_pow returns u*::MAX on overflow
1078 // so the result cannot be zero.
1079 unsafe { $Ty::new_unchecked(self.get().saturating_pow(other)) }
1086 // Use this when the generated code should differ between signed and unsigned types.
1087 macro_rules! sign_dependent_expr {
1088 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1091 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1096 nonzero_unsigned_signed_operations! {
1097 unsigned NonZeroU8(u8);
1098 unsigned NonZeroU16(u16);
1099 unsigned NonZeroU32(u32);
1100 unsigned NonZeroU64(u64);
1101 unsigned NonZeroU128(u128);
1102 unsigned NonZeroUsize(usize);
1103 signed NonZeroI8(i8);
1104 signed NonZeroI16(i16);
1105 signed NonZeroI32(i32);
1106 signed NonZeroI64(i64);
1107 signed NonZeroI128(i128);
1108 signed NonZeroIsize(isize);
1111 macro_rules! nonzero_unsigned_is_power_of_two {
1112 ( $( $Ty: ident )+ ) => {
1116 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
1118 /// On many architectures, this function can perform better than `is_power_of_two()`
1119 /// on the underlying integer type, as special handling of zero can be avoided.
1126 #[doc = concat!("let eight = std::num::", stringify!($Ty), "::new(8).unwrap();")]
1127 /// assert!(eight.is_power_of_two());
1128 #[doc = concat!("let ten = std::num::", stringify!($Ty), "::new(10).unwrap();")]
1129 /// assert!(!ten.is_power_of_two());
1132 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1133 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1135 pub const fn is_power_of_two(self) -> bool {
1136 // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
1137 // On the basic x86-64 target, this saves 3 instructions for the zero check.
1138 // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
1139 // compared to the `POPCNT` implementation on the underlying integer type.
1141 intrinsics::ctpop(self.get()) < 2
1149 nonzero_unsigned_is_power_of_two! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize }
1151 macro_rules! nonzero_min_max_unsigned {
1152 ( $( $Ty: ident($Int: ident); )+ ) => {
1155 /// The smallest value that can be represented by this non-zero
1156 /// integer type, 1.
1161 /// #![feature(nonzero_min_max)]
1162 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1164 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), 1", stringify!($Int), ");")]
1166 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1167 pub const MIN: Self = Self::new(1).unwrap();
1169 /// The largest value that can be represented by this non-zero
1171 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1176 /// #![feature(nonzero_min_max)]
1177 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1179 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1181 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1182 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1188 macro_rules! nonzero_min_max_signed {
1189 ( $( $Ty: ident($Int: ident); )+ ) => {
1192 /// The smallest value that can be represented by this non-zero
1194 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1196 /// Note: While most integer types are defined for every whole
1197 /// number between `MIN` and `MAX`, signed non-zero integers are
1198 /// a special case. They have a "gap" at 0.
1203 /// #![feature(nonzero_min_max)]
1204 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1206 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), ", stringify!($Int), "::MIN);")]
1208 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1209 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1211 /// The largest value that can be represented by this non-zero
1213 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1215 /// Note: While most integer types are defined for every whole
1216 /// number between `MIN` and `MAX`, signed non-zero integers are
1217 /// a special case. They have a "gap" at 0.
1222 /// #![feature(nonzero_min_max)]
1223 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1225 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1227 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1228 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1234 nonzero_min_max_unsigned! {
1240 NonZeroUsize(usize);
1243 nonzero_min_max_signed! {
1249 NonZeroIsize(isize);
1252 macro_rules! nonzero_bits {
1253 ( $( $Ty: ident($Int: ty); )+ ) => {
1256 /// The size of this non-zero integer type in bits.
1258 #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
1263 /// #![feature(nonzero_bits)]
1264 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1266 #[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
1268 #[unstable(feature = "nonzero_bits", issue = "94881")]
1269 pub const BITS: u32 = <$Int>::BITS;
1286 NonZeroUsize(usize);
1287 NonZeroIsize(isize);