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