1
Fork 0

u128 truncation and sign extension are not just interpreter related

This commit is contained in:
oli 2020-11-04 13:41:58 +00:00
parent e67c768110
commit abacaf2aef
18 changed files with 73 additions and 89 deletions

View file

@ -306,6 +306,35 @@ impl Size {
let bytes = self.bytes().checked_mul(count)?;
if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None }
}
/// Truncates `value` to `self` bits and then sign-extend it to 128 bits
/// (i.e., if it is negative, fill with 1's on the left).
#[inline]
pub fn sign_extend(self, value: u128) -> u128 {
let size = self.bits();
if size == 0 {
// Truncated until nothing is left.
return 0;
}
// Sign-extend it.
let shift = 128 - size;
// Shift the unsigned value to the left, then shift back to the right as signed
// (essentially fills with FF on the left).
(((value << shift) as i128) >> shift) as u128
}
/// Truncates `value` to `self` bits.
#[inline]
pub fn truncate(self, value: u128) -> u128 {
let size = self.bits();
if size == 0 {
// Truncated until nothing is left.
return 0;
}
let shift = 128 - size;
// Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
(value << shift) >> shift
}
}
// Panicking addition, subtraction and multiplication for convenience.