chore(cpu): iron out some false assumptions

This commit is contained in:
2022-01-01 03:41:50 -06:00
parent c660ca8922
commit 92a06e49c3
4 changed files with 128 additions and 36 deletions

View File

@@ -1,6 +1,30 @@
const std = @import("std");
const assert = std.debug.assert;
pub fn u32_sign_extend(value: u32, bitSize: anytype) u32 {
const amount: u5 = 32 - bitSize;
return @bitCast(u32, @bitCast(i32, value << amount) >> amount);
pub fn signExtend(comptime T: type, comptime bits: usize, value: anytype) T {
const ValT = comptime @TypeOf(value);
comptime assert(isInteger(ValT));
comptime assert(isSigned(ValT));
const value_bits = @typeInfo(ValT).Int.bits;
comptime assert(value_bits >= bits);
const bit_diff = value_bits - bits;
// (1 << bits) -1 is a mask that will take values like 0x100 and make them 0xFF
// value & mask so that only the relevant bits are sign extended
// therefore, value & ((1 << bits) - 1) is the isolation of the relevant bits
return ((value & ((1 << bits) - 1)) << bit_diff) >> bit_diff;
}
pub fn u32SignExtend(comptime bits: usize, value: u32) u32 {
return @bitCast(u32, signExtend(i32, bits, @bitCast(i32, value)));
}
fn isInteger(comptime T: type) bool {
return @typeInfo(T) == .Int;
}
fn isSigned(comptime T: type) bool {
return @typeInfo(T).Int.signedness == .signed;
}