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