diff --git a/cranelift/src/libcretonne/immediates.rs b/cranelift/src/libcretonne/immediates.rs index 911197c349..79326d9a0b 100644 --- a/cranelift/src/libcretonne/immediates.rs +++ b/cranelift/src/libcretonne/immediates.rs @@ -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 { + fn from_str(s: &str) -> Result { 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::(), Ok(Opcode::Iadd)); + assert_eq!("iadd_imm".parse::(), Ok(Opcode::IaddImm)); + assert_eq!("iadd\0".parse::(), Err("Unknown opcode")); + assert_eq!("".parse::(), Err("Unknown opcode")); + assert_eq!("\0".parse::(), Err("Unknown opcode")); } #[test]