How does Rust implement matching against strings?
Unlike most systems languages, in Rust you can match strings against string literals. For example, this compiles and does what you'd expect:
pub fn decode(s: &str) -> u8 {
match s {
"one" => 1,
"two" => 2,
_ => 0,
}
}
I'm curious about the implementation of this feature. C and C++ compilers have long been good at optimizing integer matches in switch statements. Depending on the number and contents of case arms, they generate ordinary comparisons, sophisticated lookup tables, or anything in-between. But they only support numbers, string comparisons are strictly consigned to the standard library. Therefore I wouldn't expect LLVM and Gcc to have IR instructions specifically for string matching.
So what does \rustc\\ do with the above code? Does it generate naive LLVM IR and let LLVM optimize it? Or does it help out by analyzing the patterns and noticing regularities, such as (for the above example) that strings with size other than three bytes decode to 0, and generating efficient IR? The generated assembly certainly doesn't look like a naive series of string comparisons.