My final code is like:
const fn const_bytes_equal(lhs: &[u8], rhs: &[u8]) -> bool {
if lhs.len() != rhs.len() {
return false;
}
let mut i = 0;
while i < lhs.len() {
if lhs[i] != rhs[i] {
return false;
}
i += 1;
}
true
}
const fn const_str_equal(lhs: &str, rhs: &str) -> bool {
const_bytes_equal(lhs.as_bytes(), rhs.as_bytes())
}
macro_rules! id_name_conv {
($($id:literal -> $name:literal)*) => {
const fn id2name(id: u32) -> &'static str {
match id {
$($id => $name,)*
_ => unreachable!(),
}
}
const fn name2id(name: &'static str) -> u32 {
$(if const_str_equal(name, $name) {
return $id
})*
unreachable!();
}
};
}
id_name_conv!(
0 -> "a"
1 -> "b"
);
assert_eq!(id2name(0), "a");
assert_eq!(name2id("b"), 1);