#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PcRead {
pub ahead: u8,
pub align: u32,
}
impl PcRead {
pub const fn at(self, address: u64) -> u64 {
let pc = address.wrapping_add(self.ahead as u64);
pc & !(self.align as u64 - 1)
}
pub const fn target(self, address: u64, offset: i64, bits: u32) -> u64 {
within(self.at(address).wrapping_add(offset as u64), bits)
}
}
pub const fn within(address: u64, bits: u32) -> u64 {
address & (u64::MAX >> (64 - bits))
}
#[cfg(test)]
mod tests {
use super::PcRead;
#[test]
fn the_pc_is_read_as_the_instruction_reads_it() {
assert_eq!(PcRead { ahead: 0, align: 1 }.at(0x1004), 0x1004);
assert_eq!(PcRead { ahead: 8, align: 1 }.at(0x1000), 0x1008);
assert_eq!(PcRead { ahead: 4, align: 1 }.at(0x1002), 0x1006);
assert_eq!(PcRead { ahead: 4, align: 4 }.at(0x1002), 0x1004);
assert_eq!(
PcRead {
ahead: 0,
align: 4096
}
.at(0x1234),
0x1000
);
}
}