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