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