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