Skip to main content

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;
11use crate::pat::pattern_type;
12
13macro_rules! define_valid_range_type {
14    ($(
15        $(#[$m:meta])*
16        $vis:vis struct $name:ident($int:ident is $pat:pat);
17    )+) => {$(
18        #[derive(Clone, Copy)]
19        #[repr(transparent)]
20        $(#[$m])*
21        $vis struct $name(pattern_type!($int is $pat));
22        impl $name {
23            #[inline]
24            pub const fn new(val: $int) -> Option<Self> {
25                #[allow(non_contiguous_range_endpoints)]
26                if let $pat = val {
27                    // SAFETY: just checked that the value matches the pattern
28                    Some(unsafe { $name(crate::mem::transmute(val)) })
29                } else {
30                    None
31                }
32            }
33
34            /// Constructs an instance of this type from the underlying integer
35            /// primitive without checking whether its valid.
36            ///
37            /// # Safety
38            /// Immediate language UB if `val` is not within the valid range for this
39            /// type, as it violates the validity invariant.
40            #[inline]
41            pub const unsafe fn new_unchecked(val: $int) -> Self {
42                // SAFETY: Caller promised that `val` is within the valid range.
43                unsafe { crate::mem::transmute(val) }
44            }
45
46            #[inline]
47            pub const fn as_inner(self) -> $int {
48                // SAFETY: pattern types are always legal values of their base type
49                // (Not using `.0` because that has perf regressions.)
50                unsafe { crate::mem::transmute(self) }
51            }
52        }
53
54        // This is required to allow matching a constant.  We don't get it from a derive
55        // because the derived `PartialEq` would do a field projection, which is banned
56        // by <https://github.com/rust-lang/compiler-team/issues/807>.
57        impl StructuralPartialEq for $name {}
58
59        impl Eq for $name {}
60
61        impl PartialEq for $name {
62            #[inline]
63            fn eq(&self, other: &Self) -> bool {
64                self.as_inner() == other.as_inner()
65            }
66        }
67
68        impl Ord for $name {
69            #[inline]
70            fn cmp(&self, other: &Self) -> Ordering {
71                Ord::cmp(&self.as_inner(), &other.as_inner())
72            }
73        }
74
75        impl PartialOrd for $name {
76            #[inline]
77            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
78                Some(Ord::cmp(self, other))
79            }
80        }
81
82        impl Hash for $name {
83            // Required method
84            fn hash<H: Hasher>(&self, state: &mut H) {
85                Hash::hash(&self.as_inner(), state);
86            }
87        }
88
89        impl fmt::Debug for $name {
90            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91                <$int as fmt::Debug>::fmt(&self.as_inner(), f)
92            }
93        }
94    )+};
95}
96
97define_valid_range_type! {
98    pub struct Nanoseconds(u32 is 0..=999_999_999);
99}
100
101impl Nanoseconds {
102    // SAFETY: 0 is within the valid range
103    pub const ZERO: Self = unsafe { Nanoseconds::new_unchecked(0) };
104}
105
106#[rustc_const_unstable(feature = "const_default", issue = "143894")]
107const impl Default for Nanoseconds {
108    #[inline]
109    fn default() -> Self {
110        Self::ZERO
111    }
112}
113
114const HALF_USIZE: usize = usize::MAX >> 1;
115const HALF_USIZE_MINUS_ONE: usize = HALF_USIZE - 1;
116
117define_valid_range_type! {
118    pub struct NonZeroU8Inner(u8 is 1..);
119    pub struct NonZeroU16Inner(u16 is 1..);
120    pub struct NonZeroU32Inner(u32 is 1..);
121    pub struct NonZeroU64Inner(u64 is 1..);
122    pub struct NonZeroU128Inner(u128 is 1..);
123
124    pub struct NonZeroI8Inner(i8 is ..0 | 1..);
125    pub struct NonZeroI16Inner(i16 is ..0 | 1..);
126    pub struct NonZeroI32Inner(i32 is ..0 | 1..);
127    pub struct NonZeroI64Inner(i64 is ..0 | 1..);
128    pub struct NonZeroI128Inner(i128 is ..0 | 1..);
129
130    pub struct UsizeNoHighBit(usize is 0..=HALF_USIZE);
131    pub struct UsizeNoHighBitMinusOne(usize is 0..=HALF_USIZE_MINUS_ONE);
132    pub struct NonZeroUsizeInner(usize is 1..);
133    pub struct NonZeroIsizeInner(isize is ..0 | 1..);
134
135    pub struct U32NotAllOnes(u32 is 0..u32::MAX);
136    pub struct I32NotAllOnes(i32 is ..-1 | 0..);
137
138    pub struct U64NotAllOnes(u64 is 0..u64::MAX);
139    pub struct I64NotAllOnes(i64 is ..-1 | 0..);
140
141    pub struct NonZeroCharInner(char is '\u{1}' ..= '\u{10ffff}');
142}
143
144pub trait NotAllOnesHelper {
145    type Type;
146}
147pub type NotAllOnes<T> = <T as NotAllOnesHelper>::Type;
148impl NotAllOnesHelper for u32 {
149    type Type = U32NotAllOnes;
150}
151impl NotAllOnesHelper for i32 {
152    type Type = I32NotAllOnes;
153}
154impl NotAllOnesHelper for u64 {
155    type Type = U64NotAllOnes;
156}
157impl NotAllOnesHelper for i64 {
158    type Type = I64NotAllOnes;
159}
160
161define_valid_range_type! {
162    pub struct CodePointInner(u32 is 0..=0x10ffff);
163}
164
165impl CodePointInner {
166    pub const ZERO: Self = CodePointInner::new(0).unwrap();
167}
168
169impl Default for CodePointInner {
170    #[inline]
171    fn default() -> Self {
172        Self::ZERO
173    }
174}