]> git.proxmox.com Git - rustc.git/blob - library/core/src/num/nonzero.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / library / core / src / num / nonzero.rs
1 //! Definitions of integer that is known not to equal zero.
2
3 use crate::fmt;
4 use crate::ops::{BitOr, BitOrAssign, Div, Rem};
5 use crate::str::FromStr;
6
7 use super::from_str_radix;
8 use super::{IntErrorKind, ParseIntError};
9 use crate::intrinsics;
10
11 macro_rules! impl_nonzero_fmt {
12 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
13 $(
14 #[$stability]
15 impl fmt::$Trait for $Ty {
16 #[inline]
17 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18 self.get().fmt(f)
19 }
20 }
21 )+
22 }
23 }
24
25 macro_rules! nonzero_integers {
26 ( $( #[$stability: meta] #[$const_new_unchecked_stability: meta] $Ty: ident($Int: ty); )+ ) => {
27 $(
28 /// An integer that is known not to equal zero.
29 ///
30 /// This enables some memory layout optimization.
31 #[doc = concat!("For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:")]
32 ///
33 /// ```rust
34 /// use std::mem::size_of;
35 #[doc = concat!("assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int), ">());")]
36 /// ```
37 #[$stability]
38 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
39 #[repr(transparent)]
40 #[rustc_layout_scalar_valid_range_start(1)]
41 #[rustc_nonnull_optimization_guaranteed]
42 #[rustc_diagnostic_item = stringify!($Ty)]
43 pub struct $Ty($Int);
44
45 impl $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.
48 ///
49 /// # Safety
50 ///
51 /// The value must not be zero.
52 #[$stability]
53 #[$const_new_unchecked_stability]
54 #[must_use]
55 #[inline]
56 pub const unsafe fn new_unchecked(n: $Int) -> Self {
57 // SAFETY: this is guaranteed to be safe by the caller.
58 unsafe {
59 core::intrinsics::assert_unsafe_precondition!((n: $Int) => n != 0);
60 Self(n)
61 }
62 }
63
64 /// Creates a non-zero if the given value is not zero.
65 #[$stability]
66 #[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
67 #[must_use]
68 #[inline]
69 pub const fn new(n: $Int) -> Option<Self> {
70 if n != 0 {
71 // SAFETY: we just checked that there's no `0`
72 Some(unsafe { Self(n) })
73 } else {
74 None
75 }
76 }
77
78 /// Returns the value as a primitive type.
79 #[$stability]
80 #[inline]
81 #[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
82 pub const fn get(self) -> $Int {
83 self.0
84 }
85
86 }
87
88 #[stable(feature = "from_nonzero", since = "1.31.0")]
89 #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")]
90 impl const From<$Ty> for $Int {
91 #[doc = concat!("Converts a `", stringify!($Ty), "` into an `", stringify!($Int), "`")]
92 #[inline]
93 fn from(nonzero: $Ty) -> Self {
94 nonzero.0
95 }
96 }
97
98 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
99 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
100 impl const BitOr for $Ty {
101 type Output = Self;
102 #[inline]
103 fn bitor(self, rhs: Self) -> Self::Output {
104 // SAFETY: since `self` and `rhs` are both nonzero, the
105 // result of the bitwise-or will be nonzero.
106 unsafe { $Ty::new_unchecked(self.get() | rhs.get()) }
107 }
108 }
109
110 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
111 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
112 impl const BitOr<$Int> for $Ty {
113 type Output = Self;
114 #[inline]
115 fn bitor(self, rhs: $Int) -> Self::Output {
116 // SAFETY: since `self` is nonzero, the result of the
117 // bitwise-or will be nonzero regardless of the value of
118 // `rhs`.
119 unsafe { $Ty::new_unchecked(self.get() | rhs) }
120 }
121 }
122
123 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
124 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
125 impl const BitOr<$Ty> for $Int {
126 type Output = $Ty;
127 #[inline]
128 fn bitor(self, rhs: $Ty) -> Self::Output {
129 // SAFETY: since `rhs` is nonzero, the result of the
130 // bitwise-or will be nonzero regardless of the value of
131 // `self`.
132 unsafe { $Ty::new_unchecked(self | rhs.get()) }
133 }
134 }
135
136 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
137 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
138 impl const BitOrAssign for $Ty {
139 #[inline]
140 fn bitor_assign(&mut self, rhs: Self) {
141 *self = *self | rhs;
142 }
143 }
144
145 #[stable(feature = "nonzero_bitor", since = "1.45.0")]
146 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
147 impl const BitOrAssign<$Int> for $Ty {
148 #[inline]
149 fn bitor_assign(&mut self, rhs: $Int) {
150 *self = *self | rhs;
151 }
152 }
153
154 impl_nonzero_fmt! {
155 #[$stability] (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
156 }
157 )+
158 }
159 }
160
161 nonzero_integers! {
162 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU8(u8);
163 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU16(u16);
164 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU32(u32);
165 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU64(u64);
166 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroU128(u128);
167 #[stable(feature = "nonzero", since = "1.28.0")] #[rustc_const_stable(feature = "nonzero", since = "1.28.0")] NonZeroUsize(usize);
168 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI8(i8);
169 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI16(i16);
170 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI32(i32);
171 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI64(i64);
172 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroI128(i128);
173 #[stable(feature = "signed_nonzero", since = "1.34.0")] #[rustc_const_stable(feature = "signed_nonzero", since = "1.34.0")] NonZeroIsize(isize);
174 }
175
176 macro_rules! from_str_radix_nzint_impl {
177 ($($t:ty)*) => {$(
178 #[stable(feature = "nonzero_parse", since = "1.35.0")]
179 impl FromStr for $t {
180 type Err = ParseIntError;
181 fn from_str(src: &str) -> Result<Self, Self::Err> {
182 Self::new(from_str_radix(src, 10)?)
183 .ok_or(ParseIntError {
184 kind: IntErrorKind::Zero
185 })
186 }
187 }
188 )*}
189 }
190
191 from_str_radix_nzint_impl! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize
192 NonZeroI8 NonZeroI16 NonZeroI32 NonZeroI64 NonZeroI128 NonZeroIsize }
193
194 macro_rules! nonzero_leading_trailing_zeros {
195 ( $( $Ty: ident($Uint: ty) , $LeadingTestExpr:expr ;)+ ) => {
196 $(
197 impl $Ty {
198 /// Returns the number of leading zeros in the binary representation of `self`.
199 ///
200 /// On many architectures, this function can perform better than `leading_zeros()` on the underlying integer type, as special handling of zero can be avoided.
201 ///
202 /// # Examples
203 ///
204 /// Basic usage:
205 ///
206 /// ```
207 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(", stringify!($LeadingTestExpr), ").unwrap();")]
208 ///
209 /// assert_eq!(n.leading_zeros(), 0);
210 /// ```
211 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
212 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
213 #[must_use = "this returns the result of the operation, \
214 without modifying the original"]
215 #[inline]
216 pub const fn leading_zeros(self) -> u32 {
217 // SAFETY: since `self` cannot be zero, it is safe to call `ctlz_nonzero`.
218 unsafe { intrinsics::ctlz_nonzero(self.0 as $Uint) as u32 }
219 }
220
221 /// Returns the number of trailing zeros in the binary representation
222 /// of `self`.
223 ///
224 /// On many architectures, this function can perform better than `trailing_zeros()` on the underlying integer type, as special handling of zero can be avoided.
225 ///
226 /// # Examples
227 ///
228 /// Basic usage:
229 ///
230 /// ```
231 #[doc = concat!("let n = std::num::", stringify!($Ty), "::new(0b0101000).unwrap();")]
232 ///
233 /// assert_eq!(n.trailing_zeros(), 3);
234 /// ```
235 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
236 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
237 #[must_use = "this returns the result of the operation, \
238 without modifying the original"]
239 #[inline]
240 pub const fn trailing_zeros(self) -> u32 {
241 // SAFETY: since `self` cannot be zero, it is safe to call `cttz_nonzero`.
242 unsafe { intrinsics::cttz_nonzero(self.0 as $Uint) as u32 }
243 }
244
245 }
246 )+
247 }
248 }
249
250 nonzero_leading_trailing_zeros! {
251 NonZeroU8(u8), u8::MAX;
252 NonZeroU16(u16), u16::MAX;
253 NonZeroU32(u32), u32::MAX;
254 NonZeroU64(u64), u64::MAX;
255 NonZeroU128(u128), u128::MAX;
256 NonZeroUsize(usize), usize::MAX;
257 NonZeroI8(u8), -1i8;
258 NonZeroI16(u16), -1i16;
259 NonZeroI32(u32), -1i32;
260 NonZeroI64(u64), -1i64;
261 NonZeroI128(u128), -1i128;
262 NonZeroIsize(usize), -1isize;
263 }
264
265 macro_rules! nonzero_integers_div {
266 ( $( $Ty: ident($Int: ty); )+ ) => {
267 $(
268 #[stable(feature = "nonzero_div", since = "1.51.0")]
269 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
270 impl const Div<$Ty> for $Int {
271 type Output = $Int;
272 /// This operation rounds towards zero,
273 /// truncating any fractional part of the exact result, and cannot panic.
274 #[inline]
275 fn div(self, other: $Ty) -> $Int {
276 // SAFETY: div by zero is checked because `other` is a nonzero,
277 // and MIN/-1 is checked because `self` is an unsigned int.
278 unsafe { crate::intrinsics::unchecked_div(self, other.get()) }
279 }
280 }
281
282 #[stable(feature = "nonzero_div", since = "1.51.0")]
283 #[rustc_const_unstable(feature = "const_ops", issue = "90080")]
284 impl const Rem<$Ty> for $Int {
285 type Output = $Int;
286 /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
287 #[inline]
288 fn rem(self, other: $Ty) -> $Int {
289 // SAFETY: rem by zero is checked because `other` is a nonzero,
290 // and MIN/-1 is checked because `self` is an unsigned int.
291 unsafe { crate::intrinsics::unchecked_rem(self, other.get()) }
292 }
293 }
294 )+
295 }
296 }
297
298 nonzero_integers_div! {
299 NonZeroU8(u8);
300 NonZeroU16(u16);
301 NonZeroU32(u32);
302 NonZeroU64(u64);
303 NonZeroU128(u128);
304 NonZeroUsize(usize);
305 }
306
307 // A bunch of methods for unsigned nonzero types only.
308 macro_rules! nonzero_unsigned_operations {
309 ( $( $Ty: ident($Int: ident); )+ ) => {
310 $(
311 impl $Ty {
312 /// Adds an unsigned integer to a non-zero value.
313 /// Checks for overflow and returns [`None`] on overflow.
314 /// As a consequence, the result cannot wrap to zero.
315 ///
316 ///
317 /// # Examples
318 ///
319 /// ```
320 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
321 ///
322 /// # fn main() { test().unwrap(); }
323 /// # fn test() -> Option<()> {
324 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
325 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
326 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
327 stringify!($Int), "::MAX)?;")]
328 ///
329 /// assert_eq!(Some(two), one.checked_add(1));
330 /// assert_eq!(None, max.checked_add(1));
331 /// # Some(())
332 /// # }
333 /// ```
334 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
335 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
336 #[must_use = "this returns the result of the operation, \
337 without modifying the original"]
338 #[inline]
339 pub const fn checked_add(self, other: $Int) -> Option<$Ty> {
340 if let Some(result) = self.get().checked_add(other) {
341 // SAFETY: $Int::checked_add returns None on overflow
342 // so the result cannot be zero.
343 Some(unsafe { $Ty::new_unchecked(result) })
344 } else {
345 None
346 }
347 }
348
349 /// Adds an unsigned integer to a non-zero value.
350 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
351 ///
352 /// # Examples
353 ///
354 /// ```
355 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
356 ///
357 /// # fn main() { test().unwrap(); }
358 /// # fn test() -> Option<()> {
359 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
360 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
361 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
362 stringify!($Int), "::MAX)?;")]
363 ///
364 /// assert_eq!(two, one.saturating_add(1));
365 /// assert_eq!(max, max.saturating_add(1));
366 /// # Some(())
367 /// # }
368 /// ```
369 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
370 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
371 #[must_use = "this returns the result of the operation, \
372 without modifying the original"]
373 #[inline]
374 pub const fn saturating_add(self, other: $Int) -> $Ty {
375 // SAFETY: $Int::saturating_add returns $Int::MAX on overflow
376 // so the result cannot be zero.
377 unsafe { $Ty::new_unchecked(self.get().saturating_add(other)) }
378 }
379
380 /// Adds an unsigned integer to a non-zero value,
381 /// assuming overflow cannot occur.
382 /// Overflow is unchecked, and it is undefined behaviour to overflow
383 /// *even if the result would wrap to a non-zero value*.
384 /// The behaviour is undefined as soon as
385 #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
386 ///
387 /// # Examples
388 ///
389 /// ```
390 /// #![feature(nonzero_ops)]
391 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
392 ///
393 /// # fn main() { test().unwrap(); }
394 /// # fn test() -> Option<()> {
395 #[doc = concat!("let one = ", stringify!($Ty), "::new(1)?;")]
396 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
397 ///
398 /// assert_eq!(two, unsafe { one.unchecked_add(1) });
399 /// # Some(())
400 /// # }
401 /// ```
402 #[unstable(feature = "nonzero_ops", issue = "84186")]
403 #[must_use = "this returns the result of the operation, \
404 without modifying the original"]
405 #[inline]
406 pub const unsafe fn unchecked_add(self, other: $Int) -> $Ty {
407 // SAFETY: The caller ensures there is no overflow.
408 unsafe { $Ty::new_unchecked(self.get().unchecked_add(other)) }
409 }
410
411 /// Returns the smallest power of two greater than or equal to n.
412 /// Checks for overflow and returns [`None`]
413 /// if the next power of two is greater than the type’s maximum value.
414 /// As a consequence, the result cannot wrap to zero.
415 ///
416 /// # Examples
417 ///
418 /// ```
419 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
420 ///
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)?;")]
428 ///
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() );
432 /// # Some(())
433 /// # }
434 /// ```
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"]
439 #[inline]
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) })
445 } else {
446 None
447 }
448 }
449
450 /// Returns the base 2 logarithm of the number, rounded down.
451 ///
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.
456 ///
457 /// # Examples
458 ///
459 /// ```
460 /// #![feature(int_log)]
461 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
462 ///
463 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(7).unwrap().ilog2(), 2);")]
464 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(8).unwrap().ilog2(), 3);")]
465 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(9).unwrap().ilog2(), 3);")]
466 /// ```
467 #[unstable(feature = "int_log", issue = "70887")]
468 #[must_use = "this returns the result of the operation, \
469 without modifying the original"]
470 #[inline]
471 pub const fn ilog2(self) -> u32 {
472 Self::BITS - 1 - self.leading_zeros()
473 }
474
475 /// Returns the base 10 logarithm of the number, rounded down.
476 ///
477 /// This is the same operation as
478 #[doc = concat!("[`", stringify!($Int), "::ilog10`],")]
479 /// except that it has no failure cases to worry about
480 /// since this value can never be zero.
481 ///
482 /// # Examples
483 ///
484 /// ```
485 /// #![feature(int_log)]
486 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
487 ///
488 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(99).unwrap().ilog10(), 1);")]
489 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(100).unwrap().ilog10(), 2);")]
490 #[doc = concat!("assert_eq!(", stringify!($Ty), "::new(101).unwrap().ilog10(), 2);")]
491 /// ```
492 #[unstable(feature = "int_log", issue = "70887")]
493 #[must_use = "this returns the result of the operation, \
494 without modifying the original"]
495 #[inline]
496 pub const fn ilog10(self) -> u32 {
497 super::int_log10::$Int(self.0)
498 }
499 }
500 )+
501 }
502 }
503
504 nonzero_unsigned_operations! {
505 NonZeroU8(u8);
506 NonZeroU16(u16);
507 NonZeroU32(u32);
508 NonZeroU64(u64);
509 NonZeroU128(u128);
510 NonZeroUsize(usize);
511 }
512
513 // A bunch of methods for signed nonzero types only.
514 macro_rules! nonzero_signed_operations {
515 ( $( $Ty: ident($Int: ty) -> $Uty: ident($Uint: ty); )+ ) => {
516 $(
517 impl $Ty {
518 /// Computes the absolute value of self.
519 #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
520 /// for documentation on overflow behaviour.
521 ///
522 /// # Example
523 ///
524 /// ```
525 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
526 ///
527 /// # fn main() { test().unwrap(); }
528 /// # fn test() -> Option<()> {
529 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
530 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
531 ///
532 /// assert_eq!(pos, pos.abs());
533 /// assert_eq!(pos, neg.abs());
534 /// # Some(())
535 /// # }
536 /// ```
537 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
538 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
539 #[must_use = "this returns the result of the operation, \
540 without modifying the original"]
541 #[inline]
542 pub const fn abs(self) -> $Ty {
543 // SAFETY: This cannot overflow to zero.
544 unsafe { $Ty::new_unchecked(self.get().abs()) }
545 }
546
547 /// Checked absolute value.
548 /// Checks for overflow and returns [`None`] if
549 #[doc = concat!("`self == ", stringify!($Int), "::MIN`.")]
550 /// The result cannot be zero.
551 ///
552 /// # Example
553 ///
554 /// ```
555 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
556 ///
557 /// # fn main() { test().unwrap(); }
558 /// # fn test() -> Option<()> {
559 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
560 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
561 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
562 stringify!($Int), "::MIN)?;")]
563 ///
564 /// assert_eq!(Some(pos), neg.checked_abs());
565 /// assert_eq!(None, min.checked_abs());
566 /// # Some(())
567 /// # }
568 /// ```
569 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
570 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
571 #[must_use = "this returns the result of the operation, \
572 without modifying the original"]
573 #[inline]
574 pub const fn checked_abs(self) -> Option<$Ty> {
575 if let Some(nz) = self.get().checked_abs() {
576 // SAFETY: absolute value of nonzero cannot yield zero values.
577 Some(unsafe { $Ty::new_unchecked(nz) })
578 } else {
579 None
580 }
581 }
582
583 /// Computes the absolute value of self,
584 /// with overflow information, see
585 #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
586 ///
587 /// # Example
588 ///
589 /// ```
590 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
591 ///
592 /// # fn main() { test().unwrap(); }
593 /// # fn test() -> Option<()> {
594 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
595 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
596 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
597 stringify!($Int), "::MIN)?;")]
598 ///
599 /// assert_eq!((pos, false), pos.overflowing_abs());
600 /// assert_eq!((pos, false), neg.overflowing_abs());
601 /// assert_eq!((min, true), min.overflowing_abs());
602 /// # Some(())
603 /// # }
604 /// ```
605 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
606 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
607 #[must_use = "this returns the result of the operation, \
608 without modifying the original"]
609 #[inline]
610 pub const fn overflowing_abs(self) -> ($Ty, bool) {
611 let (nz, flag) = self.get().overflowing_abs();
612 (
613 // SAFETY: absolute value of nonzero cannot yield zero values.
614 unsafe { $Ty::new_unchecked(nz) },
615 flag,
616 )
617 }
618
619 /// Saturating absolute value, see
620 #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
621 ///
622 /// # Example
623 ///
624 /// ```
625 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
626 ///
627 /// # fn main() { test().unwrap(); }
628 /// # fn test() -> Option<()> {
629 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
630 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
631 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
632 stringify!($Int), "::MIN)?;")]
633 #[doc = concat!("let min_plus = ", stringify!($Ty), "::new(",
634 stringify!($Int), "::MIN + 1)?;")]
635 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
636 stringify!($Int), "::MAX)?;")]
637 ///
638 /// assert_eq!(pos, pos.saturating_abs());
639 /// assert_eq!(pos, neg.saturating_abs());
640 /// assert_eq!(max, min.saturating_abs());
641 /// assert_eq!(max, min_plus.saturating_abs());
642 /// # Some(())
643 /// # }
644 /// ```
645 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
646 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
647 #[must_use = "this returns the result of the operation, \
648 without modifying the original"]
649 #[inline]
650 pub const fn saturating_abs(self) -> $Ty {
651 // SAFETY: absolute value of nonzero cannot yield zero values.
652 unsafe { $Ty::new_unchecked(self.get().saturating_abs()) }
653 }
654
655 /// Wrapping absolute value, see
656 #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
657 ///
658 /// # Example
659 ///
660 /// ```
661 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
662 ///
663 /// # fn main() { test().unwrap(); }
664 /// # fn test() -> Option<()> {
665 #[doc = concat!("let pos = ", stringify!($Ty), "::new(1)?;")]
666 #[doc = concat!("let neg = ", stringify!($Ty), "::new(-1)?;")]
667 #[doc = concat!("let min = ", stringify!($Ty), "::new(",
668 stringify!($Int), "::MIN)?;")]
669 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
670 stringify!($Int), "::MAX)?;")]
671 ///
672 /// assert_eq!(pos, pos.wrapping_abs());
673 /// assert_eq!(pos, neg.wrapping_abs());
674 /// assert_eq!(min, min.wrapping_abs());
675 /// # // FIXME: add once Neg is implemented?
676 /// # // assert_eq!(max, (-max).wrapping_abs());
677 /// # Some(())
678 /// # }
679 /// ```
680 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
681 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
682 #[must_use = "this returns the result of the operation, \
683 without modifying the original"]
684 #[inline]
685 pub const fn wrapping_abs(self) -> $Ty {
686 // SAFETY: absolute value of nonzero cannot yield zero values.
687 unsafe { $Ty::new_unchecked(self.get().wrapping_abs()) }
688 }
689
690 /// Computes the absolute value of self
691 /// without any wrapping or panicking.
692 ///
693 /// # Example
694 ///
695 /// ```
696 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
697 #[doc = concat!("# use std::num::", stringify!($Uty), ";")]
698 ///
699 /// # fn main() { test().unwrap(); }
700 /// # fn test() -> Option<()> {
701 #[doc = concat!("let u_pos = ", stringify!($Uty), "::new(1)?;")]
702 #[doc = concat!("let i_pos = ", stringify!($Ty), "::new(1)?;")]
703 #[doc = concat!("let i_neg = ", stringify!($Ty), "::new(-1)?;")]
704 #[doc = concat!("let i_min = ", stringify!($Ty), "::new(",
705 stringify!($Int), "::MIN)?;")]
706 #[doc = concat!("let u_max = ", stringify!($Uty), "::new(",
707 stringify!($Uint), "::MAX / 2 + 1)?;")]
708 ///
709 /// assert_eq!(u_pos, i_pos.unsigned_abs());
710 /// assert_eq!(u_pos, i_neg.unsigned_abs());
711 /// assert_eq!(u_max, i_min.unsigned_abs());
712 /// # Some(())
713 /// # }
714 /// ```
715 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
716 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
717 #[must_use = "this returns the result of the operation, \
718 without modifying the original"]
719 #[inline]
720 pub const fn unsigned_abs(self) -> $Uty {
721 // SAFETY: absolute value of nonzero cannot yield zero values.
722 unsafe { $Uty::new_unchecked(self.get().unsigned_abs()) }
723 }
724 }
725 )+
726 }
727 }
728
729 nonzero_signed_operations! {
730 NonZeroI8(i8) -> NonZeroU8(u8);
731 NonZeroI16(i16) -> NonZeroU16(u16);
732 NonZeroI32(i32) -> NonZeroU32(u32);
733 NonZeroI64(i64) -> NonZeroU64(u64);
734 NonZeroI128(i128) -> NonZeroU128(u128);
735 NonZeroIsize(isize) -> NonZeroUsize(usize);
736 }
737
738 // A bunch of methods for both signed and unsigned nonzero types.
739 macro_rules! nonzero_unsigned_signed_operations {
740 ( $( $signedness:ident $Ty: ident($Int: ty); )+ ) => {
741 $(
742 impl $Ty {
743 /// Multiplies two non-zero integers together.
744 /// Checks for overflow and returns [`None`] on overflow.
745 /// As a consequence, the result cannot wrap to zero.
746 ///
747 /// # Examples
748 ///
749 /// ```
750 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
751 ///
752 /// # fn main() { test().unwrap(); }
753 /// # fn test() -> Option<()> {
754 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
755 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
756 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
757 stringify!($Int), "::MAX)?;")]
758 ///
759 /// assert_eq!(Some(four), two.checked_mul(two));
760 /// assert_eq!(None, max.checked_mul(two));
761 /// # Some(())
762 /// # }
763 /// ```
764 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
765 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
766 #[must_use = "this returns the result of the operation, \
767 without modifying the original"]
768 #[inline]
769 pub const fn checked_mul(self, other: $Ty) -> Option<$Ty> {
770 if let Some(result) = self.get().checked_mul(other.get()) {
771 // SAFETY: checked_mul returns None on overflow
772 // and `other` is also non-null
773 // so the result cannot be zero.
774 Some(unsafe { $Ty::new_unchecked(result) })
775 } else {
776 None
777 }
778 }
779
780 /// Multiplies two non-zero integers together.
781 #[doc = concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")]
782 ///
783 /// # Examples
784 ///
785 /// ```
786 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
787 ///
788 /// # fn main() { test().unwrap(); }
789 /// # fn test() -> Option<()> {
790 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
791 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
792 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
793 stringify!($Int), "::MAX)?;")]
794 ///
795 /// assert_eq!(four, two.saturating_mul(two));
796 /// assert_eq!(max, four.saturating_mul(max));
797 /// # Some(())
798 /// # }
799 /// ```
800 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
801 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
802 #[must_use = "this returns the result of the operation, \
803 without modifying the original"]
804 #[inline]
805 pub const fn saturating_mul(self, other: $Ty) -> $Ty {
806 // SAFETY: saturating_mul returns u*::MAX on overflow
807 // and `other` is also non-null
808 // so the result cannot be zero.
809 unsafe { $Ty::new_unchecked(self.get().saturating_mul(other.get())) }
810 }
811
812 /// Multiplies two non-zero integers together,
813 /// assuming overflow cannot occur.
814 /// Overflow is unchecked, and it is undefined behaviour to overflow
815 /// *even if the result would wrap to a non-zero value*.
816 /// The behaviour is undefined as soon as
817 #[doc = sign_dependent_expr!{
818 $signedness ?
819 if signed {
820 concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
821 "or `self * rhs < ", stringify!($Int), "::MIN`.")
822 }
823 if unsigned {
824 concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
825 }
826 }]
827 ///
828 /// # Examples
829 ///
830 /// ```
831 /// #![feature(nonzero_ops)]
832 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
833 ///
834 /// # fn main() { test().unwrap(); }
835 /// # fn test() -> Option<()> {
836 #[doc = concat!("let two = ", stringify!($Ty), "::new(2)?;")]
837 #[doc = concat!("let four = ", stringify!($Ty), "::new(4)?;")]
838 ///
839 /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
840 /// # Some(())
841 /// # }
842 /// ```
843 #[unstable(feature = "nonzero_ops", issue = "84186")]
844 #[must_use = "this returns the result of the operation, \
845 without modifying the original"]
846 #[inline]
847 pub const unsafe fn unchecked_mul(self, other: $Ty) -> $Ty {
848 // SAFETY: The caller ensures there is no overflow.
849 unsafe { $Ty::new_unchecked(self.get().unchecked_mul(other.get())) }
850 }
851
852 /// Raises non-zero value to an integer power.
853 /// Checks for overflow and returns [`None`] on overflow.
854 /// As a consequence, the result cannot wrap to zero.
855 ///
856 /// # Examples
857 ///
858 /// ```
859 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
860 ///
861 /// # fn main() { test().unwrap(); }
862 /// # fn test() -> Option<()> {
863 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
864 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
865 #[doc = concat!("let half_max = ", stringify!($Ty), "::new(",
866 stringify!($Int), "::MAX / 2)?;")]
867 ///
868 /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
869 /// assert_eq!(None, half_max.checked_pow(3));
870 /// # Some(())
871 /// # }
872 /// ```
873 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
874 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
875 #[must_use = "this returns the result of the operation, \
876 without modifying the original"]
877 #[inline]
878 pub const fn checked_pow(self, other: u32) -> Option<$Ty> {
879 if let Some(result) = self.get().checked_pow(other) {
880 // SAFETY: checked_pow returns None on overflow
881 // so the result cannot be zero.
882 Some(unsafe { $Ty::new_unchecked(result) })
883 } else {
884 None
885 }
886 }
887
888 /// Raise non-zero value to an integer power.
889 #[doc = sign_dependent_expr!{
890 $signedness ?
891 if signed {
892 concat!("Return [`", stringify!($Int), "::MIN`] ",
893 "or [`", stringify!($Int), "::MAX`] on overflow.")
894 }
895 if unsigned {
896 concat!("Return [`", stringify!($Int), "::MAX`] on overflow.")
897 }
898 }]
899 ///
900 /// # Examples
901 ///
902 /// ```
903 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
904 ///
905 /// # fn main() { test().unwrap(); }
906 /// # fn test() -> Option<()> {
907 #[doc = concat!("let three = ", stringify!($Ty), "::new(3)?;")]
908 #[doc = concat!("let twenty_seven = ", stringify!($Ty), "::new(27)?;")]
909 #[doc = concat!("let max = ", stringify!($Ty), "::new(",
910 stringify!($Int), "::MAX)?;")]
911 ///
912 /// assert_eq!(twenty_seven, three.saturating_pow(3));
913 /// assert_eq!(max, max.saturating_pow(3));
914 /// # Some(())
915 /// # }
916 /// ```
917 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
918 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
919 #[must_use = "this returns the result of the operation, \
920 without modifying the original"]
921 #[inline]
922 pub const fn saturating_pow(self, other: u32) -> $Ty {
923 // SAFETY: saturating_pow returns u*::MAX on overflow
924 // so the result cannot be zero.
925 unsafe { $Ty::new_unchecked(self.get().saturating_pow(other)) }
926 }
927 }
928 )+
929 }
930 }
931
932 // Use this when the generated code should differ between signed and unsigned types.
933 macro_rules! sign_dependent_expr {
934 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
935 $signed_case
936 };
937 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
938 $unsigned_case
939 };
940 }
941
942 nonzero_unsigned_signed_operations! {
943 unsigned NonZeroU8(u8);
944 unsigned NonZeroU16(u16);
945 unsigned NonZeroU32(u32);
946 unsigned NonZeroU64(u64);
947 unsigned NonZeroU128(u128);
948 unsigned NonZeroUsize(usize);
949 signed NonZeroI8(i8);
950 signed NonZeroI16(i16);
951 signed NonZeroI32(i32);
952 signed NonZeroI64(i64);
953 signed NonZeroI128(i128);
954 signed NonZeroIsize(isize);
955 }
956
957 macro_rules! nonzero_unsigned_is_power_of_two {
958 ( $( $Ty: ident )+ ) => {
959 $(
960 impl $Ty {
961
962 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
963 ///
964 /// On many architectures, this function can perform better than `is_power_of_two()`
965 /// on the underlying integer type, as special handling of zero can be avoided.
966 ///
967 /// # Examples
968 ///
969 /// Basic usage:
970 ///
971 /// ```
972 #[doc = concat!("let eight = std::num::", stringify!($Ty), "::new(8).unwrap();")]
973 /// assert!(eight.is_power_of_two());
974 #[doc = concat!("let ten = std::num::", stringify!($Ty), "::new(10).unwrap();")]
975 /// assert!(!ten.is_power_of_two());
976 /// ```
977 #[must_use]
978 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
979 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
980 #[inline]
981 pub const fn is_power_of_two(self) -> bool {
982 // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
983 // On the basic x86-64 target, this saves 3 instructions for the zero check.
984 // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
985 // compared to the `POPCNT` implementation on the underlying integer type.
986
987 intrinsics::ctpop(self.get()) < 2
988 }
989
990 }
991 )+
992 }
993 }
994
995 nonzero_unsigned_is_power_of_two! { NonZeroU8 NonZeroU16 NonZeroU32 NonZeroU64 NonZeroU128 NonZeroUsize }
996
997 macro_rules! nonzero_min_max_unsigned {
998 ( $( $Ty: ident($Int: ident); )+ ) => {
999 $(
1000 impl $Ty {
1001 /// The smallest value that can be represented by this non-zero
1002 /// integer type, 1.
1003 ///
1004 /// # Examples
1005 ///
1006 /// ```
1007 /// #![feature(nonzero_min_max)]
1008 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1009 ///
1010 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), 1", stringify!($Int), ");")]
1011 /// ```
1012 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1013 pub const MIN: Self = Self::new(1).unwrap();
1014
1015 /// The largest value that can be represented by this non-zero
1016 /// integer type,
1017 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1018 ///
1019 /// # Examples
1020 ///
1021 /// ```
1022 /// #![feature(nonzero_min_max)]
1023 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1024 ///
1025 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1026 /// ```
1027 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1028 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1029 }
1030 )+
1031 }
1032 }
1033
1034 macro_rules! nonzero_min_max_signed {
1035 ( $( $Ty: ident($Int: ident); )+ ) => {
1036 $(
1037 impl $Ty {
1038 /// The smallest value that can be represented by this non-zero
1039 /// integer type,
1040 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1041 ///
1042 /// Note: While most integer types are defined for every whole
1043 /// number between `MIN` and `MAX`, signed non-zero integers are
1044 /// a special case. They have a "gap" at 0.
1045 ///
1046 /// # Examples
1047 ///
1048 /// ```
1049 /// #![feature(nonzero_min_max)]
1050 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1051 ///
1052 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MIN.get(), ", stringify!($Int), "::MIN);")]
1053 /// ```
1054 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1055 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1056
1057 /// The largest value that can be represented by this non-zero
1058 /// integer type,
1059 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1060 ///
1061 /// Note: While most integer types are defined for every whole
1062 /// number between `MIN` and `MAX`, signed non-zero integers are
1063 /// a special case. They have a "gap" at 0.
1064 ///
1065 /// # Examples
1066 ///
1067 /// ```
1068 /// #![feature(nonzero_min_max)]
1069 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1070 ///
1071 #[doc = concat!("assert_eq!(", stringify!($Ty), "::MAX.get(), ", stringify!($Int), "::MAX);")]
1072 /// ```
1073 #[unstable(feature = "nonzero_min_max", issue = "89065")]
1074 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1075 }
1076 )+
1077 }
1078 }
1079
1080 nonzero_min_max_unsigned! {
1081 NonZeroU8(u8);
1082 NonZeroU16(u16);
1083 NonZeroU32(u32);
1084 NonZeroU64(u64);
1085 NonZeroU128(u128);
1086 NonZeroUsize(usize);
1087 }
1088
1089 nonzero_min_max_signed! {
1090 NonZeroI8(i8);
1091 NonZeroI16(i16);
1092 NonZeroI32(i32);
1093 NonZeroI64(i64);
1094 NonZeroI128(i128);
1095 NonZeroIsize(isize);
1096 }
1097
1098 macro_rules! nonzero_bits {
1099 ( $( $Ty: ident($Int: ty); )+ ) => {
1100 $(
1101 impl $Ty {
1102 /// The size of this non-zero integer type in bits.
1103 ///
1104 #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
1105 ///
1106 /// # Examples
1107 ///
1108 /// ```
1109 /// #![feature(nonzero_bits)]
1110 #[doc = concat!("# use std::num::", stringify!($Ty), ";")]
1111 ///
1112 #[doc = concat!("assert_eq!(", stringify!($Ty), "::BITS, ", stringify!($Int), "::BITS);")]
1113 /// ```
1114 #[unstable(feature = "nonzero_bits", issue = "94881")]
1115 pub const BITS: u32 = <$Int>::BITS;
1116 }
1117 )+
1118 }
1119 }
1120
1121 nonzero_bits! {
1122 NonZeroU8(u8);
1123 NonZeroI8(i8);
1124 NonZeroU16(u16);
1125 NonZeroI16(i16);
1126 NonZeroU32(u32);
1127 NonZeroI32(i32);
1128 NonZeroU64(u64);
1129 NonZeroI64(i64);
1130 NonZeroU128(u128);
1131 NonZeroI128(i128);
1132 NonZeroUsize(usize);
1133 NonZeroIsize(isize);
1134 }