| 1 |
use Option::{None, Some}; |
| 2 |
|
| 3 |
enum Option<T> { |
| 4 |
None, |
| 5 |
Some(T) |
| 6 |
} |
| 7 |
|
| 8 |
macro_rules! nonzero_integers { |
| 9 |
( $( $Ty: ident($Int: ty); )+ ) => { |
| 10 |
$( |
| 11 |
/// An integer that is known not to equal zero. |
| 12 |
/// |
| 13 |
/// This enables some memory layout optimization. |
| 14 |
/// For example, `Option<NonZeroU32>` is the same size as `u32`: |
| 15 |
/// |
| 16 |
/// ```rust |
| 17 |
/// use std::mem::size_of; |
| 18 |
/// assert_eq!(size_of::<Option<std::num::NonZeroU32>>(), size_of::<u32>()); |
| 19 |
/// ``` |
| 20 |
#[stable(feature = "nonzero", since = "1.28.0")] |
| 21 |
// not all derive macros are implemented yet, and this test does not test these anyways |
| 22 |
// #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] |
| 23 |
#[repr(transparent)] |
| 24 |
pub struct $Ty($Int); |
| 25 |
|
| 26 |
impl $Ty { |
| 27 |
/// Create a non-zero without checking the value. |
| 28 |
/// |
| 29 |
/// # Safety |
| 30 |
/// |
| 31 |
/// The value must not be zero. |
| 32 |
#[stable(feature = "nonzero", since = "1.28.0")] |
| 33 |
#[inline] |
| 34 |
pub const unsafe fn new_unchecked(n: $Int) -> Self { |
| 35 |
$Ty(n) |
| 36 |
} |
| 37 |
|
| 38 |
/// Create a non-zero if the given value is not zero. |
| 39 |
#[stable(feature = "nonzero", since = "1.28.0")] |
| 40 |
#[inline] |
| 41 |
pub fn new(n: $Int) -> Option<Self> { |
| 42 |
if n != 0 { |
| 43 |
Some($Ty(n)) |
| 44 |
} else { |
| 45 |
None |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
/// Returns the value as a primitive type. |
| 50 |
#[stable(feature = "nonzero", since = "1.28.0")] |
| 51 |
#[inline] |
| 52 |
pub fn get(self) -> $Int { |
| 53 |
self.0 |
| 54 |
} |
| 55 |
|
| 56 |
} |
| 57 |
|
| 58 |
impl_nonzero_fmt! { // { dg-error "could not resolve macro invocation" } |
| 59 |
(Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty |
| 60 |
} |
| 61 |
)+ |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
nonzero_integers! { |
| 66 |
NonZeroU8(u8); |
| 67 |
NonZeroU16(u16); |
| 68 |
NonZeroU32(u32); |
| 69 |
NonZeroU64(u64); |
| 70 |
NonZeroU128(u128); |
| 71 |
NonZeroUsize(usize); |
| 72 |
} |