Skip to content

Commit 429b16e

Browse files
Make newtype_index methods const
1 parent 59f4ba9 commit 429b16e

File tree

1 file changed

+6
-24
lines changed

1 file changed

+6
-24
lines changed

src/librustc_index/vec.rs

+6-24
Original file line numberDiff line numberDiff line change
@@ -120,62 +120,44 @@ macro_rules! newtype_index {
120120
impl $type {
121121
$v const MAX_AS_U32: u32 = $max;
122122

123-
$v const MAX: Self = Self::from_u32_const($max);
123+
$v const MAX: Self = Self::from_u32($max);
124124

125125
#[inline]
126-
$v fn from_usize(value: usize) -> Self {
126+
$v const fn from_usize(value: usize) -> Self {
127127
assert!(value <= ($max as usize));
128128
unsafe {
129129
Self::from_u32_unchecked(value as u32)
130130
}
131131
}
132132

133133
#[inline]
134-
$v fn from_u32(value: u32) -> Self {
134+
$v const fn from_u32(value: u32) -> Self {
135135
assert!(value <= $max);
136136
unsafe {
137137
Self::from_u32_unchecked(value)
138138
}
139139
}
140140

141-
/// Hacky variant of `from_u32` for use in constants.
142-
/// This version checks the "max" constraint by using an
143-
/// invalid array dereference.
144-
#[inline]
145-
$v const fn from_u32_const(value: u32) -> Self {
146-
// This will fail at const eval time unless `value <=
147-
// max` is true (in which case we get the index 0).
148-
// It will also fail at runtime, of course, but in a
149-
// kind of wacky way.
150-
let _ = ["out of range value used"][
151-
!(value <= $max) as usize
152-
];
153-
154-
unsafe {
155-
Self { private: value }
156-
}
157-
}
158-
159141
#[inline]
160142
$v const unsafe fn from_u32_unchecked(value: u32) -> Self {
161143
Self { private: value }
162144
}
163145

164146
/// Extracts the value of this index as an integer.
165147
#[inline]
166-
$v fn index(self) -> usize {
148+
$v const fn index(self) -> usize {
167149
self.as_usize()
168150
}
169151

170152
/// Extracts the value of this index as a `u32`.
171153
#[inline]
172-
$v fn as_u32(self) -> u32 {
154+
$v const fn as_u32(self) -> u32 {
173155
self.private
174156
}
175157

176158
/// Extracts the value of this index as a `usize`.
177159
#[inline]
178-
$v fn as_usize(self) -> usize {
160+
$v const fn as_usize(self) -> usize {
179161
self.as_u32() as usize
180162
}
181163
}

0 commit comments

Comments
 (0)