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