Implement std::str::FromStr for matching opcodes.

Replace the home-grown from_str function.
This commit is contained in:
Jakob Stoklund Olesen
2016-04-08 11:06:33 -07:00
parent 53c878f4e1
commit 661ac9e7ad

View File

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