use crate::proto::ShardKeyRouter;
use tracing::warn;
pub(crate) fn xxh3_32(key: &str) -> u32 {
xxhash_rust::xxh3::xxh3_64(key.as_bytes()) as u32
}
pub(crate) fn shard_key_hash(router: i32, key: &str) -> u32 {
match ShardKeyRouter::try_from(router) {
Ok(ShardKeyRouter::Xxhash3) | Ok(ShardKeyRouter::Unknown) => xxh3_32(key),
Err(_) => {
warn!("Unrecognized shard key router {router}; routing with XXHASH3");
xxh3_32(key)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_upstream_vectors() {
assert_eq!(xxh3_32("foo"), 125730186);
assert_eq!(xxh3_32("bar"), 2687685474);
assert_eq!(xxh3_32("baz"), 862947621);
}
#[test]
fn router_dispatch_selects_xxhash3() {
assert_eq!(
shard_key_hash(ShardKeyRouter::Xxhash3 as i32, "foo"),
xxh3_32("foo")
);
assert_eq!(
shard_key_hash(ShardKeyRouter::Unknown as i32, "foo"),
xxh3_32("foo")
);
assert_eq!(shard_key_hash(999, "foo"), xxh3_32("foo"));
}
}