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