1//! Definitions of integer that is known not to equal zero.
2
3use crate::cmp::Ordering;
4use crate::fmt;
5use crate::hash::{Hash, Hasher};
6#[cfg(bootstrap)]
7use crate::marker::StructuralEq;
8use crate::marker::StructuralPartialEq;
9use crate::ops::{BitOr, BitOrAssign, Div, Neg, Rem};
10use crate::str::FromStr;
11
12use super::from_str_radix;
13use super::{IntErrorKind, ParseIntError};
14use crate::intrinsics;
15
16mod private {
17 #[unstable(
18 feature = "nonzero_internals",
19 reason = "implementation detail which may disappear or be replaced at any time",
20 issue = "none"
21 )]
22 #[const_trait]
23 pub trait Sealed {}
24}
25
26/// A marker trait for primitive types which can be zero.
27///
28/// This is an implementation detail for [`NonZero<T>`](NonZero) which may disappear or be replaced at any time.
29#[unstable(
30 feature = "nonzero_internals",
31 reason = "implementation detail which may disappear or be replaced at any time",
32 issue = "none"
33)]
34#[const_trait]
35pub trait ZeroablePrimitive: Sized + Copy + private::Sealed {}
36
37macro_rules! impl_zeroable_primitive {
38 ($NonZero:ident ( $primitive:ty )) => {
39 #[unstable(
40 feature = "nonzero_internals",
41 reason = "implementation detail which may disappear or be replaced at any time",
42 issue = "none"
43 )]
44 impl const private::Sealed for $primitive {}
45
46 #[unstable(
47 feature = "nonzero_internals",
48 reason = "implementation detail which may disappear or be replaced at any time",
49 issue = "none"
50 )]
51 impl const ZeroablePrimitive for $primitive {}
52 };
53}
54
55impl_zeroable_primitive!(NonZeroU8(u8));
56impl_zeroable_primitive!(NonZeroU16(u16));
57impl_zeroable_primitive!(NonZeroU32(u32));
58impl_zeroable_primitive!(NonZeroU64(u64));
59impl_zeroable_primitive!(NonZeroU128(u128));
60impl_zeroable_primitive!(NonZeroUsize(usize));
61impl_zeroable_primitive!(NonZeroI8(i8));
62impl_zeroable_primitive!(NonZeroI16(i16));
63impl_zeroable_primitive!(NonZeroI32(i32));
64impl_zeroable_primitive!(NonZeroI64(i64));
65impl_zeroable_primitive!(NonZeroI128(i128));
66impl_zeroable_primitive!(NonZeroIsize(isize));
67
68/// A value that is known not to equal zero.
69///
70/// This enables some memory layout optimization.
71/// For example, `Option<NonZero<u32>>` is the same size as `u32`:
72///
73/// ```
74/// #![feature(generic_nonzero)]
75/// use core::mem::size_of;
76///
77/// assert_eq!(size_of::<Option<core::num::NonZero<u32>>>(), size_of::<u32>());
78/// ```
79#[unstable(feature = "generic_nonzero", issue = "120257")]
80#[repr(transparent)]
81#[rustc_layout_scalar_valid_range_start(1)]
82#[rustc_nonnull_optimization_guaranteed]
83#[rustc_diagnostic_item = "NonZero"]
84pub struct NonZero<T: ZeroablePrimitive>(T);
85
86macro_rules! impl_nonzero_fmt {
87 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
88 $(
89 #[$stability]
90 impl fmt::$Trait for $Ty {
91 #[inline]
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 self.get().fmt(f)
94 }
95 }
96 )+
97 }
98}
99
100macro_rules! nonzero_integer {
101 (
102 #[$stability:meta]
103 #[$const_new_unchecked_stability:meta]
104 Self = $Ty:ident,
105 Primitive = $signedness:ident $Int:ident,
106 $(UnsignedNonZero = $UnsignedNonZero:ident,)?
107 UnsignedPrimitive = $UnsignedPrimitive:ty,
108
109 // Used in doc comments.
110 leading_zeros_test = $leading_zeros_test:expr,
111 ) => {
112 /// An integer that is known not to equal zero.
113 ///
114 /// This enables some memory layout optimization.
115 #[doc = concat!("For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:")]
116 ///
117 /// ```rust
118 /// use std::mem::size_of;
119 #[doc = concat!("assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int), ">());")]
120 /// ```
121 ///
122 /// # Layout
123 ///
124 #[doc = concat!("`", stringify!($Ty), "` is guaranteed to have the same layout and bit validity as `", stringify!($Int), "`")]
125 /// with the exception that `0` is not a valid instance.
126 #[doc = concat!("`Option<", stringify!($Ty), ">` is guaranteed to be compatible with `", stringify!($Int), "`,")]
127 /// including in FFI.
128 ///
129 /// Thanks to the [null pointer optimization],
130 #[doc = concat!("`", stringify!($Ty), "` and `Option<", stringify!($Ty), ">`")]
131 /// are guaranteed to have the same size and alignment:
132 ///
133 /// ```
134 /// # use std::mem::{size_of, align_of};
135 #[doc = concat!("use std::num::", stringify!($Ty), ";")]
136 ///
137 #[doc = concat!("assert_eq!(size_of::<", stringify!($Ty), ">(), size_of::<Option<", stringify!($Ty), ">>());")]
138 #[doc = concat!("assert_eq!(align_of::<", stringify!($Ty), ">(), align_of::<Option<", stringify!($Ty), ">>());")]
139 /// ```
140 ///
141 /// [null pointer optimization]: crate::option#representation
142 #[$stability]
143 pub type $Ty = NonZero<$Int>;
144
145 impl $Ty {
146 /// Creates a non-zero without checking whether the value is non-zero.
147 /// This results in undefined behaviour if the value is zero.
148 ///
149 /// # Safety
150 ///
151 /// The value must not be zero.
152 #[$stability]
153 #[$const_new_unchecked_stability]
154 #[must_use]
155 #[inline]
156 pub const unsafe fn new_unchecked(n: $Int) -> Self {
157 crate::panic::debug_assert_nounwind!(
158 n != 0,
159 concat!(stringify!($Ty), "::new_unchecked requires a non-zero argument")
160 );
161 // SAFETY: this is guaranteed to be safe by the caller.
162 unsafe {
163 Self(n)
164 }
165 }
166
167 /// Creates a non-zero if the given value is not zero.
168 #[$stability]
169 #[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
170 #[must_use]
171 #[inline]
172 pub const fn new(n: $Int) -> Option<Self> {
173 if n != 0 {
174 // SAFETY: we just checked that there's no `0`
175 Some(unsafe { Self(n) })
176 } else {
177 None
178 }
179 }
180
181 /// Converts a primitive mutable reference to a non-zero mutable reference
182 /// without checking whether the referenced value is non-zero.
183 /// This results in undefined behavior if `*n` is zero.
184 ///
185 /// # Safety
186 /// The referenced value must not be currently zero.
187 #[unstable(feature = "nonzero_from_mut", issue = "106290")]
188 #[must_use]
189 #[inline]
190 pub unsafe fn from_mut_unchecked(n: &mut $Int) -> &mut Self {
191 // SAFETY: Self is repr(transparent), and the value is assumed to be non-zero.
192 unsafe {
193 let n_alias = &mut *n;
194 core::intrinsics::assert_unsafe_precondition!(
195 concat!(stringify!($Ty), "::from_mut_unchecked requires the argument to dereference as non-zero"),
196 (n_alias: &mut $Int) => *n_alias != 0
197 );
198 &mut *(n as *mut $Int as *mut Self)
199 }
200 }
201
202 /// Converts a primitive mutable reference to a non-zero mutable reference
203 /// if the referenced integer is not zero.
204 #[unstable(feature = "nonzero_from_mut", issue = "106290")]
205 #[must_use]
206 #[inline]
207 pub fn from_mut(n: &mut $Int) -> Option<&mut Self> {
208 // SAFETY: Self is repr(transparent), and the value is non-zero.
209 // As long as the returned reference is alive,
210 // the user cannot `*n = 0` directly.
211 (*n != 0).then(|| unsafe { &mut *(n as *mut $Int as *mut Self) })
212 }
213
214 /// Returns the value as a primitive type.
215 #[$stability]
216 #[inline]
217 #[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
218 pub const fn get(self) -> $Int {
219 // FIXME: Remove this after LLVM supports `!range` metadata for function
220 // arguments https://github.com/llvm/llvm-project/issues/76628
221 //
222 // Rustc can set range metadata only if it loads `self` from
223 // memory somewhere. If the value of `self` was from by-value argument
224 // of some not-inlined function, LLVM don't have range metadata
225 // to understand that the value cannot be zero.
226
227 // SAFETY: It is an invariant of this type.
228 unsafe {
229 intrinsics::assume(self.0 != 0);
230 }
231 self.0
232 }
233
234 /// The size of this non-zero integer type in bits.
235 ///
236 #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
237 ///
238 /// # Examples
239 ///
240 /// ```
241 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
242 ///
243 #[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
244 /// ```
245 #[stable(feature = "nonzero_bits", since = "1.67.0")]
246 pub const BITS: u32 = <$Int>::BITS;
247
248 /// Returns the number of leading zeros in the binary representation of `self`.
249 ///
250 /// On many architectures, this function can perform better than `leading_zeros()` on the underlying integer type, as special handling of zero can be avoided.
251 ///
252 /// # Examples
253 ///
254 /// Basic usage:
255 ///
256 /// ```
257 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(", $leading_zeros_test, ").unwrap();")]
258 ///
259 /// assert_eq!(n.leading_zeros(), 0);
260 /// ```
261 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
262 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
263 #[must_use = "this returns the result of the operation, \
264 without modifying the original"]
265 #[inline]
266 pub const fn leading_zeros(self) -> u32 {
267 // SAFETY: since `self` cannot be zero, it is safe to call `ctlz_nonzero`.
268 unsafe { intrinsics::ctlz_nonzero(self.get() as $UnsignedPrimitive) as u32 }
269 }
270
271 /// Returns the number of trailing zeros in the binary representation
272 /// of `self`.
273 ///
274 /// On many architectures, this function can perform better than `trailing_zeros()` on the underlying integer type, as special handling of zero can be avoided.
275 ///
276 /// # Examples
277 ///
278 /// Basic usage:
279 ///
280 /// ```
281 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(0b0101000).unwrap();")]
282 ///
283 /// assert_eq!(n.trailing_zeros(), 3);
284 /// ```
285 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
286 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
287 #[must_use = "this returns the result of the operation, \
288 without modifying the original"]
289 #[inline]
290 pub const fn trailing_zeros(self) -> u32 {
291 // SAFETY: since `self` cannot be zero, it is safe to call `cttz_nonzero`.
292 unsafe { intrinsics::cttz_nonzero(self.get() as $UnsignedPrimitive) as u32 }
293 }
294
295 /// Returns the number of ones in the binary representation of `self`.
296 ///
297 /// # Examples
298 ///
299 /// Basic usage:
300 ///
301 /// ```
302 /// #![feature(non_zero_count_ones)]
303 /// # fn main() { test().unwrap(); }
304 /// # fn test() -> Option<()> {
305 #[doc = concat!("# use std::num::{self, ", stringify!($Ty), "};")]
306 ///
307 /// let one = num::NonZeroU32::new(1)?;
308 /// let three = num::NonZeroU32::new(3)?;
309 #[doc = concat!("let a = ", stringify!($Ty), "::new(0b100_0000)?;")]
310 #[doc = concat!("let b = ", stringify!($Ty), "::new(0b100_0011)?;")]
311 ///
312 /// assert_eq!(a.count_ones(), one);
313 /// assert_eq!(b.count_ones(), three);
314 /// # Some(())
315 /// # }
316 /// ```
317 ///
318 #[unstable(feature = "non_zero_count_ones", issue = "120287")]
319 #[rustc_const_unstable(feature = "non_zero_count_ones", issue = "120287")]
320 #[doc(alias = "popcount")]
321 #[doc(alias = "popcnt")]
322 #[must_use = "this returns the result of the operation, \
323 without modifying the original"]
324 #[inline(always)]
325 pub const fn count_ones(self) -> NonZeroU32 {
326 // SAFETY:
327 // `self` is non-zero, which means it has at least one bit set, which means
328 // that the result of `count_ones` is non-zero.
329 unsafe { NonZeroU32::new_unchecked(self.get().count_ones()) }
330 }
331
332 nonzero_integer_signedness_dependent_methods! {
333 Self = $Ty,
334 Primitive = $signedness $Int,
335 $(UnsignedNonZero = $UnsignedNonZero,)?
336 UnsignedPrimitive = $UnsignedPrimitive,
337 }
338
339 /// Multiplies two non-zero integers together.
340 /// Checks for overflow and returns [`None`] on overflow.
341 /// As a consequence, the result cannot wrap to zero.
342 ///
343 /// # Examples
344 ///
345 /// ```
346 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
347 /// # fn main() { test().unwrap(); }
348 /// # fn test() -> Option<()> {
349 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
350 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
351 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
352 stringify!($Int), "::MAX)?;")]
353 ///
354 /// assert_eq!(Some(four), two.checked_mul(two));
355 /// assert_eq!(None, max.checked_mul(two));
356 /// # Some(())
357 /// # }
358 /// ```
359 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
360 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
361 #[must_use = "this returns the result of the operation, \
362 without modifying the original"]
363 #[inline]
364 pub const fn checked_mul(self, other: Self) -> Option<Self> {
365 if let Some(result) = self.get().checked_mul(other.get()) {
366 // SAFETY:
367 // - `checked_mul` returns `None` on overflow
368 // - `self` and `other` are non-zero
369 // - the only way to get zero from a multiplication without overflow is for one
370 // of the sides to be zero
371 //
372 // So the result cannot be zero.
373 Some(unsafe { Self::new_unchecked(result) })
374 } else {
375 None
376 }
377 }
378
379 /// Multiplies two non-zero integers together.
380 #[doc = concat!("Return [`", stringify!($Ty), "::MAX`] on overflow.")]
381 ///
382 /// # Examples
383 ///
384 /// ```
385 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
386 /// # fn main() { test().unwrap(); }
387 /// # fn test() -> Option<()> {
388 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
389 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
390 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
391 stringify!($Int), "::MAX)?;")]
392 ///
393 /// assert_eq!(four, two.saturating_mul(two));
394 /// assert_eq!(max, four.saturating_mul(max));
395 /// # Some(())
396 /// # }
397 /// ```
398 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
399 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
400 #[must_use = "this returns the result of the operation, \
401 without modifying the original"]
402 #[inline]
403 pub const fn saturating_mul(self, other: Self) -> Self {
404 // SAFETY:
405 // - `saturating_mul` returns `u*::MAX`/`i*::MAX`/`i*::MIN` on overflow/underflow,
406 // all of which are non-zero
407 // - `self` and `other` are non-zero
408 // - the only way to get zero from a multiplication without overflow is for one
409 // of the sides to be zero
410 //
411 // So the result cannot be zero.
412 unsafe { Self::new_unchecked(self.get().saturating_mul(other.get())) }
413 }
414
415 /// Multiplies two non-zero integers together,
416 /// assuming overflow cannot occur.
417 /// Overflow is unchecked, and it is undefined behaviour to overflow
418 /// *even if the result would wrap to a non-zero value*.
419 /// The behaviour is undefined as soon as
420 #[doc = sign_dependent_expr!{
421 $signedness ?
422 if signed {
423 concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
424 "or `self * rhs < ", stringify!($Int), "::MIN`.")
425 }
426 if unsigned {
427 concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
428 }
429 }]
430 ///
431 /// # Examples
432 ///
433 /// ```
434 /// #![feature(nonzero_ops)]
435 ///
436 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
437 /// # fn main() { test().unwrap(); }
438 /// # fn test() -> Option<()> {
439 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
440 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
441 ///
442 /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
443 /// # Some(())
444 /// # }
445 /// ```
446 #[unstable(feature = "nonzero_ops", issue = "84186")]
447 #[must_use = "this returns the result of the operation, \
448 without modifying the original"]
449 #[inline]
450 pub const unsafe fn unchecked_mul(self, other: Self) -> Self {
451 // SAFETY: The caller ensures there is no overflow.
452 unsafe { Self::new_unchecked(self.get().unchecked_mul(other.get())) }
453 }
454
455 /// Raises non-zero value to an integer power.
456 /// Checks for overflow and returns [`None`] on overflow.
457 /// As a consequence, the result cannot wrap to zero.
458 ///
459 /// # Examples
460 ///
461 /// ```
462 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
463 /// # fn main() { test().unwrap(); }
464 /// # fn test() -> Option<()> {
465 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
466 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
467 #[doc = concat!("let half_max = ", stringify!($Ty), "::new(",
468 stringify!($Int), "::MAX / 2)?;")]
469 ///
470 /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
471 /// assert_eq!(None, half_max.checked_pow(3));
472 /// # Some(())
473 /// # }
474 /// ```
475 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
476 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
477 #[must_use = "this returns the result of the operation, \
478 without modifying the original"]
479 #[inline]
480 pub const fn checked_pow(self, other: u32) -> Option<Self> {
481 if let Some(result) = self.get().checked_pow(other) {
482 // SAFETY:
483 // - `checked_pow` returns `None` on overflow/underflow
484 // - `self` is non-zero
485 // - the only way to get zero from an exponentiation without overflow is
486 // for base to be zero
487 //
488 // So the result cannot be zero.
489 Some(unsafe { Self::new_unchecked(result) })
490 } else {
491 None
492 }
493 }
494
495 /// Raise non-zero value to an integer power.
496 #[doc = sign_dependent_expr!{
497 $signedness ?
498 if signed {
499 concat!("Return [`", stringify!($Ty), "::MIN`] ",
500 "or [`", stringify!($Ty), "::MAX`] on overflow.")
501 }
502 if unsigned {
503 concat!("Return [`", stringify!($Ty), "::MAX`] on overflow.")
504 }
505 }]
506 ///
507 /// # Examples
508 ///
509 /// ```
510 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
511 /// # fn main() { test().unwrap(); }
512 /// # fn test() -> Option<()> {
513 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
514 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
515 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
516 stringify!($Int), "::MAX)?;")]
517 ///
518 /// assert_eq!(twenty_seven, three.saturating_pow(3));
519 /// assert_eq!(max, max.saturating_pow(3));
520 /// # Some(())
521 /// # }
522 /// ```
523 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
524 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
525 #[must_use = "this returns the result of the operation, \
526 without modifying the original"]
527 #[inline]
528 pub const fn saturating_pow(self, other: u32) -> Self {
529 // SAFETY:
530 // - `saturating_pow` returns `u*::MAX`/`i*::MAX`/`i*::MIN` on overflow/underflow,
531 // all of which are non-zero
532 // - `self` is non-zero
533 // - the only way to get zero from an exponentiation without overflow is
534 // for base to be zero
535 //
536 // So the result cannot be zero.
537 unsafe { Self::new_unchecked(self.get().saturating_pow(other)) }
538 }
539 }
540
541 #[$stability]
542 impl Clone for $Ty {
543 #[inline]
544 fn clone(&self) -> Self {
545 // SAFETY: The contained value is non-zero.
546 unsafe { Self(self.0) }
547 }
548 }
549
550 #[$stability]
551 impl Copy for $Ty {}
552
553 #[$stability]
554 impl PartialEq for $Ty {
555 #[inline]
556 fn eq(&self, other: &Self) -> bool {
557 self.0 == other.0
558 }
559
560 #[inline]
561 fn ne(&self, other: &Self) -> bool {
562 self.0 != other.0
563 }
564 }
565
566 #[unstable(feature = "structural_match", issue = "31434")]
567 impl StructuralPartialEq for $Ty {}
568
569 #[$stability]
570 impl Eq for $Ty {}
571
572 #[unstable(feature = "structural_match", issue = "31434")]
573 #[cfg(bootstrap)]
574 impl StructuralEq for $Ty {}
575
576 #[$stability]
577 impl PartialOrd for $Ty {
578 #[inline]
579 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
580 self.0.partial_cmp(&other.0)
581 }
582
583 #[inline]
584 fn lt(&self, other: &Self) -> bool {
585 self.0 < other.0
586 }
587
588 #[inline]
589 fn le(&self, other: &Self) -> bool {
590 self.0 <= other.0
591 }
592
593 #[inline]
594 fn gt(&self, other: &Self) -> bool {
595 self.0 > other.0
596 }
597
598 #[inline]
599 fn ge(&self, other: &Self) -> bool {
600 self.0 >= other.0
601 }
602 }
603
604 #[$stability]
605 impl Ord for $Ty {
606 #[inline]
607 fn cmp(&self, other: &Self) -> Ordering {
608 self.0.cmp(&other.0)
609 }
610
611 #[inline]
612 fn max(self, other: Self) -> Self {
613 // SAFETY: The maximum of two non-zero values is still non-zero.
614 unsafe { Self(self.0.max(other.0)) }
615 }
616
617 #[inline]
618 fn min(self, other: Self) -> Self {
619 // SAFETY: The minimum of two non-zero values is still non-zero.
620 unsafe { Self(self.0.min(other.0)) }
621 }
622
623 #[inline]
624 fn clamp(self, min: Self, max: Self) -> Self {
625 // SAFETY: A non-zero value clamped between two non-zero values is still non-zero.
626 unsafe { Self(self.0.clamp(min.0, max.0)) }
627 }
628 }
629
630 #[$stability]
631 impl Hash for $Ty {
632 #[inline]
633 fn hash<H>(&self, state: &mut H)
634 where
635 H: Hasher,
636 {
637 self.0.hash(state)
638 }
639 }
640
641 #[stable(feature = "from_nonzero", since = "1.31.0")]
642 impl From<$Ty> for $Int {
643 #[doc = concat!("Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`")]
644 #[inline]
645 fn from(nonzero: $Ty) -> Self {
646 // Call nonzero to keep information range information
647 // from get method.
648 nonzero.get()
649 }
650 }
651
652 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
653 impl BitOr for $Ty {
654 type Output = Self;
655
656 #[inline]
657 fn bitor(self, rhs: Self) -> Self::Output {
658 // SAFETY: since `self` and `rhs` are both nonzero, the
659 // result of the bitwise-or will be nonzero.
660 unsafe { Self::new_unchecked(self.get() | rhs.get()) }
661 }
662 }
663
664 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
665 impl BitOr<$Int> for $Ty {
666 type Output = Self;
667
668 #[inline]
669 fn bitor(self, rhs: $Int) -> Self::Output {
670 // SAFETY: since `self` is nonzero, the result of the
671 // bitwise-or will be nonzero regardless of the value of
672 // `rhs`.
673 unsafe { Self::new_unchecked(self.get() | rhs) }
674 }
675 }
676
677 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
678 impl BitOr<$Ty> for $Int {
679 type Output = $Ty;
680
681 #[inline]
682 fn bitor(self, rhs: $Ty) -> Self::Output {
683 // SAFETY: since `rhs` is nonzero, the result of the
684 // bitwise-or will be nonzero regardless of the value of
685 // `self`.
686 unsafe { $Ty::new_unchecked(self | rhs.get()) }
687 }
688 }
689
690 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
691 impl BitOrAssign for $Ty {
692 #[inline]
693 fn bitor_assign(&mut self, rhs: Self) {
694 *self = *self | rhs;
695 }
696 }
697
698 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
699 impl BitOrAssign<$Int> for $Ty {
700 #[inline]
701 fn bitor_assign(&mut self, rhs: $Int) {
702 *self = *self | rhs;
703 }
704 }
705
706 impl_nonzero_fmt! {
707 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
708 }
709
710 #[stable(feature = "nonzero_parse", since = "1.35.0")]
711 impl FromStr for $Ty {
712 type Err = ParseIntError;
713 fn from_str(src: &str) -> Result<Self, Self::Err> {
714 Self::new(from_str_radix(src, 10)?)
715 .ok_or(ParseIntError {
716 kind: IntErrorKind::Zero
717 })
718 }
719 }
720
721 nonzero_integer_signedness_dependent_impls!($Ty $signedness $Int);
722 };
723
724 (Self = $Ty:ident, Primitive = unsigned $Int:ident $(,)?) => {
725 nonzero_integer! {
726 #[stable(feature = "nonzero", since = "1.28.0")]
727 #[rustc_const_stable(feature = "nonzero", since = "1.28.0")]
728 Self = $Ty,
729 Primitive = unsigned $Int,
730 UnsignedPrimitive = $Int,
731 leading_zeros_test = concat!(stringify!($Int), "::MAX"),
732 }
733 };
734
735 (Self = $Ty:ident, Primitive = signed $Int:ident, $($rest:tt)*) => {
736 nonzero_integer! {
737 #[stable(feature = "signed_nonzero", since = "1.34.0")]
738 #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")]
739 Self = $Ty,
740 Primitive = signed $Int,
741 $($rest)*
742 leading_zeros_test = concat!("-1", stringify!($Int)),
743 }
744 };
745}
746
747macro_rules! nonzero_integer_signedness_dependent_impls {
748 // Impls for unsigned nonzero types only.
749 ($Ty:ident unsigned $Int:ty) => {
750 #[stable(feature = "nonzero_div", since = "1.51.0")]
751 impl Div<$Ty> for $Int {
752 type Output = $Int;
753
754 /// This operation rounds towards zero,
755 /// truncating any fractional part of the exact result, and cannot panic.
756 #[inline]
757 fn div(self, other: $Ty) -> $Int {
758 // SAFETY: div by zero is checked because `other` is a nonzero,
759 // and MIN/-1 is checked because `self` is an unsigned int.
760 unsafe { crate::intrinsics::unchecked_div(self, other.get()) }
761 }
762 }
763
764 #[stable(feature = "nonzero_div", since = "1.51.0")]
765 impl Rem<$Ty> for $Int {
766 type Output = $Int;
767
768 /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
769 #[inline]
770 fn rem(self, other: $Ty) -> $Int {
771 // SAFETY: rem by zero is checked because `other` is a nonzero,
772 // and MIN/-1 is checked because `self` is an unsigned int.
773 unsafe { crate::intrinsics::unchecked_rem(self, other.get()) }
774 }
775 }
776 };
777
778 // Impls for signed nonzero types only.
779 ($Ty:ident signed $Int:ty) => {
780 #[stable(feature = "signed_nonzero_neg", since = "1.71.0")]
781 impl Neg for $Ty {
782 type Output = Self;
783
784 #[inline]
785 fn neg(self) -> Self {
786 // SAFETY: negation of nonzero cannot yield zero values.
787 unsafe { Self::new_unchecked(self.get().neg()) }
788 }
789 }
790
791 forward_ref_unop! { impl Neg, neg for $Ty,
792 #[stable(feature = "signed_nonzero_neg", since = "1.71.0")] }
793 };
794}
795
796#[rustfmt::skip] // https://github.com/rust-lang/rustfmt/issues/5974
797macro_rules! nonzero_integer_signedness_dependent_methods {
798 // Associated items for unsigned nonzero types only.
799 (
800 Self = $Ty:ident,
801 Primitive = unsigned $Int:ident,
802 UnsignedPrimitive = $Uint:ty,
803 ) => {
804 /// The smallest value that can be represented by this non-zero
805 /// integer type, 1.
806 ///
807 /// # Examples
808 ///
809 /// ```
810 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
811 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), 1", stringify!($Int), ");")]
812 /// ```
813 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
814 pub const MIN: Self = Self::new(1).unwrap();
815
816 /// The largest value that can be represented by this non-zero
817 /// integer type,
818 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
819 ///
820 /// # Examples
821 ///
822 /// ```
823 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
824 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
825 /// ```
826 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
827 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
828
829 /// Adds an unsigned integer to a non-zero value.
830 /// Checks for overflow and returns [`None`] on overflow.
831 /// As a consequence, the result cannot wrap to zero.
832 ///
833 ///
834 /// # Examples
835 ///
836 /// ```
837 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
838 /// # fn main() { test().unwrap(); }
839 /// # fn test() -> Option<()> {
840 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
841 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
842 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
843 stringify!($Int), "::MAX)?;")]
844 ///
845 /// assert_eq!(Some(two), one.checked_add(1));
846 /// assert_eq!(None, max.checked_add(1));
847 /// # Some(())
848 /// # }
849 /// ```
850 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
851 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
852 #[must_use = "this returns the result of the operation, \
853 without modifying the original"]
854 #[inline]
855 pub const fn checked_add(self, other: $Int) -> Option<Self> {
856 if let Some(result) = self.get().checked_add(other) {
857 // SAFETY:
858 // - `checked_add` returns `None` on overflow
859 // - `self` is non-zero
860 // - the only way to get zero from an addition without overflow is for both
861 // sides to be zero
862 //
863 // So the result cannot be zero.
864 Some(unsafe { Self::new_unchecked(result) })
865 } else {
866 None
867 }
868 }
869
870 /// Adds an unsigned integer to a non-zero value.
871 #[doc = concat!("Return [`", stringify!($Ty), "::MAX`] on overflow.")]
872 ///
873 /// # Examples
874 ///
875 /// ```
876 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
877 /// # fn main() { test().unwrap(); }
878 /// # fn test() -> Option<()> {
879 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
880 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
881 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
882 stringify!($Int), "::MAX)?;")]
883 ///
884 /// assert_eq!(two, one.saturating_add(1));
885 /// assert_eq!(max, max.saturating_add(1));
886 /// # Some(())
887 /// # }
888 /// ```
889 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
890 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
891 #[must_use = "this returns the result of the operation, \
892 without modifying the original"]
893 #[inline]
894 pub const fn saturating_add(self, other: $Int) -> Self {
895 // SAFETY:
896 // - `saturating_add` returns `u*::MAX` on overflow, which is non-zero
897 // - `self` is non-zero
898 // - the only way to get zero from an addition without overflow is for both
899 // sides to be zero
900 //
901 // So the result cannot be zero.
902 unsafe { Self::new_unchecked(self.get().saturating_add(other)) }
903 }
904
905 /// Adds an unsigned integer to a non-zero value,
906 /// assuming overflow cannot occur.
907 /// Overflow is unchecked, and it is undefined behaviour to overflow
908 /// *even if the result would wrap to a non-zero value*.
909 /// The behaviour is undefined as soon as
910 #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
911 ///
912 /// # Examples
913 ///
914 /// ```
915 /// #![feature(nonzero_ops)]
916 ///
917 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
918 /// # fn main() { test().unwrap(); }
919 /// # fn test() -> Option<()> {
920 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
921 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
922 ///
923 /// assert_eq!(two, unsafe { one.unchecked_add(1) });
924 /// # Some(())
925 /// # }
926 /// ```
927 #[unstable(feature = "nonzero_ops", issue = "84186")]
928 #[must_use = "this returns the result of the operation, \
929 without modifying the original"]
930 #[inline]
931 pub const unsafe fn unchecked_add(self, other: $Int) -> Self {
932 // SAFETY: The caller ensures there is no overflow.
933 unsafe { Self::new_unchecked(self.get().unchecked_add(other)) }
934 }
935
936 /// Returns the smallest power of two greater than or equal to n.
937 /// Checks for overflow and returns [`None`]
938 /// if the next power of two is greater than the type’s maximum value.
939 /// As a consequence, the result cannot wrap to zero.
940 ///
941 /// # Examples
942 ///
943 /// ```
944 #[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 three = ", stringify!($Ty), "::new(3)?;")]
949 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
950 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
951 stringify!($Int), "::MAX)?;")]
952 ///
953 /// assert_eq!(Some(two), two.checked_next_power_of_two() );
954 /// assert_eq!(Some(four), three.checked_next_power_of_two() );
955 /// assert_eq!(None, max.checked_next_power_of_two() );
956 /// # Some(())
957 /// # }
958 /// ```
959 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
960 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
961 #[must_use = "this returns the result of the operation, \
962 without modifying the original"]
963 #[inline]
964 pub const fn checked_next_power_of_two(self) -> Option<Self> {
965 if let Some(nz) = self.get().checked_next_power_of_two() {
966 // SAFETY: The next power of two is positive
967 // and overflow is checked.
968 Some(unsafe { Self::new_unchecked(nz) })
969 } else {
970 None
971 }
972 }
973
974 /// Returns the base 2 logarithm of the number, rounded down.
975 ///
976 /// This is the same operation as
977 #[doc = concat!("[`", stringify!($Int), "::ilog2`],")]
978 /// except that it has no failure cases to worry about
979 /// since this value can never be zero.
980 ///
981 /// # Examples
982 ///
983 /// ```
984 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
985 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(7).unwrap().ilog2(), 2);")]
986 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(8).unwrap().ilog2(), 3);")]
987 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(9).unwrap().ilog2(), 3);")]
988 /// ```
989 #[stable(feature = "int_log", since = "1.67.0")]
990 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
991 #[must_use = "this returns the result of the operation, \
992 without modifying the original"]
993 #[inline]
994 pub const fn ilog2(self) -> u32 {
995 Self::BITS - 1 - self.leading_zeros()
996 }
997
998 /// Returns the base 10 logarithm of the number, rounded down.
999 ///
1000 /// This is the same operation as
1001 #[doc = concat!("[`", stringify!($Int), "::ilog10`],")]
1002 /// except that it has no failure cases to worry about
1003 /// since this value can never be zero.
1004 ///
1005 /// # Examples
1006 ///
1007 /// ```
1008 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1009 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(99).unwrap().ilog10(), 1);")]
1010 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(100).unwrap().ilog10(), 2);")]
1011 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(101).unwrap().ilog10(), 2);")]
1012 /// ```
1013 #[stable(feature = "int_log", since = "1.67.0")]
1014 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1015 #[must_use = "this returns the result of the operation, \
1016 without modifying the original"]
1017 #[inline]
1018 pub const fn ilog10(self) -> u32 {
1019 super::int_log10::$Int(self.get())
1020 }
1021
1022 /// Calculates the middle point of `self` and `rhs`.
1023 ///
1024 /// `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a
1025 /// sufficiently-large signed integral type. This implies that the result is
1026 /// always rounded towards negative infinity and that no overflow will ever occur.
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
1031 /// #![feature(num_midpoint)]
1032 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1033 ///
1034 /// # fn main() { test().unwrap(); }
1035 /// # fn test() -> Option<()> {
1036 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
1037 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
1038 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
1039 ///
1040 /// assert_eq!(one.midpoint(four), two);
1041 /// assert_eq!(four.midpoint(one), two);
1042 /// # Some(())
1043 /// # }
1044 /// ```
1045 #[unstable(feature = "num_midpoint", issue = "110840")]
1046 #[rustc_const_unstable(feature = "const_num_midpoint", issue = "110840")]
1047 #[rustc_allow_const_fn_unstable(const_num_midpoint)]
1048 #[must_use = "this returns the result of the operation, \
1049 without modifying the original"]
1050 #[inline]
1051 pub const fn midpoint(self, rhs: Self) -> Self {
1052 // SAFETY: The only way to get `0` with midpoint is to have two opposite or
1053 // near opposite numbers: (-5, 5), (0, 1), (0, 0) which is impossible because
1054 // of the unsignedness of this number and also because `Self` is guaranteed to
1055 // never being 0.
1056 unsafe { Self::new_unchecked(self.get().midpoint(rhs.get())) }
1057 }
1058
1059 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
1060 ///
1061 /// On many architectures, this function can perform better than `is_power_of_two()`
1062 /// on the underlying integer type, as special handling of zero can be avoided.
1063 ///
1064 /// # Examples
1065 ///
1066 /// Basic usage:
1067 ///
1068 /// ```
1069 #[doc = concat!("let eight = std::num::", stringify!($Ty), "::new(8).unwrap();")]
1070 /// assert!(eight.is_power_of_two());
1071 #[doc = concat!("let ten = std::num::", stringify!($Ty), "::new(10).unwrap();")]
1072 /// assert!(!ten.is_power_of_two());
1073 /// ```
1074 #[must_use]
1075 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1076 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1077 #[inline]
1078 pub const fn is_power_of_two(self) -> bool {
1079 // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
1080 // On the basic x86-64 target, this saves 3 instructions for the zero check.
1081 // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
1082 // compared to the `POPCNT` implementation on the underlying integer type.
1083
1084 intrinsics::ctpop(self.get()) < 2
1085 }
1086 };
1087
1088 // Associated items for signed nonzero types only.
1089 (
1090 Self = $Ty:ident,
1091 Primitive = signed $Int:ident,
1092 UnsignedNonZero = $Uty:ident,
1093 UnsignedPrimitive = $Uint:ty,
1094 ) => {
1095 /// The smallest value that can be represented by this non-zero
1096 /// integer type,
1097 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1098 ///
1099 /// Note: While most integer types are defined for every whole
1100 /// number between `MIN` and `MAX`, signed non-zero integers are
1101 /// a special case. They have a "gap" at 0.
1102 ///
1103 /// # Examples
1104 ///
1105 /// ```
1106 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1107 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), ", stringify!($Int), "::MIN);")]
1108 /// ```
1109 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1110 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1111
1112 /// The largest value that can be represented by this non-zero
1113 /// integer type,
1114 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1115 ///
1116 /// Note: While most integer types are defined for every whole
1117 /// number between `MIN` and `MAX`, signed non-zero integers are
1118 /// a special case. They have a "gap" at 0.
1119 ///
1120 /// # Examples
1121 ///
1122 /// ```
1123 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1124 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1125 /// ```
1126 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1127 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1128
1129 /// Computes the absolute value of self.
1130 #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
1131 /// for documentation on overflow behaviour.
1132 ///
1133 /// # Example
1134 ///
1135 /// ```
1136 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1137 /// # fn main() { test().unwrap(); }
1138 /// # fn test() -> Option<()> {
1139 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
1140 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
1141 ///
1142 /// assert_eq!(pos, pos.abs());
1143 /// assert_eq!(pos, neg.abs());
1144 /// # Some(())
1145 /// # }
1146 /// ```
1147 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1148 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1149 #[must_use = "this returns the result of the operation, \
1150 without modifying the original"]
1151 #[inline]
1152 pub const fn abs(self) -> Self {
1153 // SAFETY: This cannot overflow to zero.
1154 unsafe { Self::new_unchecked(self.get().abs()) }
1155 }
1156
1157 /// Checked absolute value.
1158 /// Checks for overflow and returns [`None`] if
1159 #[doc = concat!("`self == ", stringify!($Ty), "::MIN`.")]
1160 /// The result cannot be zero.
1161 ///
1162 /// # Example
1163 ///
1164 /// ```
1165 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1166 /// # fn main() { test().unwrap(); }
1167 /// # fn test() -> Option<()> {
1168 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
1169 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
1170 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
1171 stringify!($Int), "::MIN)?;")]
1172 ///
1173 /// assert_eq!(Some(pos), neg.checked_abs());
1174 /// assert_eq!(None, min.checked_abs());
1175 /// # Some(())
1176 /// # }
1177 /// ```
1178 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1179 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1180 #[must_use = "this returns the result of the operation, \
1181 without modifying the original"]
1182 #[inline]
1183 pub const fn checked_abs(self) -> Option<Self> {
1184 if let Some(nz) = self.get().checked_abs() {
1185 // SAFETY: absolute value of nonzero cannot yield zero values.
1186 Some(unsafe { Self::new_unchecked(nz) })
1187 } else {
1188 None
1189 }
1190 }
1191
1192 /// Computes the absolute value of self,
1193 /// with overflow information, see
1194 #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
1195 ///
1196 /// # Example
1197 ///
1198 /// ```
1199 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1200 /// # fn main() { test().unwrap(); }
1201 /// # fn test() -> Option<()> {
1202 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
1203 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
1204 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
1205 stringify!($Int), "::MIN)?;")]
1206 ///
1207 /// assert_eq!((pos, false), pos.overflowing_abs());
1208 /// assert_eq!((pos, false), neg.overflowing_abs());
1209 /// assert_eq!((min, true), min.overflowing_abs());
1210 /// # Some(())
1211 /// # }
1212 /// ```
1213 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1214 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1215 #[must_use = "this returns the result of the operation, \
1216 without modifying the original"]
1217 #[inline]
1218 pub const fn overflowing_abs(self) -> (Self, bool) {
1219 let (nz, flag) = self.get().overflowing_abs();
1220 (
1221 // SAFETY: absolute value of nonzero cannot yield zero values.
1222 unsafe { Self::new_unchecked(nz) },
1223 flag,
1224 )
1225 }
1226
1227 /// Saturating absolute value, see
1228 #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
1229 ///
1230 /// # Example
1231 ///
1232 /// ```
1233 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1234 /// # fn main() { test().unwrap(); }
1235 /// # fn test() -> Option<()> {
1236 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
1237 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
1238 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
1239 stringify!($Int), "::MIN)?;")]
1240 #[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
1241 stringify!($Int), "::MIN + 1)?;")]
1242 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
1243 stringify!($Int), "::MAX)?;")]
1244 ///
1245 /// assert_eq!(pos, pos.saturating_abs());
1246 /// assert_eq!(pos, neg.saturating_abs());
1247 /// assert_eq!(max, min.saturating_abs());
1248 /// assert_eq!(max, min_plus.saturating_abs());
1249 /// # Some(())
1250 /// # }
1251 /// ```
1252 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1253 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1254 #[must_use = "this returns the result of the operation, \
1255 without modifying the original"]
1256 #[inline]
1257 pub const fn saturating_abs(self) -> Self {
1258 // SAFETY: absolute value of nonzero cannot yield zero values.
1259 unsafe { Self::new_unchecked(self.get().saturating_abs()) }
1260 }
1261
1262 /// Wrapping absolute value, see
1263 #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
1264 ///
1265 /// # Example
1266 ///
1267 /// ```
1268 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1269 /// # fn main() { test().unwrap(); }
1270 /// # fn test() -> Option<()> {
1271 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
1272 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
1273 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
1274 stringify!($Int), "::MIN)?;")]
1275 #[doc = concat!("# let max = ", stringify!($Ty), "::new(",
1276 stringify!($Int), "::MAX)?;")]
1277 ///
1278 /// assert_eq!(pos, pos.wrapping_abs());
1279 /// assert_eq!(pos, neg.wrapping_abs());
1280 /// assert_eq!(min, min.wrapping_abs());
1281 /// assert_eq!(max, (-max).wrapping_abs());
1282 /// # Some(())
1283 /// # }
1284 /// ```
1285 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1286 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1287 #[must_use = "this returns the result of the operation, \
1288 without modifying the original"]
1289 #[inline]
1290 pub const fn wrapping_abs(self) -> Self {
1291 // SAFETY: absolute value of nonzero cannot yield zero values.
1292 unsafe { Self::new_unchecked(self.get().wrapping_abs()) }
1293 }
1294
1295 /// Computes the absolute value of self
1296 /// without any wrapping or panicking.
1297 ///
1298 /// # Example
1299 ///
1300 /// ```
1301 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1302 #[doc = concat!("# use std::num::", stringify!($Uty), ";")]
1303 ///
1304 /// # fn main() { test().unwrap(); }
1305 /// # fn test() -> Option<()> {
1306 #[doc = concat!("let u_pos = ", stringify!($Uty), "::new(1)?;")]
1307 #[doc = concat!("let i_pos = ", stringify!($Ty), "::new(1)?;")]
1308 #[doc = concat!("let i_neg = ", stringify!($Ty), "::new(-1)?;")]
1309 #[doc = concat!("let i_min = ", stringify!($Ty), "::new(",
1310 stringify!($Int), "::MIN)?;")]
1311 #[doc = concat!("let u_max = ", stringify!($Uty), "::new(",
1312 stringify!($Uint), "::MAX / 2 + 1)?;")]
1313 ///
1314 /// assert_eq!(u_pos, i_pos.unsigned_abs());
1315 /// assert_eq!(u_pos, i_neg.unsigned_abs());
1316 /// assert_eq!(u_max, i_min.unsigned_abs());
1317 /// # Some(())
1318 /// # }
1319 /// ```
1320 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1321 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1322 #[must_use = "this returns the result of the operation, \
1323 without modifying the original"]
1324 #[inline]
1325 pub const fn unsigned_abs(self) -> $Uty {
1326 // SAFETY: absolute value of nonzero cannot yield zero values.
1327 unsafe { $Uty::new_unchecked(self.get().unsigned_abs()) }
1328 }
1329
1330 /// Returns `true` if `self` is positive and `false` if the
1331 /// number is negative.
1332 ///
1333 /// # Example
1334 ///
1335 /// ```
1336 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1337 /// # fn main() { test().unwrap(); }
1338 /// # fn test() -> Option<()> {
1339 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
1340 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
1341 ///
1342 /// assert!(pos_five.is_positive());
1343 /// assert!(!neg_five.is_positive());
1344 /// # Some(())
1345 /// # }
1346 /// ```
1347 #[must_use]
1348 #[inline]
1349 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1350 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1351 pub const fn is_positive(self) -> bool {
1352 self.get().is_positive()
1353 }
1354
1355 /// Returns `true` if `self` is negative and `false` if the
1356 /// number is positive.
1357 ///
1358 /// # Example
1359 ///
1360 /// ```
1361 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1362 /// # fn main() { test().unwrap(); }
1363 /// # fn test() -> Option<()> {
1364 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
1365 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
1366 ///
1367 /// assert!(neg_five.is_negative());
1368 /// assert!(!pos_five.is_negative());
1369 /// # Some(())
1370 /// # }
1371 /// ```
1372 #[must_use]
1373 #[inline]
1374 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1375 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1376 pub const fn is_negative(self) -> bool {
1377 self.get().is_negative()
1378 }
1379
1380 /// Checked negation. Computes `-self`,
1381 #[doc = concat!("returning `None` if `self == ", stringify!($Ty), "::MIN`.")]
1382 ///
1383 /// # Example
1384 ///
1385 /// ```
1386 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1387 /// # fn main() { test().unwrap(); }
1388 /// # fn test() -> Option<()> {
1389 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
1390 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
1391 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
1392 stringify!($Int), "::MIN)?;")]
1393 ///
1394 /// assert_eq!(pos_five.checked_neg(), Some(neg_five));
1395 /// assert_eq!(min.checked_neg(), None);
1396 /// # Some(())
1397 /// # }
1398 /// ```
1399 #[inline]
1400 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1401 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1402 pub const fn checked_neg(self) -> Option<Self> {
1403 if let Some(result) = self.get().checked_neg() {
1404 // SAFETY: negation of nonzero cannot yield zero values.
1405 return Some(unsafe { Self::new_unchecked(result) });
1406 }
1407 None
1408 }
1409
1410 /// Negates self, overflowing if this is equal to the minimum value.
1411 ///
1412 #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")]
1413 /// for documentation on overflow behaviour.
1414 ///
1415 /// # Example
1416 ///
1417 /// ```
1418 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1419 /// # fn main() { test().unwrap(); }
1420 /// # fn test() -> Option<()> {
1421 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
1422 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
1423 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
1424 stringify!($Int), "::MIN)?;")]
1425 ///
1426 /// assert_eq!(pos_five.overflowing_neg(), (neg_five, false));
1427 /// assert_eq!(min.overflowing_neg(), (min, true));
1428 /// # Some(())
1429 /// # }
1430 /// ```
1431 #[inline]
1432 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1433 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1434 pub const fn overflowing_neg(self) -> (Self, bool) {
1435 let (result, overflow) = self.get().overflowing_neg();
1436 // SAFETY: negation of nonzero cannot yield zero values.
1437 ((unsafe { Self::new_unchecked(result) }), overflow)
1438 }
1439
1440 /// Saturating negation. Computes `-self`,
1441 #[doc = concat!("returning [`", stringify!($Ty), "::MAX`]")]
1442 #[doc = concat!("if `self == ", stringify!($Ty), "::MIN`")]
1443 /// instead of overflowing.
1444 ///
1445 /// # Example
1446 ///
1447 /// ```
1448 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1449 /// # fn main() { test().unwrap(); }
1450 /// # fn test() -> Option<()> {
1451 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
1452 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
1453 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
1454 stringify!($Int), "::MIN)?;")]
1455 #[doc = concat!("let min_plus_one = ", stringify!($Ty), "::new(",
1456 stringify!($Int), "::MIN + 1)?;")]
1457 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
1458 stringify!($Int), "::MAX)?;")]
1459 ///
1460 /// assert_eq!(pos_five.saturating_neg(), neg_five);
1461 /// assert_eq!(min.saturating_neg(), max);
1462 /// assert_eq!(max.saturating_neg(), min_plus_one);
1463 /// # Some(())
1464 /// # }
1465 /// ```
1466 #[inline]
1467 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1468 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1469 pub const fn saturating_neg(self) -> Self {
1470 if let Some(result) = self.checked_neg() {
1471 return result;
1472 }
1473 Self::MAX
1474 }
1475
1476 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1477 /// of the type.
1478 ///
1479 #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")]
1480 /// for documentation on overflow behaviour.
1481 ///
1482 /// # Example
1483 ///
1484 /// ```
1485 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1486 /// # fn main() { test().unwrap(); }
1487 /// # fn test() -> Option<()> {
1488 #[doc = concat!("let pos_five = ", stringify!($Ty), "::new(5)?;")]
1489 #[doc = concat!("let neg_five = ", stringify!($Ty), "::new(-5)?;")]
1490 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
1491 stringify!($Int), "::MIN)?;")]
1492 ///
1493 /// assert_eq!(pos_five.wrapping_neg(), neg_five);
1494 /// assert_eq!(min.wrapping_neg(), min);
1495 /// # Some(())
1496 /// # }
1497 /// ```
1498 #[inline]
1499 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1500 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1501 pub const fn wrapping_neg(self) -> Self {
1502 let result = self.get().wrapping_neg();
1503 // SAFETY: negation of nonzero cannot yield zero values.
1504 unsafe { Self::new_unchecked(result) }
1505 }
1506 };
1507}
1508
1509// Use this when the generated code should differ between signed and unsigned types.
1510macro_rules! sign_dependent_expr {
1511 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1512 $signed_case
1513 };
1514 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
1515 $unsigned_case
1516 };
1517}
1518
1519nonzero_integer! {
1520 Self = NonZeroU8,
1521 Primitive = unsigned u8,
1522}
1523
1524nonzero_integer! {
1525 Self = NonZeroU16,
1526 Primitive = unsigned u16,
1527}
1528
1529nonzero_integer! {
1530 Self = NonZeroU32,
1531 Primitive = unsigned u32,
1532}
1533
1534nonzero_integer! {
1535 Self = NonZeroU64,
1536 Primitive = unsigned u64,
1537}
1538
1539nonzero_integer! {
1540 Self = NonZeroU128,
1541 Primitive = unsigned u128,
1542}
1543
1544nonzero_integer! {
1545 Self = NonZeroUsize,
1546 Primitive = unsigned usize,
1547}
1548
1549nonzero_integer! {
1550 Self = NonZeroI8,
1551 Primitive = signed i8,
1552 UnsignedNonZero = NonZeroU8,
1553 UnsignedPrimitive = u8,
1554}
1555
1556nonzero_integer! {
1557 Self = NonZeroI16,
1558 Primitive = signed i16,
1559 UnsignedNonZero = NonZeroU16,
1560 UnsignedPrimitive = u16,
1561}
1562
1563nonzero_integer! {
1564 Self = NonZeroI32,
1565 Primitive = signed i32,
1566 UnsignedNonZero = NonZeroU32,
1567 UnsignedPrimitive = u32,
1568}
1569
1570nonzero_integer! {
1571 Self = NonZeroI64,
1572 Primitive = signed i64,
1573 UnsignedNonZero = NonZeroU64,
1574 UnsignedPrimitive = u64,
1575}
1576
1577nonzero_integer! {
1578 Self = NonZeroI128,
1579 Primitive = signed i128,
1580 UnsignedNonZero = NonZeroU128,
1581 UnsignedPrimitive = u128,
1582}
1583
1584nonzero_integer! {
1585 Self = NonZeroIsize,
1586 Primitive = signed isize,
1587 UnsignedNonZero = NonZeroUsize,
1588 UnsignedPrimitive = usize,
1589}
1590