impl From<u8> for Opcode

This commit is contained in:
Luke Street 2024-09-26 23:18:47 -06:00
parent d161deca50
commit c8026715f0
2 changed files with 38 additions and 2 deletions

View File

@ -1051,13 +1051,30 @@ impl Opcode {
for i in entry.0..entry.1 { for i in entry.0..entry.1 {
let pattern = OPCODE_PATTERNS[i as usize]; let pattern = OPCODE_PATTERNS[i as usize];
if (code & pattern.0) == pattern.1 { if (code & pattern.0) == pattern.1 {
// Safety: The enum is repr(u8) and marked non_exhaustive // Safety: The enum is repr(u8) and the value is within the enum's range
return unsafe { core::mem::transmute::<u8, Opcode>(i) }; return unsafe { core::mem::transmute::<u8, Opcode>(i) };
} }
} }
Self::Illegal Self::Illegal
} }
} }
impl From<u8> for Opcode {
#[inline]
fn from(value: u8) -> Self {
if value > 221 {
Self::Illegal
} else {
// Safety: The enum is repr(u8) and the value is within the enum's range
unsafe { core::mem::transmute::<u8, Self>(value) }
}
}
}
impl From<Opcode> for u8 {
#[inline]
fn from(value: Opcode) -> Self {
value as u8
}
}
impl Ins { impl Ins {
/// simm: Signed Immediate /// simm: Signed Immediate
#[inline(always)] #[inline(always)]

View File

@ -41,6 +41,8 @@ pub fn gen_disasm(isa: &Isa, max_args: usize) -> Result<TokenStream> {
entries.push(entry); entries.push(entry);
} }
ensure!(sorted_ops.len() == isa.opcodes.len()); ensure!(sorted_ops.len() == isa.opcodes.len());
ensure!(sorted_ops.len() <= 256);
let opcode_max = Literal::u8_unsuffixed((sorted_ops.len() - 1) as u8);
// Generate the opcode entries table // Generate the opcode entries table
let mut opcode_entries = TokenStream::new(); let mut opcode_entries = TokenStream::new();
@ -337,13 +339,30 @@ pub fn gen_disasm(isa: &Isa, max_args: usize) -> Result<TokenStream> {
for i in entry.0..entry.1 { for i in entry.0..entry.1 {
let pattern = OPCODE_PATTERNS[i as usize]; let pattern = OPCODE_PATTERNS[i as usize];
if (code & pattern.0) == pattern.1 { if (code & pattern.0) == pattern.1 {
#[comment = " Safety: The enum is repr(u8) and marked non_exhaustive"] #[comment = " Safety: The enum is repr(u8) and the value is within the enum's range"]
return unsafe { core::mem::transmute::<u8, Opcode>(i) }; return unsafe { core::mem::transmute::<u8, Opcode>(i) };
} }
} }
Self::Illegal Self::Illegal
} }
} }
impl From<u8> for Opcode {
#[inline]
fn from(value: u8) -> Self {
if value > #opcode_max {
Self::Illegal
} else {
#[comment = " Safety: The enum is repr(u8) and the value is within the enum's range"]
unsafe { core::mem::transmute::<u8, Self>(value) }
}
}
}
impl From<Opcode> for u8 {
#[inline]
fn from(value: Opcode) -> Self {
value as u8
}
}
impl Ins { impl Ins {
#ins_fields #ins_fields