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), ";")]
324 /// # fn main() { test().unwrap(); }
325 /// # fn test() -> Option<()> {
326 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
327 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
328 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
329 stringify!($Int), "::MAX)?;")]
331 /// assert_eq!(Some(two), one.checked_add(1));
332 /// assert_eq!(None, max.checked_add(1));
336 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
337 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
338 #[must_use = "this returns the result of the operation, \
339 without modifying the original"]
341 pub const fn checked_add(self, other: $Int) -> Option<$Ty> {
342 if let Some(result) = self.get().checked_add(other) {
343 // SAFETY: $Int::checked_add returns None on overflow
344 // so the result cannot be zero.
345 Some(unsafe { $Ty::new_unchecked(result) })
351 /// Adds an unsigned integer to a non-zero value.
352 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
357 #[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 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
371 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
372 #[must_use = "this returns the result of the operation, \
373 without modifying the original"]
375 pub const fn saturating_add(self, other: $Int) -> $Ty {
376 // SAFETY: $Int::saturating_add returns $Int::MAX on overflow
377 // so the result cannot be zero.
378 unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
381 /// Adds an unsigned integer to a non-zero value,
382 /// assuming overflow cannot occur.
383 /// Overflow is unchecked, and it is undefined behaviour to overflow
384 /// *even if the result would wrap to a non-zero value*.
385 /// The behaviour is undefined as soon as
386 #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
391 /// #![feature(nonzero_ops)]
393 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
394 /// # fn main() { test().unwrap(); }
395 /// # fn test() -> Option<()> {
396 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
397 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
399 /// assert_eq!(two, unsafe { one.unchecked_add(1) });
403 #[unstable(feature = "nonzero_ops", issue = "84186")]
404 #[must_use = "this returns the result of the operation, \
405 without modifying the original"]
407 pub const unsafe fn unchecked_add(self, other: $Int) -> $Ty {
408 // SAFETY: The caller ensures there is no overflow.
409 unsafe { $Ty::new_unchecked(self.get().unchecked_add(other)) }
412 /// Returns the smallest power of two greater than or equal to n.
413 /// Checks for overflow and returns [`None`]
414 /// if the next power of two is greater than the type’s maximum value.
415 /// As a consequence, the result cannot wrap to zero.
420 #[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 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
461 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(7).unwrap().ilog2(), 2);")]
462 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(8).unwrap().ilog2(), 3);")]
463 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(9).unwrap().ilog2(), 3);")]
465 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
466 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
467 #[must_use = "this returns the result of the operation, \
468 without modifying the original"]
470 pub const fn ilog2(self) -> u32 {
471 Self::BITS - 1 - self.leading_zeros()
474 /// Returns the base 10 logarithm of the number, rounded down.
476 /// This is the same operation as
477 #[doc = concat!("[`", stringify!($Int), "::ilog10`],")]
478 /// except that it has no failure cases to worry about
479 /// since this value can never be zero.
484 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
485 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(99).unwrap().ilog10(), 1);")]
486 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(100).unwrap().ilog10(), 2);")]
487 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(101).unwrap().ilog10(), 2);")]
489 #[stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
490 #[rustc_const_stable(feature = "int_log", since = "CURRENT_RUSTC_VERSION")]
491 #[must_use = "this returns the result of the operation, \
492 without modifying the original"]
494 pub const fn ilog10(self) -> u32 {
495 super::int_log10::$Int(self.0)
502 nonzero_unsigned_operations! {
511 // A bunch of methods for signed nonzero types only.
512 macro_rules! nonzero_signed_operations {
513 ( $( $Ty: ident($Int: ty) -> $Uty: ident($Uint: ty); )+ ) => {
516 /// Computes the absolute value of self.
517 #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
518 /// for documentation on overflow behaviour.
523 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
524 /// # fn main() { test().unwrap(); }
525 /// # fn test() -> Option<()> {
526 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
527 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
529 /// assert_eq!(pos, pos.abs());
530 /// assert_eq!(pos, neg.abs());
534 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
535 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
536 #[must_use = "this returns the result of the operation, \
537 without modifying the original"]
539 pub const fn abs(self) -> $Ty {
540 // SAFETY: This cannot overflow to zero.
541 unsafe { $Ty::new_unchecked(self.get().abs()) }
544 /// Checked absolute value.
545 /// Checks for overflow and returns [`None`] if
546 #[doc = concat!("`self == ", stringify!($Int), "::MIN`.")]
547 /// The result cannot be zero.
552 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
553 /// # fn main() { test().unwrap(); }
554 /// # fn test() -> Option<()> {
555 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
556 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
557 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
558 stringify!($Int), "::MIN)?;")]
560 /// assert_eq!(Some(pos), neg.checked_abs());
561 /// assert_eq!(None, min.checked_abs());
565 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
566 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
567 #[must_use = "this returns the result of the operation, \
568 without modifying the original"]
570 pub const fn checked_abs(self) -> Option<$Ty> {
571 if let Some(nz) = self.get().checked_abs() {
572 // SAFETY: absolute value of nonzero cannot yield zero values.
573 Some(unsafe { $Ty::new_unchecked(nz) })
579 /// Computes the absolute value of self,
580 /// with overflow information, see
581 #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
586 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
587 /// # fn main() { test().unwrap(); }
588 /// # fn test() -> Option<()> {
589 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
590 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
591 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
592 stringify!($Int), "::MIN)?;")]
594 /// assert_eq!((pos, false), pos.overflowing_abs());
595 /// assert_eq!((pos, false), neg.overflowing_abs());
596 /// assert_eq!((min, true), min.overflowing_abs());
600 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
601 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
602 #[must_use = "this returns the result of the operation, \
603 without modifying the original"]
605 pub const fn overflowing_abs(self) -> ($Ty, bool) {
606 let (nz, flag) = self.get().overflowing_abs();
608 // SAFETY: absolute value of nonzero cannot yield zero values.
609 unsafe { $Ty::new_unchecked(nz) },
614 /// Saturating absolute value, see
615 #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
620 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
621 /// # fn main() { test().unwrap(); }
622 /// # fn test() -> Option<()> {
623 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
624 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
625 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
626 stringify!($Int), "::MIN)?;")]
627 #[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
628 stringify!($Int), "::MIN + 1)?;")]
629 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
630 stringify!($Int), "::MAX)?;")]
632 /// assert_eq!(pos, pos.saturating_abs());
633 /// assert_eq!(pos, neg.saturating_abs());
634 /// assert_eq!(max, min.saturating_abs());
635 /// assert_eq!(max, min_plus.saturating_abs());
639 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
640 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
641 #[must_use = "this returns the result of the operation, \
642 without modifying the original"]
644 pub const fn saturating_abs(self) -> $Ty {
645 // SAFETY: absolute value of nonzero cannot yield zero values.
646 unsafe { $Ty::new_unchecked(self.get().saturating_abs()) }
649 /// Wrapping absolute value, see
650 #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
655 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
656 /// # fn main() { test().unwrap(); }
657 /// # fn test() -> Option<()> {
658 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
659 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
660 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
661 stringify!($Int), "::MIN)?;")]
662 #[doc = concat!("# let max = ", stringify!($Ty), "::new(",
663 stringify!($Int), "::MAX)?;")]
665 /// assert_eq!(pos, pos.wrapping_abs());
666 /// assert_eq!(pos, neg.wrapping_abs());
667 /// assert_eq!(min, min.wrapping_abs());
668 /// # // FIXME: add once Neg is implemented?
669 /// # // assert_eq!(max, (-max).wrapping_abs());
673 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
674 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
675 #[must_use = "this returns the result of the operation, \
676 without modifying the original"]
678 pub const fn wrapping_abs(self) -> $Ty {
679 // SAFETY: absolute value of nonzero cannot yield zero values.
680 unsafe { $Ty::new_unchecked(self.get().wrapping_abs()) }
683 /// Computes the absolute value of self
684 /// without any wrapping or panicking.
689 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
690 #[doc = concat!("# use std::num::", stringify!($Uty), ";")]
692 /// # fn main() { test().unwrap(); }
693 /// # fn test() -> Option<()> {
694 #[doc = concat!("let u_pos = ", stringify!($Uty), "::new(1)?;")]
695 #[doc = concat!("let i_pos = ", stringify!($Ty), "::new(1)?;")]
696 #[doc = concat!("let i_neg = ", stringify!($Ty), "::new(-1)?;")]
697 #[doc = concat!("let i_min = ", stringify!($Ty), "::new(",
698 stringify!($Int), "::MIN)?;")]
699 #[doc = concat!("let u_max = ", stringify!($Uty), "::new(",
700 stringify!($Uint), "::MAX / 2 + 1)?;")]
702 /// assert_eq!(u_pos, i_pos.unsigned_abs());
703 /// assert_eq!(u_pos, i_neg.unsigned_abs());
704 /// assert_eq!(u_max, i_min.unsigned_abs());
708 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
709 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
710 #[must_use = "this returns the result of the operation, \
711 without modifying the original"]
713 pub const fn unsigned_abs(self) -> $Uty {
714 // SAFETY: absolute value of nonzero cannot yield zero values.
715 unsafe { $Uty::new_unchecked(self.get().unsigned_abs()) }
718 /// Returns `true` if `self` is negative and `false` if the
719 /// number is positive.
724 /// #![feature(nonzero_negation_ops)]
726 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
727 /// # fn main() { test().unwrap(); }
728 /// # fn test() -> Option<()> {
729 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
730 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
732 /// assert!(neg_five.is_negative());
733 /// assert!(!pos_five.is_negative());
739 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
740 pub const fn is_negative(self) -> bool {
741 self.get().is_negative()
744 /// Checked negation. Computes `-self`, returning `None` if `self == i32::MIN`.
749 /// #![feature(nonzero_negation_ops)]
751 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
752 /// # fn main() { test().unwrap(); }
753 /// # fn test() -> Option<()> {
754 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
755 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
756 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
757 stringify!($Int), "::MIN)?;")]
759 /// assert_eq!(pos_five.checked_neg(), Some(neg_five));
760 /// assert_eq!(min.checked_neg(), None);
765 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
766 pub const fn checked_neg(self) -> Option<$Ty> {
767 if let Some(result) = self.get().checked_neg() {
768 // SAFETY: negation of nonzero cannot yield zero values.
769 return Some(unsafe { $Ty::new_unchecked(result) });
774 /// Negates self, overflowing if this is equal to the minimum value.
776 #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")]
777 /// for documentation on overflow behaviour.
782 /// #![feature(nonzero_negation_ops)]
784 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
785 /// # fn main() { test().unwrap(); }
786 /// # fn test() -> Option<()> {
787 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
788 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
789 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
790 stringify!($Int), "::MIN)?;")]
792 /// assert_eq!(pos_five.overflowing_neg(), (neg_five, false));
793 /// assert_eq!(min.overflowing_neg(), (min, true));
798 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
799 pub const fn overflowing_neg(self) -> ($Ty, bool) {
800 let (result, overflow) = self.get().overflowing_neg();
801 // SAFETY: negation of nonzero cannot yield zero values.
802 ((unsafe { $Ty::new_unchecked(result) }), overflow)
805 /// Saturating negation. Computes `-self`, returning `MAX` if
806 /// `self == i32::MIN` instead of overflowing.
811 /// #![feature(nonzero_negation_ops)]
813 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
814 /// # fn main() { test().unwrap(); }
815 /// # fn test() -> Option<()> {
816 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
817 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
818 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
819 stringify!($Int), "::MIN)?;")]
820 #[doc = concat!("let min_plus_one = ", stringify!($Ty), "::new(",
821 stringify!($Int), "::MIN + 1)?;")]
822 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
823 stringify!($Int), "::MAX)?;")]
825 /// assert_eq!(pos_five.saturating_neg(), neg_five);
826 /// assert_eq!(min.saturating_neg(), max);
827 /// assert_eq!(max.saturating_neg(), min_plus_one);
832 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
833 pub const fn saturating_neg(self) -> $Ty {
834 if let Some(result) = self.checked_neg() {
840 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
843 #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")]
844 /// for documentation on overflow behaviour.
849 /// #![feature(nonzero_negation_ops)]
851 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
852 /// # fn main() { test().unwrap(); }
853 /// # fn test() -> Option<()> {
854 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
855 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
856 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
857 stringify!($Int), "::MIN)?;")]
859 /// assert_eq!(pos_five.wrapping_neg(), neg_five);
860 /// assert_eq!(min.wrapping_neg(), min);
865 #[unstable(feature = "nonzero_negation_ops", issue = "102443")]
866 pub const fn wrapping_neg(self) -> $Ty {
867 let result = self.get().wrapping_neg();
868 // SAFETY: negation of nonzero cannot yield zero values.
869 unsafe { $Ty::new_unchecked(result) }
876 nonzero_signed_operations! {
877 NonZeroI8(i8) -> NonZeroU8(u8);
878 NonZeroI16(i16) -> NonZeroU16(u16);
879 NonZeroI32(i32) -> NonZeroU32(u32);
880 NonZeroI64(i64) -> NonZeroU64(u64);
881 NonZeroI128(i128) -> NonZeroU128(u128);
882 NonZeroIsize(isize) -> NonZeroUsize(usize);
885 // A bunch of methods for both signed and unsigned nonzero types.
886 macro_rules! nonzero_unsigned_signed_operations {
887 ( $( $signedness:ident $Ty: ident($Int: ty); )+ ) => {
890 /// Multiplies two non-zero integers together.
891 /// Checks for overflow and returns [`None`] on overflow.
892 /// As a consequence, the result cannot wrap to zero.
897 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
898 /// # fn main() { test().unwrap(); }
899 /// # fn test() -> Option<()> {
900 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
901 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
902 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
903 stringify!($Int), "::MAX)?;")]
905 /// assert_eq!(Some(four), two.checked_mul(two));
906 /// assert_eq!(None, max.checked_mul(two));
910 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
911 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
912 #[must_use = "this returns the result of the operation, \
913 without modifying the original"]
915 pub const fn checked_mul(self, other: $Ty) -> Option<$Ty> {
916 if let Some(result) = self.get().checked_mul(other.get()) {
917 // SAFETY: checked_mul returns None on overflow
918 // and `other` is also non-null
919 // so the result cannot be zero.
920 Some(unsafe { $Ty::new_unchecked(result) })
926 /// Multiplies two non-zero integers together.
927 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
932 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
933 /// # fn main() { test().unwrap(); }
934 /// # fn test() -> Option<()> {
935 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
936 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
937 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
938 stringify!($Int), "::MAX)?;")]
940 /// assert_eq!(four, two.saturating_mul(two));
941 /// assert_eq!(max, four.saturating_mul(max));
945 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
946 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
947 #[must_use = "this returns the result of the operation, \
948 without modifying the original"]
950 pub const fn saturating_mul(self, other: $Ty) -> $Ty {
951 // SAFETY: saturating_mul returns u*::MAX on overflow
952 // and `other` is also non-null
953 // so the result cannot be zero.
954 unsafe { $Ty::new_unchecked(self.get().saturating_mul(other.get())) }
957 /// Multiplies two non-zero integers together,
958 /// assuming overflow cannot occur.
959 /// Overflow is unchecked, and it is undefined behaviour to overflow
960 /// *even if the result would wrap to a non-zero value*.
961 /// The behaviour is undefined as soon as
962 #[doc = sign_dependent_expr!{
965 concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
966 "or `self * rhs < ", stringify!($Int), "::MIN`.")
969 concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
976 /// #![feature(nonzero_ops)]
978 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
979 /// # fn main() { test().unwrap(); }
980 /// # fn test() -> Option<()> {
981 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
982 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
984 /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
988 #[unstable(feature = "nonzero_ops", issue = "84186")]
989 #[must_use = "this returns the result of the operation, \
990 without modifying the original"]
992 pub const unsafe fn unchecked_mul(self, other: $Ty) -> $Ty {
993 // SAFETY: The caller ensures there is no overflow.
994 unsafe { $Ty::new_unchecked(self.get().unchecked_mul(other.get())) }
997 /// Raises non-zero value to an integer power.
998 /// Checks for overflow and returns [`None`] on overflow.
999 /// As a consequence, the result cannot wrap to zero.
1004 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1005 /// # fn main() { test().unwrap(); }
1006 /// # fn test() -> Option<()> {
1007 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
1008 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
1009 #[doc = concat!("let half_max = ", stringify!($Ty), "::new(",
1010 stringify!($Int), "::MAX / 2)?;")]
1012 /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
1013 /// assert_eq!(None, half_max.checked_pow(3));
1017 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1018 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1019 #[must_use = "this returns the result of the operation, \
1020 without modifying the original"]
1022 pub const fn checked_pow(self, other: u32) -> Option<$Ty> {
1023 if let Some(result) = self.get().checked_pow(other) {
1024 // SAFETY: checked_pow returns None on overflow
1025 // so the result cannot be zero.
1026 Some(unsafe { $Ty::new_unchecked(result) })
1032 /// Raise non-zero value to an integer power.
1033 #[doc = sign_dependent_expr!{
1036 concat!("Return [`", stringify!($Int), "::MIN`] ",
1037 "or [`", stringify!($Int), "::MAX`] on overflow.")
1040 concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")
1047 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1048 /// # fn main() { test().unwrap(); }
1049 /// # fn test() -> Option<()> {
1050 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
1051 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
1052 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
1053 stringify!($Int), "::MAX)?;")]
1055 /// assert_eq!(twenty_seven, three.saturating_pow(3));
1056 /// assert_eq!(max, max.saturating_pow(3));
1060 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1061 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1062 #[must_use = "this returns the result of the operation, \
1063 without modifying the original"]
1065 pub const fn saturating_pow(self, other: u32) -> $Ty {
1066 // SAFETY: saturating_pow returns u*::MAX on overflow
1067 // so the result cannot be zero.
1068 unsafe { $Ty::new_unchecked(self.get().saturating_pow(other)) }
1075 // Use this when the generated code should differ between signed and unsigned types.
1076 macro_rules! sign_dependent_expr {
1077 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1080 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1085 nonzero_unsigned_signed_operations! {
1086 unsigned NonZeroU8(u8);
1087 unsigned NonZeroU16(u16);
1088 unsigned NonZeroU32(u32);
1089 unsigned NonZeroU64(u64);
1090 unsigned NonZeroU128(u128);
1091 unsigned NonZeroUsize(usize);
1092 signed NonZeroI8(i8);
1093 signed NonZeroI16(i16);
1094 signed NonZeroI32(i32);
1095 signed NonZeroI64(i64);
1096 signed NonZeroI128(i128);
1097 signed NonZeroIsize(isize);
1100 macro_rules! nonzero_unsigned_is_power_of_two {
1101 ( $( $Ty: ident )+ ) => {
1105 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
1107 /// On many architectures, this function can perform better than `is_power_of_two()`
1108 /// on the underlying integer type, as special handling of zero can be avoided.
1115 #[doc = concat!("let eight = std::num::", stringify!($Ty), "::new(8).unwrap();")]
1116 /// assert!(eight.is_power_of_two());
1117 #[doc = concat!("let ten = std::num::", stringify!($Ty), "::new(10).unwrap();")]
1118 /// assert!(!ten.is_power_of_two());
1121 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1122 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1124 pub const fn is_power_of_two(self) -> bool {
1125 // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
1126 // On the basic x86-64 target, this saves 3 instructions for the zero check.
1127 // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
1128 // compared to the `POPCNT` implementation on the underlying integer type.
1130 intrinsics::ctpop(self.get()) < 2
1138 nonzero_unsigned_is_power_of_two! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize }
1140 macro_rules! nonzero_min_max_unsigned {
1141 ( $( $Ty: ident($Int: ident); )+ ) => {
1144 /// The smallest value that can be represented by this non-zero
1145 /// integer type, 1.
1150 /// #![feature(nonzero_min_max)]
1152 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1153 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), 1", stringify!($Int), ");")]
1155 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1156 pub const MIN: Self = Self::new(1).unwrap();
1158 /// The largest value that can be represented by this non-zero
1160 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1165 /// #![feature(nonzero_min_max)]
1167 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1168 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1170 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1171 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1177 macro_rules! nonzero_min_max_signed {
1178 ( $( $Ty: ident($Int: ident); )+ ) => {
1181 /// The smallest value that can be represented by this non-zero
1183 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1185 /// Note: While most integer types are defined for every whole
1186 /// number between `MIN` and `MAX`, signed non-zero integers are
1187 /// a special case. They have a "gap" at 0.
1192 /// #![feature(nonzero_min_max)]
1194 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1195 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), ", stringify!($Int), "::MIN);")]
1197 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1198 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1200 /// The largest value that can be represented by this non-zero
1202 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1204 /// Note: While most integer types are defined for every whole
1205 /// number between `MIN` and `MAX`, signed non-zero integers are
1206 /// a special case. They have a "gap" at 0.
1211 /// #![feature(nonzero_min_max)]
1213 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1214 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1216 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1217 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1223 nonzero_min_max_unsigned! {
1229 NonZeroUsize(usize);
1232 nonzero_min_max_signed! {
1238 NonZeroIsize(isize);
1241 macro_rules! nonzero_bits {
1242 ( $( $Ty: ident($Int: ty); )+ ) => {
1245 /// The size of this non-zero integer type in bits.
1247 #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
1252 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1254 #[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
1256 #[stable(feature = "nonzero_bits", since = "CURRENT_RUSTC_VERSION")]
1257 pub const BITS: u32 = <$Int>::BITS;
1274 NonZeroUsize(usize);
1275 NonZeroIsize(isize);