Skip to content

Commit 0bce91f

Browse files
committed
add Scalar::try_from_(u)int methods
1 parent c8ea4ac commit 0bce91f

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

src/librustc/mir/interpret/value.rs

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -237,13 +237,18 @@ impl<'tcx, Tag> Scalar<Tag> {
237237
}
238238

239239
#[inline]
240-
pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
240+
pub fn try_from_uint(i: impl Into<u128>, size: Size) -> InterpResult<'tcx, Self> {
241241
let i = i.into();
242-
assert_eq!(
243-
truncate(i, size), i,
244-
"Unsigned value {:#x} does not fit in {} bits", i, size.bits()
245-
);
246-
Scalar::Raw { data: i, size: size.bytes() as u8 }
242+
if truncate(i, size) == i {
243+
Ok(Scalar::Raw { data: i, size: size.bytes() as u8 })
244+
} else {
245+
throw_unsup_format!("Unsigned value {:#x} does not fit in {} bits", i, size.bits())
246+
}
247+
}
248+
249+
#[inline]
250+
pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
251+
Self::try_from_uint(i, size).unwrap()
247252
}
248253

249254
#[inline]
@@ -267,15 +272,20 @@ impl<'tcx, Tag> Scalar<Tag> {
267272
}
268273

269274
#[inline]
270-
pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
275+
pub fn try_from_int(i: impl Into<i128>, size: Size) -> InterpResult<'tcx, Self> {
271276
let i = i.into();
272277
// `into` performed sign extension, we have to truncate
273278
let truncated = truncate(i as u128, size);
274-
assert_eq!(
275-
sign_extend(truncated, size) as i128, i,
276-
"Signed value {:#x} does not fit in {} bits", i, size.bits()
277-
);
278-
Scalar::Raw { data: truncated, size: size.bytes() as u8 }
279+
if sign_extend(truncated, size) as i128 == i {
280+
Ok(Scalar::Raw { data: truncated, size: size.bytes() as u8 })
281+
} else {
282+
throw_unsup_format!("Signed value {:#x} does not fit in {} bits", i, size.bits())
283+
}
284+
}
285+
286+
#[inline]
287+
pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
288+
Self::try_from_int(i, size).unwrap()
279289
}
280290

281291
#[inline]

0 commit comments

Comments
 (0)