1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
//! Definition of different immediate types which are used as input operands for various
//! instructions.
/// Trait to interact with immediate operands.
pub(crate) trait Imm {
/// Get immediate operand as slice of bytes.
fn bytes(&self) -> &[u8];
}
macro_rules! impl_imm {
(#[$doc:meta] $name:ident, $size:expr, from: { $( $from:ty ),* $(,)? }) => {
#[$doc]
pub struct $name([u8; $size]);
impl Imm for $name {
/// Get immediate operand as slice of bytes.
fn bytes(&self) -> &[u8] {
&self.0
}
}
$(
impl From<$from> for $name {
fn from(imm: $from) -> Self {
let mut buf = [0u8; $size];
let imm = imm.to_ne_bytes();
buf[0..imm.len()].copy_from_slice(&imm);
$name(buf)
}
}
)*
}
}
impl_imm!(
/// Type representing an 8 bit immediate.
Imm8, 1, from: { u8, i8 }
);
impl_imm!(
/// Type representing a 16 bit immediate.
Imm16, 2, from: { u16, i16, u8, i8 }
);
impl_imm!(
/// Type representing a 32 bit immediate.
Imm32, 4, from: { u32, i32, u16, i16, u8, i8 }
);
impl_imm!(
/// Type representing a 64 bit immediate.
Imm64, 8, from: { u64, i64, u32, i32, u16, i16, u8, i8, usize, isize }
);
#[cfg(test)]
mod test {
use super::*;
use std::mem::size_of;
#[test]
fn test_usize_isize() {
// Imm64 should not implementd from usize/isize if this fails.
assert_eq!(size_of::<usize>(), size_of::<Imm64>());
assert_eq!(size_of::<isize>(), size_of::<Imm64>());
}
}