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