Implement std::str::FromStr for matching opcodes.
Replace the home-grown from_str function.
This commit is contained in:
@@ -7,6 +7,7 @@
|
||||
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
use std::mem;
|
||||
use std::str::FromStr;
|
||||
|
||||
// Include code generated by `meta/gen_instr.py`. This file contains:
|
||||
//
|
||||
@@ -32,9 +33,11 @@ fn simple_hash(s: &str) -> u32 {
|
||||
h
|
||||
}
|
||||
|
||||
impl Opcode {
|
||||
impl FromStr for Opcode {
|
||||
type Err = &'static str;
|
||||
|
||||
/// Parse an Opcode name from a string.
|
||||
pub fn from_str(s: &str) -> Option<Opcode> {
|
||||
fn from_str(s: &str) -> Result<Opcode, &'static str> {
|
||||
let tlen = OPCODE_HASH_TABLE.len();
|
||||
assert!(tlen.is_power_of_two());
|
||||
let mut idx = simple_hash(s) as usize;
|
||||
@@ -44,11 +47,11 @@ impl Opcode {
|
||||
let entry = OPCODE_HASH_TABLE[idx];
|
||||
|
||||
if entry == Opcode::NotAnOpcode {
|
||||
return None;
|
||||
return Err("Unknown opcode");
|
||||
}
|
||||
|
||||
if *opcode_name(entry) == *s {
|
||||
return Some(entry);
|
||||
return Ok(entry);
|
||||
}
|
||||
|
||||
// Quadratic probing.
|
||||
@@ -224,11 +227,11 @@ mod tests {
|
||||
assert_eq!(format!("{}", Opcode::IaddImm), "iadd_imm");
|
||||
|
||||
// Check the matcher.
|
||||
assert_eq!(Opcode::from_str("iadd"), Some(Opcode::Iadd));
|
||||
assert_eq!(Opcode::from_str("iadd_imm"), Some(Opcode::IaddImm));
|
||||
assert_eq!(Opcode::from_str("iadd\0"), None);
|
||||
assert_eq!(Opcode::from_str(""), None);
|
||||
assert_eq!(Opcode::from_str("\0"), None);
|
||||
assert_eq!("iadd".parse::<Opcode>(), Ok(Opcode::Iadd));
|
||||
assert_eq!("iadd_imm".parse::<Opcode>(), Ok(Opcode::IaddImm));
|
||||
assert_eq!("iadd\0".parse::<Opcode>(), Err("Unknown opcode"));
|
||||
assert_eq!("".parse::<Opcode>(), Err("Unknown opcode"));
|
||||
assert_eq!("\0".parse::<Opcode>(), Err("Unknown opcode"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user