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