Code:
#[derive(Eq, PartialEq, Hash)]
enum Key {
String(String),
Bytes(Vec<u8>),
}
enum KeyRef<'a> {
String(&'a str),
Bytes(&'a [u8]),
}
fn query(map: &HashMap<Key, u32>, key: KeyRef) -> Option<u32> {
// how to do it without allocating?
}
I tried various approaches, the only one I found working is to implement:
impl Borrow<str> for Key { ... }
impl Borrow<[u8]> for Key { ... }
Which is not safe, because Borrow
would panic if used with the wrong enum variant, and also the hash of Key
must not include an enum discriminator.
Maybe something else is possible?