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