add Scalar::try_from_(u)int methods
This commit is contained in:
parent
c8ea4ace92
commit
0bce91ff0b
@ -237,13 +237,18 @@ pub fn from_char(c: char) -> Self {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
|
||||
pub fn try_from_uint(i: impl Into<u128>, size: Size) -> InterpResult<'tcx, Self> {
|
||||
let i = i.into();
|
||||
assert_eq!(
|
||||
truncate(i, size), i,
|
||||
"Unsigned value {:#x} does not fit in {} bits", i, size.bits()
|
||||
);
|
||||
Scalar::Raw { data: i, size: size.bytes() as u8 }
|
||||
if truncate(i, size) == i {
|
||||
Ok(Scalar::Raw { data: i, size: size.bytes() as u8 })
|
||||
} else {
|
||||
throw_unsup_format!("Unsigned value {:#x} does not fit in {} bits", i, size.bits())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
|
||||
Self::try_from_uint(i, size).unwrap()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@ -267,15 +272,20 @@ pub fn from_u64(i: u64) -> Self {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
|
||||
pub fn try_from_int(i: impl Into<i128>, size: Size) -> InterpResult<'tcx, Self> {
|
||||
let i = i.into();
|
||||
// `into` performed sign extension, we have to truncate
|
||||
let truncated = truncate(i as u128, size);
|
||||
assert_eq!(
|
||||
sign_extend(truncated, size) as i128, i,
|
||||
"Signed value {:#x} does not fit in {} bits", i, size.bits()
|
||||
);
|
||||
Scalar::Raw { data: truncated, size: size.bytes() as u8 }
|
||||
if sign_extend(truncated, size) as i128 == i {
|
||||
Ok(Scalar::Raw { data: truncated, size: size.bytes() as u8 })
|
||||
} else {
|
||||
throw_unsup_format!("Signed value {:#x} does not fit in {} bits", i, size.bits())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_int(i: impl Into<i128>, size: Size) -> Self {
|
||||
Self::try_from_int(i, size).unwrap()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
Loading…
Reference in New Issue
Block a user