core/num/
niche_types.rs

1#![unstable(
2    feature = "temporary_niche_types",
3    issue = "none",
4    reason = "for core, alloc, and std internals until pattern types are further along"
5)]
6
7use crate::cmp::Ordering;
8use crate::fmt;
9use crate::hash::{Hash, Hasher};
10use crate::marker::StructuralPartialEq;
11
12macro_rules! define_valid_range_type {
13    ($(
14        $(#[$m:meta])*
15        $vis:vis struct $name:ident($int:ident as $uint:ident in $low:literal..=$high:literal);
16    )+) => {$(
17        #[derive(Clone, Copy, Eq)]
18        #[repr(transparent)]
19        #[rustc_layout_scalar_valid_range_start($low)]
20        #[rustc_layout_scalar_valid_range_end($high)]
21        $(#[$m])*
22        $vis struct $name($int);
23
24        const _: () = {
25            // With the `valid_range` attributes, it's always specified as unsigned
26            assert!(<$uint>::MIN == 0);
27            let ulow: $uint = $low;
28            let uhigh: $uint = $high;
29            assert!(ulow <= uhigh);
30
31            assert!(size_of::<$int>() == size_of::<$uint>());
32        };
33
34        impl $name {
35            /// Constructs an instance of this type from the underlying integer
36            /// primitive without checking whether its zero.
37            ///
38            /// # Safety
39            /// Immediate language UB if `val == 0`, as it violates the validity
40            /// invariant of this type.
41            #[inline]
42            pub const unsafe fn new_unchecked(val: $int) -> Self {
43                // SAFETY: Caller promised that `val` is non-zero.
44                unsafe { $name(val) }
45            }
46
47            #[inline]
48            pub const fn as_inner(self) -> $int {
49                // SAFETY: This is a transparent wrapper, so unwrapping it is sound
50                // (Not using `.0` due to MCP#807.)
51                unsafe { crate::mem::transmute(self) }
52            }
53        }
54
55        // This is required to allow matching a constant.  We don't get it from a derive
56        // because the derived `PartialEq` would do a field projection, which is banned
57        // by <https://github.com/rust-lang/compiler-team/issues/807>.
58        impl StructuralPartialEq for $name {}
59
60        impl PartialEq for $name {
61            #[inline]
62            fn eq(&self, other: &Self) -> bool {
63                self.as_inner() == other.as_inner()
64            }
65        }
66
67        impl Ord for $name {
68            #[inline]
69            fn cmp(&self, other: &Self) -> Ordering {
70                Ord::cmp(&self.as_inner(), &other.as_inner())
71            }
72        }
73
74        impl PartialOrd for $name {
75            #[inline]
76            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
77                Some(Ord::cmp(self, other))
78            }
79        }
80
81        impl Hash for $name {
82            // Required method
83            fn hash<H: Hasher>(&self, state: &mut H) {
84                Hash::hash(&self.as_inner(), state);
85            }
86        }
87
88        impl fmt::Debug for $name {
89            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90                <$int as fmt::Debug>::fmt(&self.as_inner(), f)
91            }
92        }
93    )+};
94}
95
96define_valid_range_type! {
97    pub struct Nanoseconds(u32 as u32 in 0..=999_999_999);
98}
99
100impl Nanoseconds {
101    // SAFETY: 0 is within the valid range
102    pub const ZERO: Self = unsafe { Nanoseconds::new_unchecked(0) };
103}
104
105impl Default for Nanoseconds {
106    #[inline]
107    fn default() -> Self {
108        Self::ZERO
109    }
110}
111
112define_valid_range_type! {
113    pub struct NonZeroU8Inner(u8 as u8 in 1..=0xff);
114    pub struct NonZeroU16Inner(u16 as u16 in 1..=0xff_ff);
115    pub struct NonZeroU32Inner(u32 as u32 in 1..=0xffff_ffff);
116    pub struct NonZeroU64Inner(u64 as u64 in 1..=0xffffffff_ffffffff);
117    pub struct NonZeroU128Inner(u128 as u128 in 1..=0xffffffffffffffff_ffffffffffffffff);
118
119    pub struct NonZeroI8Inner(i8 as u8 in 1..=0xff);
120    pub struct NonZeroI16Inner(i16 as u16 in 1..=0xff_ff);
121    pub struct NonZeroI32Inner(i32 as u32 in 1..=0xffff_ffff);
122    pub struct NonZeroI64Inner(i64 as u64 in 1..=0xffffffff_ffffffff);
123    pub struct NonZeroI128Inner(i128 as u128 in 1..=0xffffffffffffffff_ffffffffffffffff);
124}
125
126#[cfg(target_pointer_width = "16")]
127define_valid_range_type! {
128    pub struct UsizeNoHighBit(usize as usize in 0..=0x7fff);
129    pub struct NonZeroUsizeInner(usize as usize in 1..=0xffff);
130    pub struct NonZeroIsizeInner(isize as usize in 1..=0xffff);
131}
132#[cfg(target_pointer_width = "32")]
133define_valid_range_type! {
134    pub struct UsizeNoHighBit(usize as usize in 0..=0x7fff_ffff);
135    pub struct NonZeroUsizeInner(usize as usize in 1..=0xffff_ffff);
136    pub struct NonZeroIsizeInner(isize as usize in 1..=0xffff_ffff);
137}
138#[cfg(target_pointer_width = "64")]
139define_valid_range_type! {
140    pub struct UsizeNoHighBit(usize as usize in 0..=0x7fff_ffff_ffff_ffff);
141    pub struct NonZeroUsizeInner(usize as usize in 1..=0xffff_ffff_ffff_ffff);
142    pub struct NonZeroIsizeInner(isize as usize in 1..=0xffff_ffff_ffff_ffff);
143}
144
145define_valid_range_type! {
146    pub struct U32NotAllOnes(u32 as u32 in 0..=0xffff_fffe);
147    pub struct I32NotAllOnes(i32 as u32 in 0..=0xffff_fffe);
148
149    pub struct U64NotAllOnes(u64 as u64 in 0..=0xffff_ffff_ffff_fffe);
150    pub struct I64NotAllOnes(i64 as u64 in 0..=0xffff_ffff_ffff_fffe);
151}
152
153pub trait NotAllOnesHelper {
154    type Type;
155}
156pub type NotAllOnes<T> = <T as NotAllOnesHelper>::Type;
157impl NotAllOnesHelper for u32 {
158    type Type = U32NotAllOnes;
159}
160impl NotAllOnesHelper for i32 {
161    type Type = I32NotAllOnes;
162}
163impl NotAllOnesHelper for u64 {
164    type Type = U64NotAllOnes;
165}
166impl NotAllOnesHelper for i64 {
167    type Type = I64NotAllOnes;
168}