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