core/num/nonzero.rs
1//! Definitions of integer that is known not to equal zero.
2
3use super::{IntErrorKind, ParseIntError};
4use crate::clone::UseCloned;
5use crate::cmp::Ordering;
6use crate::hash::{Hash, Hasher};
7use crate::marker::{Freeze, StructuralPartialEq};
8use crate::ops::{BitOr, BitOrAssign, Div, DivAssign, Neg, Rem, RemAssign};
9use crate::panic::{RefUnwindSafe, UnwindSafe};
10use crate::str::FromStr;
11use crate::{fmt, intrinsics, ptr, ub_checks};
12
13/// A marker trait for primitive types which can be zero.
14///
15/// This is an implementation detail for <code>[NonZero]\<T></code> which may disappear or be replaced at any time.
16///
17/// # Safety
18///
19/// Types implementing this trait must be primitives that are valid when zeroed.
20///
21/// The associated `Self::NonZeroInner` type must have the same size+align as `Self`,
22/// but with a niche and bit validity making it so the following `transmutes` are sound:
23///
24/// - `Self::NonZeroInner` to `Option<Self::NonZeroInner>`
25/// - `Option<Self::NonZeroInner>` to `Self`
26///
27/// (And, consequently, `Self::NonZeroInner` to `Self`.)
28#[unstable(
29 feature = "nonzero_internals",
30 reason = "implementation detail which may disappear or be replaced at any time",
31 issue = "none"
32)]
33pub unsafe trait ZeroablePrimitive: Sized + Copy + private::Sealed {
34 #[doc(hidden)]
35 type NonZeroInner: Sized + Copy;
36}
37
38macro_rules! impl_zeroable_primitive {
39 ($($NonZeroInner:ident ( $primitive:ty )),+ $(,)?) => {
40 mod private {
41 #[unstable(
42 feature = "nonzero_internals",
43 reason = "implementation detail which may disappear or be replaced at any time",
44 issue = "none"
45 )]
46 pub trait Sealed {}
47 }
48
49 $(
50 #[unstable(
51 feature = "nonzero_internals",
52 reason = "implementation detail which may disappear or be replaced at any time",
53 issue = "none"
54 )]
55 impl private::Sealed for $primitive {}
56
57 #[unstable(
58 feature = "nonzero_internals",
59 reason = "implementation detail which may disappear or be replaced at any time",
60 issue = "none"
61 )]
62 unsafe impl ZeroablePrimitive for $primitive {
63 type NonZeroInner = super::niche_types::$NonZeroInner;
64 }
65 )+
66 };
67}
68
69impl_zeroable_primitive!(
70 NonZeroU8Inner(u8),
71 NonZeroU16Inner(u16),
72 NonZeroU32Inner(u32),
73 NonZeroU64Inner(u64),
74 NonZeroU128Inner(u128),
75 NonZeroUsizeInner(usize),
76 NonZeroI8Inner(i8),
77 NonZeroI16Inner(i16),
78 NonZeroI32Inner(i32),
79 NonZeroI64Inner(i64),
80 NonZeroI128Inner(i128),
81 NonZeroIsizeInner(isize),
82);
83
84/// A value that is known not to equal zero.
85///
86/// This enables some memory layout optimization.
87/// For example, `Option<NonZero<u32>>` is the same size as `u32`:
88///
89/// ```
90/// use core::{num::NonZero};
91///
92/// assert_eq!(size_of::<Option<NonZero<u32>>>(), size_of::<u32>());
93/// ```
94///
95/// # Layout
96///
97/// `NonZero<T>` is guaranteed to have the same layout and bit validity as `T`
98/// with the exception that the all-zero bit pattern is invalid.
99/// `Option<NonZero<T>>` is guaranteed to be compatible with `T`, including in
100/// FFI.
101///
102/// Thanks to the [null pointer optimization], `NonZero<T>` and
103/// `Option<NonZero<T>>` are guaranteed to have the same size and alignment:
104///
105/// ```
106/// use std::num::NonZero;
107///
108/// assert_eq!(size_of::<NonZero<u32>>(), size_of::<Option<NonZero<u32>>>());
109/// assert_eq!(align_of::<NonZero<u32>>(), align_of::<Option<NonZero<u32>>>());
110/// ```
111///
112/// [null pointer optimization]: crate::option#representation
113#[stable(feature = "generic_nonzero", since = "1.79.0")]
114#[repr(transparent)]
115#[rustc_nonnull_optimization_guaranteed]
116#[rustc_diagnostic_item = "NonZero"]
117pub struct NonZero<T: ZeroablePrimitive>(T::NonZeroInner);
118
119macro_rules! impl_nonzero_fmt {
120 ($(#[$Attribute:meta] $Trait:ident)*) => {
121 $(
122 #[$Attribute]
123 impl<T> fmt::$Trait for NonZero<T>
124 where
125 T: ZeroablePrimitive + fmt::$Trait,
126 {
127 #[inline]
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 self.get().fmt(f)
130 }
131 }
132 )*
133 };
134}
135
136impl_nonzero_fmt! {
137 #[stable(feature = "nonzero", since = "1.28.0")]
138 Debug
139 #[stable(feature = "nonzero", since = "1.28.0")]
140 Display
141 #[stable(feature = "nonzero", since = "1.28.0")]
142 Binary
143 #[stable(feature = "nonzero", since = "1.28.0")]
144 Octal
145 #[stable(feature = "nonzero", since = "1.28.0")]
146 LowerHex
147 #[stable(feature = "nonzero", since = "1.28.0")]
148 UpperHex
149 #[stable(feature = "nonzero_fmt_exp", since = "1.84.0")]
150 LowerExp
151 #[stable(feature = "nonzero_fmt_exp", since = "1.84.0")]
152 UpperExp
153}
154
155macro_rules! impl_nonzero_auto_trait {
156 (unsafe $Trait:ident) => {
157 #[stable(feature = "nonzero", since = "1.28.0")]
158 unsafe impl<T> $Trait for NonZero<T> where T: ZeroablePrimitive + $Trait {}
159 };
160 ($Trait:ident) => {
161 #[stable(feature = "nonzero", since = "1.28.0")]
162 impl<T> $Trait for NonZero<T> where T: ZeroablePrimitive + $Trait {}
163 };
164}
165
166// Implement auto-traits manually based on `T` to avoid docs exposing
167// the `ZeroablePrimitive::NonZeroInner` implementation detail.
168impl_nonzero_auto_trait!(unsafe Freeze);
169impl_nonzero_auto_trait!(RefUnwindSafe);
170impl_nonzero_auto_trait!(unsafe Send);
171impl_nonzero_auto_trait!(unsafe Sync);
172impl_nonzero_auto_trait!(Unpin);
173impl_nonzero_auto_trait!(UnwindSafe);
174
175#[stable(feature = "nonzero", since = "1.28.0")]
176impl<T> Clone for NonZero<T>
177where
178 T: ZeroablePrimitive,
179{
180 #[inline]
181 fn clone(&self) -> Self {
182 *self
183 }
184}
185
186#[unstable(feature = "ergonomic_clones", issue = "132290")]
187impl<T> UseCloned for NonZero<T> where T: ZeroablePrimitive {}
188
189#[stable(feature = "nonzero", since = "1.28.0")]
190impl<T> Copy for NonZero<T> where T: ZeroablePrimitive {}
191
192#[stable(feature = "nonzero", since = "1.28.0")]
193impl<T> PartialEq for NonZero<T>
194where
195 T: ZeroablePrimitive + PartialEq,
196{
197 #[inline]
198 fn eq(&self, other: &Self) -> bool {
199 self.get() == other.get()
200 }
201
202 #[inline]
203 fn ne(&self, other: &Self) -> bool {
204 self.get() != other.get()
205 }
206}
207
208#[unstable(feature = "structural_match", issue = "31434")]
209impl<T> StructuralPartialEq for NonZero<T> where T: ZeroablePrimitive + StructuralPartialEq {}
210
211#[stable(feature = "nonzero", since = "1.28.0")]
212impl<T> Eq for NonZero<T> where T: ZeroablePrimitive + Eq {}
213
214#[stable(feature = "nonzero", since = "1.28.0")]
215impl<T> PartialOrd for NonZero<T>
216where
217 T: ZeroablePrimitive + PartialOrd,
218{
219 #[inline]
220 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
221 self.get().partial_cmp(&other.get())
222 }
223
224 #[inline]
225 fn lt(&self, other: &Self) -> bool {
226 self.get() < other.get()
227 }
228
229 #[inline]
230 fn le(&self, other: &Self) -> bool {
231 self.get() <= other.get()
232 }
233
234 #[inline]
235 fn gt(&self, other: &Self) -> bool {
236 self.get() > other.get()
237 }
238
239 #[inline]
240 fn ge(&self, other: &Self) -> bool {
241 self.get() >= other.get()
242 }
243}
244
245#[stable(feature = "nonzero", since = "1.28.0")]
246impl<T> Ord for NonZero<T>
247where
248 T: ZeroablePrimitive + Ord,
249{
250 #[inline]
251 fn cmp(&self, other: &Self) -> Ordering {
252 self.get().cmp(&other.get())
253 }
254
255 #[inline]
256 fn max(self, other: Self) -> Self {
257 // SAFETY: The maximum of two non-zero values is still non-zero.
258 unsafe { Self::new_unchecked(self.get().max(other.get())) }
259 }
260
261 #[inline]
262 fn min(self, other: Self) -> Self {
263 // SAFETY: The minimum of two non-zero values is still non-zero.
264 unsafe { Self::new_unchecked(self.get().min(other.get())) }
265 }
266
267 #[inline]
268 fn clamp(self, min: Self, max: Self) -> Self {
269 // SAFETY: A non-zero value clamped between two non-zero values is still non-zero.
270 unsafe { Self::new_unchecked(self.get().clamp(min.get(), max.get())) }
271 }
272}
273
274#[stable(feature = "nonzero", since = "1.28.0")]
275impl<T> Hash for NonZero<T>
276where
277 T: ZeroablePrimitive + Hash,
278{
279 #[inline]
280 fn hash<H>(&self, state: &mut H)
281 where
282 H: Hasher,
283 {
284 self.get().hash(state)
285 }
286}
287
288#[stable(feature = "from_nonzero", since = "1.31.0")]
289impl<T> From<NonZero<T>> for T
290where
291 T: ZeroablePrimitive,
292{
293 #[inline]
294 fn from(nonzero: NonZero<T>) -> Self {
295 // Call `get` method to keep range information.
296 nonzero.get()
297 }
298}
299
300#[stable(feature = "nonzero_bitor", since = "1.45.0")]
301impl<T> BitOr for NonZero<T>
302where
303 T: ZeroablePrimitive + BitOr<Output = T>,
304{
305 type Output = Self;
306
307 #[inline]
308 fn bitor(self, rhs: Self) -> Self::Output {
309 // SAFETY: Bitwise OR of two non-zero values is still non-zero.
310 unsafe { Self::new_unchecked(self.get() | rhs.get()) }
311 }
312}
313
314#[stable(feature = "nonzero_bitor", since = "1.45.0")]
315impl<T> BitOr<T> for NonZero<T>
316where
317 T: ZeroablePrimitive + BitOr<Output = T>,
318{
319 type Output = Self;
320
321 #[inline]
322 fn bitor(self, rhs: T) -> Self::Output {
323 // SAFETY: Bitwise OR of a non-zero value with anything is still non-zero.
324 unsafe { Self::new_unchecked(self.get() | rhs) }
325 }
326}
327
328#[stable(feature = "nonzero_bitor", since = "1.45.0")]
329impl<T> BitOr<NonZero<T>> for T
330where
331 T: ZeroablePrimitive + BitOr<Output = T>,
332{
333 type Output = NonZero<T>;
334
335 #[inline]
336 fn bitor(self, rhs: NonZero<T>) -> Self::Output {
337 // SAFETY: Bitwise OR of anything with a non-zero value is still non-zero.
338 unsafe { NonZero::new_unchecked(self | rhs.get()) }
339 }
340}
341
342#[stable(feature = "nonzero_bitor", since = "1.45.0")]
343impl<T> BitOrAssign for NonZero<T>
344where
345 T: ZeroablePrimitive,
346 Self: BitOr<Output = Self>,
347{
348 #[inline]
349 fn bitor_assign(&mut self, rhs: Self) {
350 *self = *self | rhs;
351 }
352}
353
354#[stable(feature = "nonzero_bitor", since = "1.45.0")]
355impl<T> BitOrAssign<T> for NonZero<T>
356where
357 T: ZeroablePrimitive,
358 Self: BitOr<T, Output = Self>,
359{
360 #[inline]
361 fn bitor_assign(&mut self, rhs: T) {
362 *self = *self | rhs;
363 }
364}
365
366impl<T> NonZero<T>
367where
368 T: ZeroablePrimitive,
369{
370 /// Creates a non-zero if the given value is not zero.
371 #[stable(feature = "nonzero", since = "1.28.0")]
372 #[rustc_const_stable(feature = "const_nonzero_int_methods", since = "1.47.0")]
373 #[must_use]
374 #[inline]
375 pub const fn new(n: T) -> Option<Self> {
376 // SAFETY: Memory layout optimization guarantees that `Option<NonZero<T>>` has
377 // the same layout and size as `T`, with `0` representing `None`.
378 unsafe { intrinsics::transmute_unchecked(n) }
379 }
380
381 /// Creates a non-zero without checking whether the value is non-zero.
382 /// This results in undefined behavior if the value is zero.
383 ///
384 /// # Safety
385 ///
386 /// The value must not be zero.
387 #[stable(feature = "nonzero", since = "1.28.0")]
388 #[rustc_const_stable(feature = "nonzero", since = "1.28.0")]
389 #[must_use]
390 #[inline]
391 #[track_caller]
392 pub const unsafe fn new_unchecked(n: T) -> Self {
393 match Self::new(n) {
394 Some(n) => n,
395 None => {
396 // SAFETY: The caller guarantees that `n` is non-zero, so this is unreachable.
397 unsafe {
398 ub_checks::assert_unsafe_precondition!(
399 check_language_ub,
400 "NonZero::new_unchecked requires the argument to be non-zero",
401 () => false,
402 );
403 intrinsics::unreachable()
404 }
405 }
406 }
407 }
408
409 /// Converts a reference to a non-zero mutable reference
410 /// if the referenced value is not zero.
411 #[unstable(feature = "nonzero_from_mut", issue = "106290")]
412 #[must_use]
413 #[inline]
414 pub fn from_mut(n: &mut T) -> Option<&mut Self> {
415 // SAFETY: Memory layout optimization guarantees that `Option<NonZero<T>>` has
416 // the same layout and size as `T`, with `0` representing `None`.
417 let opt_n = unsafe { &mut *(ptr::from_mut(n).cast::<Option<Self>>()) };
418
419 opt_n.as_mut()
420 }
421
422 /// Converts a mutable reference to a non-zero mutable reference
423 /// without checking whether the referenced value is non-zero.
424 /// This results in undefined behavior if the referenced value is zero.
425 ///
426 /// # Safety
427 ///
428 /// The referenced value must not be zero.
429 #[unstable(feature = "nonzero_from_mut", issue = "106290")]
430 #[must_use]
431 #[inline]
432 #[track_caller]
433 pub unsafe fn from_mut_unchecked(n: &mut T) -> &mut Self {
434 match Self::from_mut(n) {
435 Some(n) => n,
436 None => {
437 // SAFETY: The caller guarantees that `n` references a value that is non-zero, so this is unreachable.
438 unsafe {
439 ub_checks::assert_unsafe_precondition!(
440 check_library_ub,
441 "NonZero::from_mut_unchecked requires the argument to dereference as non-zero",
442 () => false,
443 );
444 intrinsics::unreachable()
445 }
446 }
447 }
448 }
449
450 /// Returns the contained value as a primitive type.
451 #[stable(feature = "nonzero", since = "1.28.0")]
452 #[rustc_const_stable(feature = "const_nonzero_get", since = "1.34.0")]
453 #[inline]
454 pub const fn get(self) -> T {
455 // Rustc can set range metadata only if it loads `self` from
456 // memory somewhere. If the value of `self` was from by-value argument
457 // of some not-inlined function, LLVM don't have range metadata
458 // to understand that the value cannot be zero.
459 //
460 // Using the transmute `assume`s the range at runtime.
461 //
462 // Even once LLVM supports `!range` metadata for function arguments
463 // (see <https://github.com/llvm/llvm-project/issues/76628>), this can't
464 // be `.0` because MCP#807 bans field-projecting into `scalar_valid_range`
465 // types, and it arguably wouldn't want to be anyway because if this is
466 // MIR-inlined, there's no opportunity to put that argument metadata anywhere.
467 //
468 // The good answer here will eventually be pattern types, which will hopefully
469 // allow it to go back to `.0`, maybe with a cast of some sort.
470 //
471 // SAFETY: `ZeroablePrimitive` guarantees that the size and bit validity
472 // of `.0` is such that this transmute is sound.
473 unsafe { intrinsics::transmute_unchecked(self) }
474 }
475}
476
477macro_rules! nonzero_integer {
478 (
479 #[$stability:meta]
480 Self = $Ty:ident,
481 Primitive = $signedness:ident $Int:ident,
482 SignedPrimitive = $Sint:ty,
483 UnsignedPrimitive = $Uint:ty,
484
485 // Used in doc comments.
486 rot = $rot:literal,
487 rot_op = $rot_op:literal,
488 rot_result = $rot_result:literal,
489 swap_op = $swap_op:literal,
490 swapped = $swapped:literal,
491 reversed = $reversed:literal,
492 leading_zeros_test = $leading_zeros_test:expr,
493 ) => {
494 #[doc = sign_dependent_expr!{
495 $signedness ?
496 if signed {
497 concat!("An [`", stringify!($Int), "`] that is known not to equal zero.")
498 }
499 if unsigned {
500 concat!("A [`", stringify!($Int), "`] that is known not to equal zero.")
501 }
502 }]
503 ///
504 /// This enables some memory layout optimization.
505 #[doc = concat!("For example, `Option<", stringify!($Ty), ">` is the same size as `", stringify!($Int), "`:")]
506 ///
507 /// ```rust
508 #[doc = concat!("assert_eq!(size_of::<Option<core::num::", stringify!($Ty), ">>(), size_of::<", stringify!($Int), ">());")]
509 /// ```
510 ///
511 /// # Layout
512 ///
513 #[doc = concat!("`", stringify!($Ty), "` is guaranteed to have the same layout and bit validity as `", stringify!($Int), "`")]
514 /// with the exception that `0` is not a valid instance.
515 #[doc = concat!("`Option<", stringify!($Ty), ">` is guaranteed to be compatible with `", stringify!($Int), "`,")]
516 /// including in FFI.
517 ///
518 /// Thanks to the [null pointer optimization],
519 #[doc = concat!("`", stringify!($Ty), "` and `Option<", stringify!($Ty), ">`")]
520 /// are guaranteed to have the same size and alignment:
521 ///
522 /// ```
523 #[doc = concat!("use std::num::", stringify!($Ty), ";")]
524 ///
525 #[doc = concat!("assert_eq!(size_of::<", stringify!($Ty), ">(), size_of::<Option<", stringify!($Ty), ">>());")]
526 #[doc = concat!("assert_eq!(align_of::<", stringify!($Ty), ">(), align_of::<Option<", stringify!($Ty), ">>());")]
527 /// ```
528 ///
529 /// [null pointer optimization]: crate::option#representation
530 #[$stability]
531 pub type $Ty = NonZero<$Int>;
532
533 impl NonZero<$Int> {
534 /// The size of this non-zero integer type in bits.
535 ///
536 #[doc = concat!("This value is equal to [`", stringify!($Int), "::BITS`].")]
537 ///
538 /// # Examples
539 ///
540 /// ```
541 /// # use std::num::NonZero;
542 /// #
543 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::BITS, ", stringify!($Int), "::BITS);")]
544 /// ```
545 #[stable(feature = "nonzero_bits", since = "1.67.0")]
546 pub const BITS: u32 = <$Int>::BITS;
547
548 /// Returns the number of leading zeros in the binary representation of `self`.
549 ///
550 /// On many architectures, this function can perform better than `leading_zeros()` on the underlying integer type, as special handling of zero can be avoided.
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// # use std::num::NonZero;
556 /// #
557 /// # fn main() { test().unwrap(); }
558 /// # fn test() -> Option<()> {
559 #[doc = concat!("let n = NonZero::<", stringify!($Int), ">::new(", $leading_zeros_test, ")?;")]
560 ///
561 /// assert_eq!(n.leading_zeros(), 0);
562 /// # Some(())
563 /// # }
564 /// ```
565 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
566 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
567 #[must_use = "this returns the result of the operation, \
568 without modifying the original"]
569 #[inline]
570 pub const fn leading_zeros(self) -> u32 {
571 // SAFETY: since `self` cannot be zero, it is safe to call `ctlz_nonzero`.
572 unsafe {
573 intrinsics::ctlz_nonzero(self.get() as $Uint)
574 }
575 }
576
577 /// Returns the number of trailing zeros in the binary representation
578 /// of `self`.
579 ///
580 /// On many architectures, this function can perform better than `trailing_zeros()` on the underlying integer type, as special handling of zero can be avoided.
581 ///
582 /// # Examples
583 ///
584 /// ```
585 /// # use std::num::NonZero;
586 /// #
587 /// # fn main() { test().unwrap(); }
588 /// # fn test() -> Option<()> {
589 #[doc = concat!("let n = NonZero::<", stringify!($Int), ">::new(0b0101000)?;")]
590 ///
591 /// assert_eq!(n.trailing_zeros(), 3);
592 /// # Some(())
593 /// # }
594 /// ```
595 #[stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
596 #[rustc_const_stable(feature = "nonzero_leading_trailing_zeros", since = "1.53.0")]
597 #[must_use = "this returns the result of the operation, \
598 without modifying the original"]
599 #[inline]
600 pub const fn trailing_zeros(self) -> u32 {
601 // SAFETY: since `self` cannot be zero, it is safe to call `cttz_nonzero`.
602 unsafe {
603 intrinsics::cttz_nonzero(self.get() as $Uint)
604 }
605 }
606
607 /// Returns `self` with only the most significant bit set.
608 ///
609 /// # Example
610 ///
611 /// ```
612 /// #![feature(isolate_most_least_significant_one)]
613 ///
614 /// # use core::num::NonZero;
615 /// # fn main() { test().unwrap(); }
616 /// # fn test() -> Option<()> {
617 #[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b_01100100)?;")]
618 #[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b_01000000)?;")]
619 ///
620 /// assert_eq!(a.isolate_most_significant_one(), b);
621 /// # Some(())
622 /// # }
623 /// ```
624 #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")]
625 #[must_use = "this returns the result of the operation, \
626 without modifying the original"]
627 #[inline(always)]
628 pub const fn isolate_most_significant_one(self) -> Self {
629 let n = self.get() & (((1 as $Int) << (<$Int>::BITS - 1)).wrapping_shr(self.leading_zeros()));
630
631 // SAFETY:
632 // `self` is non-zero, so masking to preserve only the most
633 // significant set bit will result in a non-zero `n`.
634 unsafe { NonZero::new_unchecked(n) }
635 }
636
637 /// Returns `self` with only the least significant bit set.
638 ///
639 /// # Example
640 ///
641 /// ```
642 /// #![feature(isolate_most_least_significant_one)]
643 ///
644 /// # use core::num::NonZero;
645 /// # fn main() { test().unwrap(); }
646 /// # fn test() -> Option<()> {
647 #[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b_01100100)?;")]
648 #[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b_00000100)?;")]
649 ///
650 /// assert_eq!(a.isolate_least_significant_one(), b);
651 /// # Some(())
652 /// # }
653 /// ```
654 #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")]
655 #[must_use = "this returns the result of the operation, \
656 without modifying the original"]
657 #[inline(always)]
658 pub const fn isolate_least_significant_one(self) -> Self {
659 let n = self.get();
660 let n = n & n.wrapping_neg();
661
662 // SAFETY: `self` is non-zero, so `self` with only its least
663 // significant set bit will remain non-zero.
664 unsafe { NonZero::new_unchecked(n) }
665 }
666
667 /// Returns the number of ones in the binary representation of `self`.
668 ///
669 /// # Examples
670 ///
671 /// ```
672 /// # use std::num::NonZero;
673 /// #
674 /// # fn main() { test().unwrap(); }
675 /// # fn test() -> Option<()> {
676 #[doc = concat!("let a = NonZero::<", stringify!($Int), ">::new(0b100_0000)?;")]
677 #[doc = concat!("let b = NonZero::<", stringify!($Int), ">::new(0b100_0011)?;")]
678 ///
679 /// assert_eq!(a.count_ones(), NonZero::new(1)?);
680 /// assert_eq!(b.count_ones(), NonZero::new(3)?);
681 /// # Some(())
682 /// # }
683 /// ```
684 ///
685 #[stable(feature = "non_zero_count_ones", since = "1.86.0")]
686 #[rustc_const_stable(feature = "non_zero_count_ones", since = "1.86.0")]
687 #[doc(alias = "popcount")]
688 #[doc(alias = "popcnt")]
689 #[must_use = "this returns the result of the operation, \
690 without modifying the original"]
691 #[inline(always)]
692 pub const fn count_ones(self) -> NonZero<u32> {
693 // SAFETY:
694 // `self` is non-zero, which means it has at least one bit set, which means
695 // that the result of `count_ones` is non-zero.
696 unsafe { NonZero::new_unchecked(self.get().count_ones()) }
697 }
698
699 /// Shifts the bits to the left by a specified amount, `n`,
700 /// wrapping the truncated bits to the end of the resulting integer.
701 ///
702 /// Please note this isn't the same operation as the `<<` shifting operator!
703 ///
704 /// # Examples
705 ///
706 /// ```
707 /// #![feature(nonzero_bitwise)]
708 /// # use std::num::NonZero;
709 /// #
710 /// # fn main() { test().unwrap(); }
711 /// # fn test() -> Option<()> {
712 #[doc = concat!("let n = NonZero::new(", $rot_op, stringify!($Int), ")?;")]
713 #[doc = concat!("let m = NonZero::new(", $rot_result, ")?;")]
714 ///
715 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
716 /// # Some(())
717 /// # }
718 /// ```
719 #[unstable(feature = "nonzero_bitwise", issue = "128281")]
720 #[must_use = "this returns the result of the operation, \
721 without modifying the original"]
722 #[inline(always)]
723 pub const fn rotate_left(self, n: u32) -> Self {
724 let result = self.get().rotate_left(n);
725 // SAFETY: Rotating bits preserves the property int > 0.
726 unsafe { Self::new_unchecked(result) }
727 }
728
729 /// Shifts the bits to the right by a specified amount, `n`,
730 /// wrapping the truncated bits to the beginning of the resulting
731 /// integer.
732 ///
733 /// Please note this isn't the same operation as the `>>` shifting operator!
734 ///
735 /// # Examples
736 ///
737 /// ```
738 /// #![feature(nonzero_bitwise)]
739 /// # use std::num::NonZero;
740 /// #
741 /// # fn main() { test().unwrap(); }
742 /// # fn test() -> Option<()> {
743 #[doc = concat!("let n = NonZero::new(", $rot_result, stringify!($Int), ")?;")]
744 #[doc = concat!("let m = NonZero::new(", $rot_op, ")?;")]
745 ///
746 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
747 /// # Some(())
748 /// # }
749 /// ```
750 #[unstable(feature = "nonzero_bitwise", issue = "128281")]
751 #[must_use = "this returns the result of the operation, \
752 without modifying the original"]
753 #[inline(always)]
754 pub const fn rotate_right(self, n: u32) -> Self {
755 let result = self.get().rotate_right(n);
756 // SAFETY: Rotating bits preserves the property int > 0.
757 unsafe { Self::new_unchecked(result) }
758 }
759
760 /// Reverses the byte order of the integer.
761 ///
762 /// # Examples
763 ///
764 /// ```
765 /// #![feature(nonzero_bitwise)]
766 /// # use std::num::NonZero;
767 /// #
768 /// # fn main() { test().unwrap(); }
769 /// # fn test() -> Option<()> {
770 #[doc = concat!("let n = NonZero::new(", $swap_op, stringify!($Int), ")?;")]
771 /// let m = n.swap_bytes();
772 ///
773 #[doc = concat!("assert_eq!(m, NonZero::new(", $swapped, ")?);")]
774 /// # Some(())
775 /// # }
776 /// ```
777 #[unstable(feature = "nonzero_bitwise", issue = "128281")]
778 #[must_use = "this returns the result of the operation, \
779 without modifying the original"]
780 #[inline(always)]
781 pub const fn swap_bytes(self) -> Self {
782 let result = self.get().swap_bytes();
783 // SAFETY: Shuffling bytes preserves the property int > 0.
784 unsafe { Self::new_unchecked(result) }
785 }
786
787 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
788 /// second least-significant bit becomes second most-significant bit, etc.
789 ///
790 /// # Examples
791 ///
792 /// ```
793 /// #![feature(nonzero_bitwise)]
794 /// # use std::num::NonZero;
795 /// #
796 /// # fn main() { test().unwrap(); }
797 /// # fn test() -> Option<()> {
798 #[doc = concat!("let n = NonZero::new(", $swap_op, stringify!($Int), ")?;")]
799 /// let m = n.reverse_bits();
800 ///
801 #[doc = concat!("assert_eq!(m, NonZero::new(", $reversed, ")?);")]
802 /// # Some(())
803 /// # }
804 /// ```
805 #[unstable(feature = "nonzero_bitwise", issue = "128281")]
806 #[must_use = "this returns the result of the operation, \
807 without modifying the original"]
808 #[inline(always)]
809 pub const fn reverse_bits(self) -> Self {
810 let result = self.get().reverse_bits();
811 // SAFETY: Reversing bits preserves the property int > 0.
812 unsafe { Self::new_unchecked(result) }
813 }
814
815 /// Converts an integer from big endian to the target's endianness.
816 ///
817 /// On big endian this is a no-op. On little endian the bytes are
818 /// swapped.
819 ///
820 /// # Examples
821 ///
822 /// ```
823 /// #![feature(nonzero_bitwise)]
824 /// # use std::num::NonZero;
825 #[doc = concat!("use std::num::", stringify!($Ty), ";")]
826 /// #
827 /// # fn main() { test().unwrap(); }
828 /// # fn test() -> Option<()> {
829 #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")]
830 ///
831 /// if cfg!(target_endian = "big") {
832 #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_be(n), n)")]
833 /// } else {
834 #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_be(n), n.swap_bytes())")]
835 /// }
836 /// # Some(())
837 /// # }
838 /// ```
839 #[unstable(feature = "nonzero_bitwise", issue = "128281")]
840 #[must_use]
841 #[inline(always)]
842 pub const fn from_be(x: Self) -> Self {
843 let result = $Int::from_be(x.get());
844 // SAFETY: Shuffling bytes preserves the property int > 0.
845 unsafe { Self::new_unchecked(result) }
846 }
847
848 /// Converts an integer from little endian to the target's endianness.
849 ///
850 /// On little endian this is a no-op. On big endian the bytes are
851 /// swapped.
852 ///
853 /// # Examples
854 ///
855 /// ```
856 /// #![feature(nonzero_bitwise)]
857 /// # use std::num::NonZero;
858 #[doc = concat!("use std::num::", stringify!($Ty), ";")]
859 /// #
860 /// # fn main() { test().unwrap(); }
861 /// # fn test() -> Option<()> {
862 #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")]
863 ///
864 /// if cfg!(target_endian = "little") {
865 #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_le(n), n)")]
866 /// } else {
867 #[doc = concat!(" assert_eq!(", stringify!($Ty), "::from_le(n), n.swap_bytes())")]
868 /// }
869 /// # Some(())
870 /// # }
871 /// ```
872 #[unstable(feature = "nonzero_bitwise", issue = "128281")]
873 #[must_use]
874 #[inline(always)]
875 pub const fn from_le(x: Self) -> Self {
876 let result = $Int::from_le(x.get());
877 // SAFETY: Shuffling bytes preserves the property int > 0.
878 unsafe { Self::new_unchecked(result) }
879 }
880
881 /// Converts `self` to big endian from the target's endianness.
882 ///
883 /// On big endian this is a no-op. On little endian the bytes are
884 /// swapped.
885 ///
886 /// # Examples
887 ///
888 /// ```
889 /// #![feature(nonzero_bitwise)]
890 /// # use std::num::NonZero;
891 /// #
892 /// # fn main() { test().unwrap(); }
893 /// # fn test() -> Option<()> {
894 #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")]
895 ///
896 /// if cfg!(target_endian = "big") {
897 /// assert_eq!(n.to_be(), n)
898 /// } else {
899 /// assert_eq!(n.to_be(), n.swap_bytes())
900 /// }
901 /// # Some(())
902 /// # }
903 /// ```
904 #[unstable(feature = "nonzero_bitwise", issue = "128281")]
905 #[must_use = "this returns the result of the operation, \
906 without modifying the original"]
907 #[inline(always)]
908 pub const fn to_be(self) -> Self {
909 let result = self.get().to_be();
910 // SAFETY: Shuffling bytes preserves the property int > 0.
911 unsafe { Self::new_unchecked(result) }
912 }
913
914 /// Converts `self` to little endian from the target's endianness.
915 ///
916 /// On little endian this is a no-op. On big endian the bytes are
917 /// swapped.
918 ///
919 /// # Examples
920 ///
921 /// ```
922 /// #![feature(nonzero_bitwise)]
923 /// # use std::num::NonZero;
924 /// #
925 /// # fn main() { test().unwrap(); }
926 /// # fn test() -> Option<()> {
927 #[doc = concat!("let n = NonZero::new(0x1A", stringify!($Int), ")?;")]
928 ///
929 /// if cfg!(target_endian = "little") {
930 /// assert_eq!(n.to_le(), n)
931 /// } else {
932 /// assert_eq!(n.to_le(), n.swap_bytes())
933 /// }
934 /// # Some(())
935 /// # }
936 /// ```
937 #[unstable(feature = "nonzero_bitwise", issue = "128281")]
938 #[must_use = "this returns the result of the operation, \
939 without modifying the original"]
940 #[inline(always)]
941 pub const fn to_le(self) -> Self {
942 let result = self.get().to_le();
943 // SAFETY: Shuffling bytes preserves the property int > 0.
944 unsafe { Self::new_unchecked(result) }
945 }
946
947 nonzero_integer_signedness_dependent_methods! {
948 Primitive = $signedness $Int,
949 SignedPrimitive = $Sint,
950 UnsignedPrimitive = $Uint,
951 }
952
953 /// Multiplies two non-zero integers together.
954 /// Checks for overflow and returns [`None`] on overflow.
955 /// As a consequence, the result cannot wrap to zero.
956 ///
957 /// # Examples
958 ///
959 /// ```
960 /// # use std::num::NonZero;
961 /// #
962 /// # fn main() { test().unwrap(); }
963 /// # fn test() -> Option<()> {
964 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
965 #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
966 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
967 ///
968 /// assert_eq!(Some(four), two.checked_mul(two));
969 /// assert_eq!(None, max.checked_mul(two));
970 /// # Some(())
971 /// # }
972 /// ```
973 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
974 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
975 #[must_use = "this returns the result of the operation, \
976 without modifying the original"]
977 #[inline]
978 pub const fn checked_mul(self, other: Self) -> Option<Self> {
979 if let Some(result) = self.get().checked_mul(other.get()) {
980 // SAFETY:
981 // - `checked_mul` returns `None` on overflow
982 // - `self` and `other` are non-zero
983 // - the only way to get zero from a multiplication without overflow is for one
984 // of the sides to be zero
985 //
986 // So the result cannot be zero.
987 Some(unsafe { Self::new_unchecked(result) })
988 } else {
989 None
990 }
991 }
992
993 /// Multiplies two non-zero integers together.
994 #[doc = concat!("Return [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")]
995 ///
996 /// # Examples
997 ///
998 /// ```
999 /// # use std::num::NonZero;
1000 /// #
1001 /// # fn main() { test().unwrap(); }
1002 /// # fn test() -> Option<()> {
1003 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1004 #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1005 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1006 ///
1007 /// assert_eq!(four, two.saturating_mul(two));
1008 /// assert_eq!(max, four.saturating_mul(max));
1009 /// # Some(())
1010 /// # }
1011 /// ```
1012 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1013 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1014 #[must_use = "this returns the result of the operation, \
1015 without modifying the original"]
1016 #[inline]
1017 pub const fn saturating_mul(self, other: Self) -> Self {
1018 // SAFETY:
1019 // - `saturating_mul` returns `u*::MAX`/`i*::MAX`/`i*::MIN` on overflow/underflow,
1020 // all of which are non-zero
1021 // - `self` and `other` are non-zero
1022 // - the only way to get zero from a multiplication without overflow is for one
1023 // of the sides to be zero
1024 //
1025 // So the result cannot be zero.
1026 unsafe { Self::new_unchecked(self.get().saturating_mul(other.get())) }
1027 }
1028
1029 /// Multiplies two non-zero integers together,
1030 /// assuming overflow cannot occur.
1031 /// Overflow is unchecked, and it is undefined behavior to overflow
1032 /// *even if the result would wrap to a non-zero value*.
1033 /// The behavior is undefined as soon as
1034 #[doc = sign_dependent_expr!{
1035 $signedness ?
1036 if signed {
1037 concat!("`self * rhs > ", stringify!($Int), "::MAX`, ",
1038 "or `self * rhs < ", stringify!($Int), "::MIN`.")
1039 }
1040 if unsigned {
1041 concat!("`self * rhs > ", stringify!($Int), "::MAX`.")
1042 }
1043 }]
1044 ///
1045 /// # Examples
1046 ///
1047 /// ```
1048 /// #![feature(nonzero_ops)]
1049 ///
1050 /// # use std::num::NonZero;
1051 /// #
1052 /// # fn main() { test().unwrap(); }
1053 /// # fn test() -> Option<()> {
1054 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1055 #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1056 ///
1057 /// assert_eq!(four, unsafe { two.unchecked_mul(two) });
1058 /// # Some(())
1059 /// # }
1060 /// ```
1061 #[unstable(feature = "nonzero_ops", issue = "84186")]
1062 #[must_use = "this returns the result of the operation, \
1063 without modifying the original"]
1064 #[inline]
1065 pub const unsafe fn unchecked_mul(self, other: Self) -> Self {
1066 // SAFETY: The caller ensures there is no overflow.
1067 unsafe { Self::new_unchecked(self.get().unchecked_mul(other.get())) }
1068 }
1069
1070 /// Raises non-zero value to an integer power.
1071 /// Checks for overflow and returns [`None`] on overflow.
1072 /// As a consequence, the result cannot wrap to zero.
1073 ///
1074 /// # Examples
1075 ///
1076 /// ```
1077 /// # use std::num::NonZero;
1078 /// #
1079 /// # fn main() { test().unwrap(); }
1080 /// # fn test() -> Option<()> {
1081 #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1082 #[doc = concat!("let twenty_seven = NonZero::new(27", stringify!($Int), ")?;")]
1083 #[doc = concat!("let half_max = NonZero::new(", stringify!($Int), "::MAX / 2)?;")]
1084 ///
1085 /// assert_eq!(Some(twenty_seven), three.checked_pow(3));
1086 /// assert_eq!(None, half_max.checked_pow(3));
1087 /// # Some(())
1088 /// # }
1089 /// ```
1090 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1091 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1092 #[must_use = "this returns the result of the operation, \
1093 without modifying the original"]
1094 #[inline]
1095 pub const fn checked_pow(self, other: u32) -> Option<Self> {
1096 if let Some(result) = self.get().checked_pow(other) {
1097 // SAFETY:
1098 // - `checked_pow` returns `None` on overflow/underflow
1099 // - `self` is non-zero
1100 // - the only way to get zero from an exponentiation without overflow is
1101 // for base to be zero
1102 //
1103 // So the result cannot be zero.
1104 Some(unsafe { Self::new_unchecked(result) })
1105 } else {
1106 None
1107 }
1108 }
1109
1110 /// Raise non-zero value to an integer power.
1111 #[doc = sign_dependent_expr!{
1112 $signedness ?
1113 if signed {
1114 concat!("Return [`NonZero::<", stringify!($Int), ">::MIN`] ",
1115 "or [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")
1116 }
1117 if unsigned {
1118 concat!("Return [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")
1119 }
1120 }]
1121 ///
1122 /// # Examples
1123 ///
1124 /// ```
1125 /// # use std::num::NonZero;
1126 /// #
1127 /// # fn main() { test().unwrap(); }
1128 /// # fn test() -> Option<()> {
1129 #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1130 #[doc = concat!("let twenty_seven = NonZero::new(27", stringify!($Int), ")?;")]
1131 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1132 ///
1133 /// assert_eq!(twenty_seven, three.saturating_pow(3));
1134 /// assert_eq!(max, max.saturating_pow(3));
1135 /// # Some(())
1136 /// # }
1137 /// ```
1138 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1139 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1140 #[must_use = "this returns the result of the operation, \
1141 without modifying the original"]
1142 #[inline]
1143 pub const fn saturating_pow(self, other: u32) -> Self {
1144 // SAFETY:
1145 // - `saturating_pow` returns `u*::MAX`/`i*::MAX`/`i*::MIN` on overflow/underflow,
1146 // all of which are non-zero
1147 // - `self` is non-zero
1148 // - the only way to get zero from an exponentiation without overflow is
1149 // for base to be zero
1150 //
1151 // So the result cannot be zero.
1152 unsafe { Self::new_unchecked(self.get().saturating_pow(other)) }
1153 }
1154 }
1155
1156 #[stable(feature = "nonzero_parse", since = "1.35.0")]
1157 impl FromStr for NonZero<$Int> {
1158 type Err = ParseIntError;
1159 fn from_str(src: &str) -> Result<Self, Self::Err> {
1160 Self::new(<$Int>::from_str_radix(src, 10)?)
1161 .ok_or(ParseIntError {
1162 kind: IntErrorKind::Zero
1163 })
1164 }
1165 }
1166
1167 nonzero_integer_signedness_dependent_impls!($signedness $Int);
1168 };
1169
1170 (
1171 Self = $Ty:ident,
1172 Primitive = unsigned $Int:ident,
1173 SignedPrimitive = $Sint:ident,
1174 rot = $rot:literal,
1175 rot_op = $rot_op:literal,
1176 rot_result = $rot_result:literal,
1177 swap_op = $swap_op:literal,
1178 swapped = $swapped:literal,
1179 reversed = $reversed:literal,
1180 $(,)?
1181 ) => {
1182 nonzero_integer! {
1183 #[stable(feature = "nonzero", since = "1.28.0")]
1184 Self = $Ty,
1185 Primitive = unsigned $Int,
1186 SignedPrimitive = $Sint,
1187 UnsignedPrimitive = $Int,
1188 rot = $rot,
1189 rot_op = $rot_op,
1190 rot_result = $rot_result,
1191 swap_op = $swap_op,
1192 swapped = $swapped,
1193 reversed = $reversed,
1194 leading_zeros_test = concat!(stringify!($Int), "::MAX"),
1195 }
1196 };
1197
1198 (
1199 Self = $Ty:ident,
1200 Primitive = signed $Int:ident,
1201 UnsignedPrimitive = $Uint:ident,
1202 rot = $rot:literal,
1203 rot_op = $rot_op:literal,
1204 rot_result = $rot_result:literal,
1205 swap_op = $swap_op:literal,
1206 swapped = $swapped:literal,
1207 reversed = $reversed:literal,
1208 ) => {
1209 nonzero_integer! {
1210 #[stable(feature = "signed_nonzero", since = "1.34.0")]
1211 Self = $Ty,
1212 Primitive = signed $Int,
1213 SignedPrimitive = $Int,
1214 UnsignedPrimitive = $Uint,
1215 rot = $rot,
1216 rot_op = $rot_op,
1217 rot_result = $rot_result,
1218 swap_op = $swap_op,
1219 swapped = $swapped,
1220 reversed = $reversed,
1221 leading_zeros_test = concat!("-1", stringify!($Int)),
1222 }
1223 };
1224}
1225
1226macro_rules! nonzero_integer_signedness_dependent_impls {
1227 // Impls for unsigned nonzero types only.
1228 (unsigned $Int:ty) => {
1229 #[stable(feature = "nonzero_div", since = "1.51.0")]
1230 impl Div<NonZero<$Int>> for $Int {
1231 type Output = $Int;
1232
1233 /// Same as `self / other.get()`, but because `other` is a `NonZero<_>`,
1234 /// there's never a runtime check for division-by-zero.
1235 ///
1236 /// This operation rounds towards zero, truncating any fractional
1237 /// part of the exact result, and cannot panic.
1238 #[doc(alias = "unchecked_div")]
1239 #[inline]
1240 fn div(self, other: NonZero<$Int>) -> $Int {
1241 // SAFETY: Division by zero is checked because `other` is non-zero,
1242 // and MIN/-1 is checked because `self` is an unsigned int.
1243 unsafe { intrinsics::unchecked_div(self, other.get()) }
1244 }
1245 }
1246
1247 #[stable(feature = "nonzero_div_assign", since = "1.79.0")]
1248 impl DivAssign<NonZero<$Int>> for $Int {
1249 /// Same as `self /= other.get()`, but because `other` is a `NonZero<_>`,
1250 /// there's never a runtime check for division-by-zero.
1251 ///
1252 /// This operation rounds towards zero, truncating any fractional
1253 /// part of the exact result, and cannot panic.
1254 #[inline]
1255 fn div_assign(&mut self, other: NonZero<$Int>) {
1256 *self = *self / other;
1257 }
1258 }
1259
1260 #[stable(feature = "nonzero_div", since = "1.51.0")]
1261 impl Rem<NonZero<$Int>> for $Int {
1262 type Output = $Int;
1263
1264 /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
1265 #[inline]
1266 fn rem(self, other: NonZero<$Int>) -> $Int {
1267 // SAFETY: Remainder by zero is checked because `other` is non-zero,
1268 // and MIN/-1 is checked because `self` is an unsigned int.
1269 unsafe { intrinsics::unchecked_rem(self, other.get()) }
1270 }
1271 }
1272
1273 #[stable(feature = "nonzero_div_assign", since = "1.79.0")]
1274 impl RemAssign<NonZero<$Int>> for $Int {
1275 /// This operation satisfies `n % d == n - (n / d) * d`, and cannot panic.
1276 #[inline]
1277 fn rem_assign(&mut self, other: NonZero<$Int>) {
1278 *self = *self % other;
1279 }
1280 }
1281
1282 impl NonZero<$Int> {
1283 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
1284 ///
1285 /// The result is guaranteed to be non-zero.
1286 ///
1287 /// # Examples
1288 ///
1289 /// ```
1290 /// # #![feature(unsigned_nonzero_div_ceil)]
1291 /// # use std::num::NonZero;
1292 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ").unwrap();")]
1293 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX).unwrap();")]
1294 /// assert_eq!(one.div_ceil(max), one);
1295 ///
1296 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ").unwrap();")]
1297 #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ").unwrap();")]
1298 /// assert_eq!(three.div_ceil(two), two);
1299 /// ```
1300 #[unstable(feature = "unsigned_nonzero_div_ceil", issue = "132968")]
1301 #[must_use = "this returns the result of the operation, \
1302 without modifying the original"]
1303 #[inline]
1304 pub const fn div_ceil(self, rhs: Self) -> Self {
1305 let v = self.get().div_ceil(rhs.get());
1306 // SAFETY: ceiled division of two positive integers can never be zero.
1307 unsafe { Self::new_unchecked(v) }
1308 }
1309 }
1310 };
1311 // Impls for signed nonzero types only.
1312 (signed $Int:ty) => {
1313 #[stable(feature = "signed_nonzero_neg", since = "1.71.0")]
1314 impl Neg for NonZero<$Int> {
1315 type Output = Self;
1316
1317 #[inline]
1318 fn neg(self) -> Self {
1319 // SAFETY: negation of nonzero cannot yield zero values.
1320 unsafe { Self::new_unchecked(self.get().neg()) }
1321 }
1322 }
1323
1324 forward_ref_unop! { impl Neg, neg for NonZero<$Int>,
1325 #[stable(feature = "signed_nonzero_neg", since = "1.71.0")] }
1326 };
1327}
1328
1329#[rustfmt::skip] // https://github.com/rust-lang/rustfmt/issues/5974
1330macro_rules! nonzero_integer_signedness_dependent_methods {
1331 // Associated items for unsigned nonzero types only.
1332 (
1333 Primitive = unsigned $Int:ident,
1334 SignedPrimitive = $Sint:ty,
1335 UnsignedPrimitive = $Uint:ty,
1336 ) => {
1337 /// The smallest value that can be represented by this non-zero
1338 /// integer type, 1.
1339 ///
1340 /// # Examples
1341 ///
1342 /// ```
1343 /// # use std::num::NonZero;
1344 /// #
1345 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MIN.get(), 1", stringify!($Int), ");")]
1346 /// ```
1347 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1348 pub const MIN: Self = Self::new(1).unwrap();
1349
1350 /// The largest value that can be represented by this non-zero
1351 /// integer type,
1352 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1353 ///
1354 /// # Examples
1355 ///
1356 /// ```
1357 /// # use std::num::NonZero;
1358 /// #
1359 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MAX.get(), ", stringify!($Int), "::MAX);")]
1360 /// ```
1361 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1362 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1363
1364 /// Adds an unsigned integer to a non-zero value.
1365 /// Checks for overflow and returns [`None`] on overflow.
1366 /// As a consequence, the result cannot wrap to zero.
1367 ///
1368 ///
1369 /// # Examples
1370 ///
1371 /// ```
1372 /// # use std::num::NonZero;
1373 /// #
1374 /// # fn main() { test().unwrap(); }
1375 /// # fn test() -> Option<()> {
1376 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1377 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1378 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1379 ///
1380 /// assert_eq!(Some(two), one.checked_add(1));
1381 /// assert_eq!(None, max.checked_add(1));
1382 /// # Some(())
1383 /// # }
1384 /// ```
1385 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1386 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1387 #[must_use = "this returns the result of the operation, \
1388 without modifying the original"]
1389 #[inline]
1390 pub const fn checked_add(self, other: $Int) -> Option<Self> {
1391 if let Some(result) = self.get().checked_add(other) {
1392 // SAFETY:
1393 // - `checked_add` returns `None` on overflow
1394 // - `self` is non-zero
1395 // - the only way to get zero from an addition without overflow is for both
1396 // sides to be zero
1397 //
1398 // So the result cannot be zero.
1399 Some(unsafe { Self::new_unchecked(result) })
1400 } else {
1401 None
1402 }
1403 }
1404
1405 /// Adds an unsigned integer to a non-zero value.
1406 #[doc = concat!("Return [`NonZero::<", stringify!($Int), ">::MAX`] on overflow.")]
1407 ///
1408 /// # Examples
1409 ///
1410 /// ```
1411 /// # use std::num::NonZero;
1412 /// #
1413 /// # fn main() { test().unwrap(); }
1414 /// # fn test() -> Option<()> {
1415 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1416 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1417 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1418 ///
1419 /// assert_eq!(two, one.saturating_add(1));
1420 /// assert_eq!(max, max.saturating_add(1));
1421 /// # Some(())
1422 /// # }
1423 /// ```
1424 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1425 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1426 #[must_use = "this returns the result of the operation, \
1427 without modifying the original"]
1428 #[inline]
1429 pub const fn saturating_add(self, other: $Int) -> Self {
1430 // SAFETY:
1431 // - `saturating_add` returns `u*::MAX` on overflow, which is non-zero
1432 // - `self` is non-zero
1433 // - the only way to get zero from an addition without overflow is for both
1434 // sides to be zero
1435 //
1436 // So the result cannot be zero.
1437 unsafe { Self::new_unchecked(self.get().saturating_add(other)) }
1438 }
1439
1440 /// Adds an unsigned integer to a non-zero value,
1441 /// assuming overflow cannot occur.
1442 /// Overflow is unchecked, and it is undefined behavior to overflow
1443 /// *even if the result would wrap to a non-zero value*.
1444 /// The behavior is undefined as soon as
1445 #[doc = concat!("`self + rhs > ", stringify!($Int), "::MAX`.")]
1446 ///
1447 /// # Examples
1448 ///
1449 /// ```
1450 /// #![feature(nonzero_ops)]
1451 ///
1452 /// # use std::num::NonZero;
1453 /// #
1454 /// # fn main() { test().unwrap(); }
1455 /// # fn test() -> Option<()> {
1456 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1457 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1458 ///
1459 /// assert_eq!(two, unsafe { one.unchecked_add(1) });
1460 /// # Some(())
1461 /// # }
1462 /// ```
1463 #[unstable(feature = "nonzero_ops", issue = "84186")]
1464 #[must_use = "this returns the result of the operation, \
1465 without modifying the original"]
1466 #[inline]
1467 pub const unsafe fn unchecked_add(self, other: $Int) -> Self {
1468 // SAFETY: The caller ensures there is no overflow.
1469 unsafe { Self::new_unchecked(self.get().unchecked_add(other)) }
1470 }
1471
1472 /// Returns the smallest power of two greater than or equal to `self`.
1473 /// Checks for overflow and returns [`None`]
1474 /// if the next power of two is greater than the type’s maximum value.
1475 /// As a consequence, the result cannot wrap to zero.
1476 ///
1477 /// # Examples
1478 ///
1479 /// ```
1480 /// # use std::num::NonZero;
1481 /// #
1482 /// # fn main() { test().unwrap(); }
1483 /// # fn test() -> Option<()> {
1484 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1485 #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1486 #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1487 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1488 ///
1489 /// assert_eq!(Some(two), two.checked_next_power_of_two() );
1490 /// assert_eq!(Some(four), three.checked_next_power_of_two() );
1491 /// assert_eq!(None, max.checked_next_power_of_two() );
1492 /// # Some(())
1493 /// # }
1494 /// ```
1495 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1496 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1497 #[must_use = "this returns the result of the operation, \
1498 without modifying the original"]
1499 #[inline]
1500 pub const fn checked_next_power_of_two(self) -> Option<Self> {
1501 if let Some(nz) = self.get().checked_next_power_of_two() {
1502 // SAFETY: The next power of two is positive
1503 // and overflow is checked.
1504 Some(unsafe { Self::new_unchecked(nz) })
1505 } else {
1506 None
1507 }
1508 }
1509
1510 /// Returns the base 2 logarithm of the number, rounded down.
1511 ///
1512 /// This is the same operation as
1513 #[doc = concat!("[`", stringify!($Int), "::ilog2`],")]
1514 /// except that it has no failure cases to worry about
1515 /// since this value can never be zero.
1516 ///
1517 /// # Examples
1518 ///
1519 /// ```
1520 /// # use std::num::NonZero;
1521 /// #
1522 /// # fn main() { test().unwrap(); }
1523 /// # fn test() -> Option<()> {
1524 #[doc = concat!("assert_eq!(NonZero::new(7", stringify!($Int), ")?.ilog2(), 2);")]
1525 #[doc = concat!("assert_eq!(NonZero::new(8", stringify!($Int), ")?.ilog2(), 3);")]
1526 #[doc = concat!("assert_eq!(NonZero::new(9", stringify!($Int), ")?.ilog2(), 3);")]
1527 /// # Some(())
1528 /// # }
1529 /// ```
1530 #[stable(feature = "int_log", since = "1.67.0")]
1531 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1532 #[must_use = "this returns the result of the operation, \
1533 without modifying the original"]
1534 #[inline]
1535 pub const fn ilog2(self) -> u32 {
1536 Self::BITS - 1 - self.leading_zeros()
1537 }
1538
1539 /// Returns the base 10 logarithm of the number, rounded down.
1540 ///
1541 /// This is the same operation as
1542 #[doc = concat!("[`", stringify!($Int), "::ilog10`],")]
1543 /// except that it has no failure cases to worry about
1544 /// since this value can never be zero.
1545 ///
1546 /// # Examples
1547 ///
1548 /// ```
1549 /// # use std::num::NonZero;
1550 /// #
1551 /// # fn main() { test().unwrap(); }
1552 /// # fn test() -> Option<()> {
1553 #[doc = concat!("assert_eq!(NonZero::new(99", stringify!($Int), ")?.ilog10(), 1);")]
1554 #[doc = concat!("assert_eq!(NonZero::new(100", stringify!($Int), ")?.ilog10(), 2);")]
1555 #[doc = concat!("assert_eq!(NonZero::new(101", stringify!($Int), ")?.ilog10(), 2);")]
1556 /// # Some(())
1557 /// # }
1558 /// ```
1559 #[stable(feature = "int_log", since = "1.67.0")]
1560 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1561 #[must_use = "this returns the result of the operation, \
1562 without modifying the original"]
1563 #[inline]
1564 pub const fn ilog10(self) -> u32 {
1565 super::int_log10::$Int(self.get())
1566 }
1567
1568 /// Calculates the midpoint (average) between `self` and `rhs`.
1569 ///
1570 /// `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a
1571 /// sufficiently-large signed integral type. This implies that the result is
1572 /// always rounded towards negative infinity and that no overflow will ever occur.
1573 ///
1574 /// # Examples
1575 ///
1576 /// ```
1577 /// # use std::num::NonZero;
1578 /// #
1579 /// # fn main() { test().unwrap(); }
1580 /// # fn test() -> Option<()> {
1581 #[doc = concat!("let one = NonZero::new(1", stringify!($Int), ")?;")]
1582 #[doc = concat!("let two = NonZero::new(2", stringify!($Int), ")?;")]
1583 #[doc = concat!("let four = NonZero::new(4", stringify!($Int), ")?;")]
1584 ///
1585 /// assert_eq!(one.midpoint(four), two);
1586 /// assert_eq!(four.midpoint(one), two);
1587 /// # Some(())
1588 /// # }
1589 /// ```
1590 #[stable(feature = "num_midpoint", since = "1.85.0")]
1591 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1592 #[must_use = "this returns the result of the operation, \
1593 without modifying the original"]
1594 #[doc(alias = "average_floor")]
1595 #[doc(alias = "average")]
1596 #[inline]
1597 pub const fn midpoint(self, rhs: Self) -> Self {
1598 // SAFETY: The only way to get `0` with midpoint is to have two opposite or
1599 // near opposite numbers: (-5, 5), (0, 1), (0, 0) which is impossible because
1600 // of the unsignedness of this number and also because `Self` is guaranteed to
1601 // never being 0.
1602 unsafe { Self::new_unchecked(self.get().midpoint(rhs.get())) }
1603 }
1604
1605 /// Returns `true` if and only if `self == (1 << k)` for some `k`.
1606 ///
1607 /// On many architectures, this function can perform better than `is_power_of_two()`
1608 /// on the underlying integer type, as special handling of zero can be avoided.
1609 ///
1610 /// # Examples
1611 ///
1612 /// ```
1613 /// # use std::num::NonZero;
1614 /// #
1615 /// # fn main() { test().unwrap(); }
1616 /// # fn test() -> Option<()> {
1617 #[doc = concat!("let eight = NonZero::new(8", stringify!($Int), ")?;")]
1618 /// assert!(eight.is_power_of_two());
1619 #[doc = concat!("let ten = NonZero::new(10", stringify!($Int), ")?;")]
1620 /// assert!(!ten.is_power_of_two());
1621 /// # Some(())
1622 /// # }
1623 /// ```
1624 #[must_use]
1625 #[stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1626 #[rustc_const_stable(feature = "nonzero_is_power_of_two", since = "1.59.0")]
1627 #[inline]
1628 pub const fn is_power_of_two(self) -> bool {
1629 // LLVM 11 normalizes `unchecked_sub(x, 1) & x == 0` to the implementation seen here.
1630 // On the basic x86-64 target, this saves 3 instructions for the zero check.
1631 // On x86_64 with BMI1, being nonzero lets it codegen to `BLSR`, which saves an instruction
1632 // compared to the `POPCNT` implementation on the underlying integer type.
1633
1634 intrinsics::ctpop(self.get()) < 2
1635 }
1636
1637 /// Returns the square root of the number, rounded down.
1638 ///
1639 /// # Examples
1640 ///
1641 /// ```
1642 /// # use std::num::NonZero;
1643 /// #
1644 /// # fn main() { test().unwrap(); }
1645 /// # fn test() -> Option<()> {
1646 #[doc = concat!("let ten = NonZero::new(10", stringify!($Int), ")?;")]
1647 #[doc = concat!("let three = NonZero::new(3", stringify!($Int), ")?;")]
1648 ///
1649 /// assert_eq!(ten.isqrt(), three);
1650 /// # Some(())
1651 /// # }
1652 /// ```
1653 #[stable(feature = "isqrt", since = "1.84.0")]
1654 #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
1655 #[must_use = "this returns the result of the operation, \
1656 without modifying the original"]
1657 #[inline]
1658 pub const fn isqrt(self) -> Self {
1659 let result = self.get().isqrt();
1660
1661 // SAFETY: Integer square root is a monotonically nondecreasing
1662 // function, which means that increasing the input will never cause
1663 // the output to decrease. Thus, since the input for nonzero
1664 // unsigned integers has a lower bound of 1, the lower bound of the
1665 // results will be sqrt(1), which is 1, so a result can't be zero.
1666 unsafe { Self::new_unchecked(result) }
1667 }
1668
1669 /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
1670 ///
1671 /// # Examples
1672 ///
1673 /// ```
1674 /// # use std::num::NonZero;
1675 ///
1676 #[doc = concat!("let n = NonZero::<", stringify!($Int), ">::MAX;")]
1677 ///
1678 #[doc = concat!("assert_eq!(n.cast_signed(), NonZero::new(-1", stringify!($Sint), ").unwrap());")]
1679 /// ```
1680 #[stable(feature = "integer_sign_cast", since = "1.87.0")]
1681 #[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
1682 #[must_use = "this returns the result of the operation, \
1683 without modifying the original"]
1684 #[inline(always)]
1685 pub const fn cast_signed(self) -> NonZero<$Sint> {
1686 // SAFETY: `self.get()` can't be zero
1687 unsafe { NonZero::new_unchecked(self.get().cast_signed()) }
1688 }
1689 };
1690
1691 // Associated items for signed nonzero types only.
1692 (
1693 Primitive = signed $Int:ident,
1694 SignedPrimitive = $Sint:ty,
1695 UnsignedPrimitive = $Uint:ty,
1696 ) => {
1697 /// The smallest value that can be represented by this non-zero
1698 /// integer type,
1699 #[doc = concat!("equal to [`", stringify!($Int), "::MIN`].")]
1700 ///
1701 /// Note: While most integer types are defined for every whole
1702 /// number between `MIN` and `MAX`, signed non-zero integers are
1703 /// a special case. They have a "gap" at 0.
1704 ///
1705 /// # Examples
1706 ///
1707 /// ```
1708 /// # use std::num::NonZero;
1709 /// #
1710 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MIN.get(), ", stringify!($Int), "::MIN);")]
1711 /// ```
1712 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1713 pub const MIN: Self = Self::new(<$Int>::MIN).unwrap();
1714
1715 /// The largest value that can be represented by this non-zero
1716 /// integer type,
1717 #[doc = concat!("equal to [`", stringify!($Int), "::MAX`].")]
1718 ///
1719 /// Note: While most integer types are defined for every whole
1720 /// number between `MIN` and `MAX`, signed non-zero integers are
1721 /// a special case. They have a "gap" at 0.
1722 ///
1723 /// # Examples
1724 ///
1725 /// ```
1726 /// # use std::num::NonZero;
1727 /// #
1728 #[doc = concat!("assert_eq!(NonZero::<", stringify!($Int), ">::MAX.get(), ", stringify!($Int), "::MAX);")]
1729 /// ```
1730 #[stable(feature = "nonzero_min_max", since = "1.70.0")]
1731 pub const MAX: Self = Self::new(<$Int>::MAX).unwrap();
1732
1733 /// Computes the absolute value of self.
1734 #[doc = concat!("See [`", stringify!($Int), "::abs`]")]
1735 /// for documentation on overflow behavior.
1736 ///
1737 /// # Example
1738 ///
1739 /// ```
1740 /// # use std::num::NonZero;
1741 /// #
1742 /// # fn main() { test().unwrap(); }
1743 /// # fn test() -> Option<()> {
1744 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1745 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1746 ///
1747 /// assert_eq!(pos, pos.abs());
1748 /// assert_eq!(pos, neg.abs());
1749 /// # Some(())
1750 /// # }
1751 /// ```
1752 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1753 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1754 #[must_use = "this returns the result of the operation, \
1755 without modifying the original"]
1756 #[inline]
1757 pub const fn abs(self) -> Self {
1758 // SAFETY: This cannot overflow to zero.
1759 unsafe { Self::new_unchecked(self.get().abs()) }
1760 }
1761
1762 /// Checked absolute value.
1763 /// Checks for overflow and returns [`None`] if
1764 #[doc = concat!("`self == NonZero::<", stringify!($Int), ">::MIN`.")]
1765 /// The result cannot be zero.
1766 ///
1767 /// # Example
1768 ///
1769 /// ```
1770 /// # use std::num::NonZero;
1771 /// #
1772 /// # fn main() { test().unwrap(); }
1773 /// # fn test() -> Option<()> {
1774 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1775 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1776 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1777 ///
1778 /// assert_eq!(Some(pos), neg.checked_abs());
1779 /// assert_eq!(None, min.checked_abs());
1780 /// # Some(())
1781 /// # }
1782 /// ```
1783 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1784 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1785 #[must_use = "this returns the result of the operation, \
1786 without modifying the original"]
1787 #[inline]
1788 pub const fn checked_abs(self) -> Option<Self> {
1789 if let Some(nz) = self.get().checked_abs() {
1790 // SAFETY: absolute value of nonzero cannot yield zero values.
1791 Some(unsafe { Self::new_unchecked(nz) })
1792 } else {
1793 None
1794 }
1795 }
1796
1797 /// Computes the absolute value of self,
1798 /// with overflow information, see
1799 #[doc = concat!("[`", stringify!($Int), "::overflowing_abs`].")]
1800 ///
1801 /// # Example
1802 ///
1803 /// ```
1804 /// # use std::num::NonZero;
1805 /// #
1806 /// # fn main() { test().unwrap(); }
1807 /// # fn test() -> Option<()> {
1808 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1809 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1810 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1811 ///
1812 /// assert_eq!((pos, false), pos.overflowing_abs());
1813 /// assert_eq!((pos, false), neg.overflowing_abs());
1814 /// assert_eq!((min, true), min.overflowing_abs());
1815 /// # Some(())
1816 /// # }
1817 /// ```
1818 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1819 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1820 #[must_use = "this returns the result of the operation, \
1821 without modifying the original"]
1822 #[inline]
1823 pub const fn overflowing_abs(self) -> (Self, bool) {
1824 let (nz, flag) = self.get().overflowing_abs();
1825 (
1826 // SAFETY: absolute value of nonzero cannot yield zero values.
1827 unsafe { Self::new_unchecked(nz) },
1828 flag,
1829 )
1830 }
1831
1832 /// Saturating absolute value, see
1833 #[doc = concat!("[`", stringify!($Int), "::saturating_abs`].")]
1834 ///
1835 /// # Example
1836 ///
1837 /// ```
1838 /// # use std::num::NonZero;
1839 /// #
1840 /// # fn main() { test().unwrap(); }
1841 /// # fn test() -> Option<()> {
1842 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1843 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1844 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1845 #[doc = concat!("let min_plus = NonZero::new(", stringify!($Int), "::MIN + 1)?;")]
1846 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1847 ///
1848 /// assert_eq!(pos, pos.saturating_abs());
1849 /// assert_eq!(pos, neg.saturating_abs());
1850 /// assert_eq!(max, min.saturating_abs());
1851 /// assert_eq!(max, min_plus.saturating_abs());
1852 /// # Some(())
1853 /// # }
1854 /// ```
1855 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1856 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1857 #[must_use = "this returns the result of the operation, \
1858 without modifying the original"]
1859 #[inline]
1860 pub const fn saturating_abs(self) -> Self {
1861 // SAFETY: absolute value of nonzero cannot yield zero values.
1862 unsafe { Self::new_unchecked(self.get().saturating_abs()) }
1863 }
1864
1865 /// Wrapping absolute value, see
1866 #[doc = concat!("[`", stringify!($Int), "::wrapping_abs`].")]
1867 ///
1868 /// # Example
1869 ///
1870 /// ```
1871 /// # use std::num::NonZero;
1872 /// #
1873 /// # fn main() { test().unwrap(); }
1874 /// # fn test() -> Option<()> {
1875 #[doc = concat!("let pos = NonZero::new(1", stringify!($Int), ")?;")]
1876 #[doc = concat!("let neg = NonZero::new(-1", stringify!($Int), ")?;")]
1877 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1878 #[doc = concat!("# let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
1879 ///
1880 /// assert_eq!(pos, pos.wrapping_abs());
1881 /// assert_eq!(pos, neg.wrapping_abs());
1882 /// assert_eq!(min, min.wrapping_abs());
1883 /// assert_eq!(max, (-max).wrapping_abs());
1884 /// # Some(())
1885 /// # }
1886 /// ```
1887 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1888 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1889 #[must_use = "this returns the result of the operation, \
1890 without modifying the original"]
1891 #[inline]
1892 pub const fn wrapping_abs(self) -> Self {
1893 // SAFETY: absolute value of nonzero cannot yield zero values.
1894 unsafe { Self::new_unchecked(self.get().wrapping_abs()) }
1895 }
1896
1897 /// Computes the absolute value of self
1898 /// without any wrapping or panicking.
1899 ///
1900 /// # Example
1901 ///
1902 /// ```
1903 /// # use std::num::NonZero;
1904 /// #
1905 /// # fn main() { test().unwrap(); }
1906 /// # fn test() -> Option<()> {
1907 #[doc = concat!("let u_pos = NonZero::new(1", stringify!($Uint), ")?;")]
1908 #[doc = concat!("let i_pos = NonZero::new(1", stringify!($Int), ")?;")]
1909 #[doc = concat!("let i_neg = NonZero::new(-1", stringify!($Int), ")?;")]
1910 #[doc = concat!("let i_min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1911 #[doc = concat!("let u_max = NonZero::new(", stringify!($Uint), "::MAX / 2 + 1)?;")]
1912 ///
1913 /// assert_eq!(u_pos, i_pos.unsigned_abs());
1914 /// assert_eq!(u_pos, i_neg.unsigned_abs());
1915 /// assert_eq!(u_max, i_min.unsigned_abs());
1916 /// # Some(())
1917 /// # }
1918 /// ```
1919 #[stable(feature = "nonzero_checked_ops", since = "1.64.0")]
1920 #[rustc_const_stable(feature = "const_nonzero_checked_ops", since = "1.64.0")]
1921 #[must_use = "this returns the result of the operation, \
1922 without modifying the original"]
1923 #[inline]
1924 pub const fn unsigned_abs(self) -> NonZero<$Uint> {
1925 // SAFETY: absolute value of nonzero cannot yield zero values.
1926 unsafe { NonZero::new_unchecked(self.get().unsigned_abs()) }
1927 }
1928
1929 /// Returns `true` if `self` is positive and `false` if the
1930 /// number is negative.
1931 ///
1932 /// # Example
1933 ///
1934 /// ```
1935 /// # use std::num::NonZero;
1936 /// #
1937 /// # fn main() { test().unwrap(); }
1938 /// # fn test() -> Option<()> {
1939 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
1940 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
1941 ///
1942 /// assert!(pos_five.is_positive());
1943 /// assert!(!neg_five.is_positive());
1944 /// # Some(())
1945 /// # }
1946 /// ```
1947 #[must_use]
1948 #[inline]
1949 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1950 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1951 pub const fn is_positive(self) -> bool {
1952 self.get().is_positive()
1953 }
1954
1955 /// Returns `true` if `self` is negative and `false` if the
1956 /// number is positive.
1957 ///
1958 /// # Example
1959 ///
1960 /// ```
1961 /// # use std::num::NonZero;
1962 /// #
1963 /// # fn main() { test().unwrap(); }
1964 /// # fn test() -> Option<()> {
1965 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
1966 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
1967 ///
1968 /// assert!(neg_five.is_negative());
1969 /// assert!(!pos_five.is_negative());
1970 /// # Some(())
1971 /// # }
1972 /// ```
1973 #[must_use]
1974 #[inline]
1975 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1976 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
1977 pub const fn is_negative(self) -> bool {
1978 self.get().is_negative()
1979 }
1980
1981 /// Checked negation. Computes `-self`,
1982 #[doc = concat!("returning `None` if `self == NonZero::<", stringify!($Int), ">::MIN`.")]
1983 ///
1984 /// # Example
1985 ///
1986 /// ```
1987 /// # use std::num::NonZero;
1988 /// #
1989 /// # fn main() { test().unwrap(); }
1990 /// # fn test() -> Option<()> {
1991 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
1992 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
1993 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
1994 ///
1995 /// assert_eq!(pos_five.checked_neg(), Some(neg_five));
1996 /// assert_eq!(min.checked_neg(), None);
1997 /// # Some(())
1998 /// # }
1999 /// ```
2000 #[inline]
2001 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2002 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2003 pub const fn checked_neg(self) -> Option<Self> {
2004 if let Some(result) = self.get().checked_neg() {
2005 // SAFETY: negation of nonzero cannot yield zero values.
2006 return Some(unsafe { Self::new_unchecked(result) });
2007 }
2008 None
2009 }
2010
2011 /// Negates self, overflowing if this is equal to the minimum value.
2012 ///
2013 #[doc = concat!("See [`", stringify!($Int), "::overflowing_neg`]")]
2014 /// for documentation on overflow behavior.
2015 ///
2016 /// # Example
2017 ///
2018 /// ```
2019 /// # use std::num::NonZero;
2020 /// #
2021 /// # fn main() { test().unwrap(); }
2022 /// # fn test() -> Option<()> {
2023 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2024 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2025 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2026 ///
2027 /// assert_eq!(pos_five.overflowing_neg(), (neg_five, false));
2028 /// assert_eq!(min.overflowing_neg(), (min, true));
2029 /// # Some(())
2030 /// # }
2031 /// ```
2032 #[inline]
2033 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2034 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2035 pub const fn overflowing_neg(self) -> (Self, bool) {
2036 let (result, overflow) = self.get().overflowing_neg();
2037 // SAFETY: negation of nonzero cannot yield zero values.
2038 ((unsafe { Self::new_unchecked(result) }), overflow)
2039 }
2040
2041 /// Saturating negation. Computes `-self`,
2042 #[doc = concat!("returning [`NonZero::<", stringify!($Int), ">::MAX`]")]
2043 #[doc = concat!("if `self == NonZero::<", stringify!($Int), ">::MIN`")]
2044 /// instead of overflowing.
2045 ///
2046 /// # Example
2047 ///
2048 /// ```
2049 /// # use std::num::NonZero;
2050 /// #
2051 /// # fn main() { test().unwrap(); }
2052 /// # fn test() -> Option<()> {
2053 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2054 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2055 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2056 #[doc = concat!("let min_plus_one = NonZero::new(", stringify!($Int), "::MIN + 1)?;")]
2057 #[doc = concat!("let max = NonZero::new(", stringify!($Int), "::MAX)?;")]
2058 ///
2059 /// assert_eq!(pos_five.saturating_neg(), neg_five);
2060 /// assert_eq!(min.saturating_neg(), max);
2061 /// assert_eq!(max.saturating_neg(), min_plus_one);
2062 /// # Some(())
2063 /// # }
2064 /// ```
2065 #[inline]
2066 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2067 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2068 pub const fn saturating_neg(self) -> Self {
2069 if let Some(result) = self.checked_neg() {
2070 return result;
2071 }
2072 Self::MAX
2073 }
2074
2075 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
2076 /// of the type.
2077 ///
2078 #[doc = concat!("See [`", stringify!($Int), "::wrapping_neg`]")]
2079 /// for documentation on overflow behavior.
2080 ///
2081 /// # Example
2082 ///
2083 /// ```
2084 /// # use std::num::NonZero;
2085 /// #
2086 /// # fn main() { test().unwrap(); }
2087 /// # fn test() -> Option<()> {
2088 #[doc = concat!("let pos_five = NonZero::new(5", stringify!($Int), ")?;")]
2089 #[doc = concat!("let neg_five = NonZero::new(-5", stringify!($Int), ")?;")]
2090 #[doc = concat!("let min = NonZero::new(", stringify!($Int), "::MIN)?;")]
2091 ///
2092 /// assert_eq!(pos_five.wrapping_neg(), neg_five);
2093 /// assert_eq!(min.wrapping_neg(), min);
2094 /// # Some(())
2095 /// # }
2096 /// ```
2097 #[inline]
2098 #[stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2099 #[rustc_const_stable(feature = "nonzero_negation_ops", since = "1.71.0")]
2100 pub const fn wrapping_neg(self) -> Self {
2101 let result = self.get().wrapping_neg();
2102 // SAFETY: negation of nonzero cannot yield zero values.
2103 unsafe { Self::new_unchecked(result) }
2104 }
2105
2106 /// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
2107 ///
2108 /// # Examples
2109 ///
2110 /// ```
2111 /// # use std::num::NonZero;
2112 ///
2113 #[doc = concat!("let n = NonZero::new(-1", stringify!($Int), ").unwrap();")]
2114 ///
2115 #[doc = concat!("assert_eq!(n.cast_unsigned(), NonZero::<", stringify!($Uint), ">::MAX);")]
2116 /// ```
2117 #[stable(feature = "integer_sign_cast", since = "1.87.0")]
2118 #[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
2119 #[must_use = "this returns the result of the operation, \
2120 without modifying the original"]
2121 #[inline(always)]
2122 pub const fn cast_unsigned(self) -> NonZero<$Uint> {
2123 // SAFETY: `self.get()` can't be zero
2124 unsafe { NonZero::new_unchecked(self.get().cast_unsigned()) }
2125 }
2126
2127 };
2128}
2129
2130nonzero_integer! {
2131 Self = NonZeroU8,
2132 Primitive = unsigned u8,
2133 SignedPrimitive = i8,
2134 rot = 2,
2135 rot_op = "0x82",
2136 rot_result = "0xa",
2137 swap_op = "0x12",
2138 swapped = "0x12",
2139 reversed = "0x48",
2140}
2141
2142nonzero_integer! {
2143 Self = NonZeroU16,
2144 Primitive = unsigned u16,
2145 SignedPrimitive = i16,
2146 rot = 4,
2147 rot_op = "0xa003",
2148 rot_result = "0x3a",
2149 swap_op = "0x1234",
2150 swapped = "0x3412",
2151 reversed = "0x2c48",
2152}
2153
2154nonzero_integer! {
2155 Self = NonZeroU32,
2156 Primitive = unsigned u32,
2157 SignedPrimitive = i32,
2158 rot = 8,
2159 rot_op = "0x10000b3",
2160 rot_result = "0xb301",
2161 swap_op = "0x12345678",
2162 swapped = "0x78563412",
2163 reversed = "0x1e6a2c48",
2164}
2165
2166nonzero_integer! {
2167 Self = NonZeroU64,
2168 Primitive = unsigned u64,
2169 SignedPrimitive = i64,
2170 rot = 12,
2171 rot_op = "0xaa00000000006e1",
2172 rot_result = "0x6e10aa",
2173 swap_op = "0x1234567890123456",
2174 swapped = "0x5634129078563412",
2175 reversed = "0x6a2c48091e6a2c48",
2176}
2177
2178nonzero_integer! {
2179 Self = NonZeroU128,
2180 Primitive = unsigned u128,
2181 SignedPrimitive = i128,
2182 rot = 16,
2183 rot_op = "0x13f40000000000000000000000004f76",
2184 rot_result = "0x4f7613f4",
2185 swap_op = "0x12345678901234567890123456789012",
2186 swapped = "0x12907856341290785634129078563412",
2187 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
2188}
2189
2190#[cfg(target_pointer_width = "16")]
2191nonzero_integer! {
2192 Self = NonZeroUsize,
2193 Primitive = unsigned usize,
2194 SignedPrimitive = isize,
2195 rot = 4,
2196 rot_op = "0xa003",
2197 rot_result = "0x3a",
2198 swap_op = "0x1234",
2199 swapped = "0x3412",
2200 reversed = "0x2c48",
2201}
2202
2203#[cfg(target_pointer_width = "32")]
2204nonzero_integer! {
2205 Self = NonZeroUsize,
2206 Primitive = unsigned usize,
2207 SignedPrimitive = isize,
2208 rot = 8,
2209 rot_op = "0x10000b3",
2210 rot_result = "0xb301",
2211 swap_op = "0x12345678",
2212 swapped = "0x78563412",
2213 reversed = "0x1e6a2c48",
2214}
2215
2216#[cfg(target_pointer_width = "64")]
2217nonzero_integer! {
2218 Self = NonZeroUsize,
2219 Primitive = unsigned usize,
2220 SignedPrimitive = isize,
2221 rot = 12,
2222 rot_op = "0xaa00000000006e1",
2223 rot_result = "0x6e10aa",
2224 swap_op = "0x1234567890123456",
2225 swapped = "0x5634129078563412",
2226 reversed = "0x6a2c48091e6a2c48",
2227}
2228
2229nonzero_integer! {
2230 Self = NonZeroI8,
2231 Primitive = signed i8,
2232 UnsignedPrimitive = u8,
2233 rot = 2,
2234 rot_op = "-0x7e",
2235 rot_result = "0xa",
2236 swap_op = "0x12",
2237 swapped = "0x12",
2238 reversed = "0x48",
2239}
2240
2241nonzero_integer! {
2242 Self = NonZeroI16,
2243 Primitive = signed i16,
2244 UnsignedPrimitive = u16,
2245 rot = 4,
2246 rot_op = "-0x5ffd",
2247 rot_result = "0x3a",
2248 swap_op = "0x1234",
2249 swapped = "0x3412",
2250 reversed = "0x2c48",
2251}
2252
2253nonzero_integer! {
2254 Self = NonZeroI32,
2255 Primitive = signed i32,
2256 UnsignedPrimitive = u32,
2257 rot = 8,
2258 rot_op = "0x10000b3",
2259 rot_result = "0xb301",
2260 swap_op = "0x12345678",
2261 swapped = "0x78563412",
2262 reversed = "0x1e6a2c48",
2263}
2264
2265nonzero_integer! {
2266 Self = NonZeroI64,
2267 Primitive = signed i64,
2268 UnsignedPrimitive = u64,
2269 rot = 12,
2270 rot_op = "0xaa00000000006e1",
2271 rot_result = "0x6e10aa",
2272 swap_op = "0x1234567890123456",
2273 swapped = "0x5634129078563412",
2274 reversed = "0x6a2c48091e6a2c48",
2275}
2276
2277nonzero_integer! {
2278 Self = NonZeroI128,
2279 Primitive = signed i128,
2280 UnsignedPrimitive = u128,
2281 rot = 16,
2282 rot_op = "0x13f40000000000000000000000004f76",
2283 rot_result = "0x4f7613f4",
2284 swap_op = "0x12345678901234567890123456789012",
2285 swapped = "0x12907856341290785634129078563412",
2286 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
2287}
2288
2289#[cfg(target_pointer_width = "16")]
2290nonzero_integer! {
2291 Self = NonZeroIsize,
2292 Primitive = signed isize,
2293 UnsignedPrimitive = usize,
2294 rot = 4,
2295 rot_op = "-0x5ffd",
2296 rot_result = "0x3a",
2297 swap_op = "0x1234",
2298 swapped = "0x3412",
2299 reversed = "0x2c48",
2300}
2301
2302#[cfg(target_pointer_width = "32")]
2303nonzero_integer! {
2304 Self = NonZeroIsize,
2305 Primitive = signed isize,
2306 UnsignedPrimitive = usize,
2307 rot = 8,
2308 rot_op = "0x10000b3",
2309 rot_result = "0xb301",
2310 swap_op = "0x12345678",
2311 swapped = "0x78563412",
2312 reversed = "0x1e6a2c48",
2313}
2314
2315#[cfg(target_pointer_width = "64")]
2316nonzero_integer! {
2317 Self = NonZeroIsize,
2318 Primitive = signed isize,
2319 UnsignedPrimitive = usize,
2320 rot = 12,
2321 rot_op = "0xaa00000000006e1",
2322 rot_result = "0x6e10aa",
2323 swap_op = "0x1234567890123456",
2324 swapped = "0x5634129078563412",
2325 reversed = "0x6a2c48091e6a2c48",
2326}