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