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