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