use ahash::AHashSet;
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use std::sync::LazyLock;
#[path = "arity_table.rs"]
mod arity_table;
#[derive(Default)]
struct NameHasher(u64);
impl NameHasher {
#[inline(always)]
fn mix(&mut self, word: u64) {
self.0 = (self.0.rotate_left(5) ^ word).wrapping_mul(0x517c_c1b7_2722_0a95);
}
}
impl Hasher for NameHasher {
#[inline]
fn write(&mut self, bytes: &[u8]) {
let (eights, rest) = bytes.as_chunks::<8>();
for eight in eights {
self.mix(u64::from_le_bytes(*eight));
}
let mut last = 0u64;
for (i, byte) in rest.iter().enumerate() {
last |= (*byte as u64) << (8 * i);
}
self.mix(last ^ ((bytes.len() as u64) << 56));
}
#[inline]
fn write_u8(&mut self, _: u8) {}
#[inline]
fn finish(&self) -> u64 {
self.0 ^ (self.0 >> 32)
}
}
type ByName<V> = HashMap<&'static str, V, BuildHasherDefault<NameHasher>>;
struct ShortNames {
slots: Box<[ShortName]>,
}
#[derive(Clone, Copy, Default)]
struct ShortName {
key: u64,
len: u8,
container: bool,
arity: i16,
}
impl ShortNames {
const SLOTS: usize = 1024;
const LONGEST: usize = 8;
#[inline(always)]
fn key(name: &[u8]) -> u64 {
let len = name.len();
if len >= 4 {
let mut head = [0u8; 4];
head.copy_from_slice(&name[..4]);
let mut tail = [0u8; 4];
tail.copy_from_slice(&name[len - 4..]);
u32::from_le_bytes(head) as u64 | (u32::from_le_bytes(tail) as u64) << (8 * (len - 4))
} else {
(name[0] as u64)
| (name[len / 2] as u64) << (8 * (len / 2))
| (name[len - 1] as u64) << (8 * (len - 1))
}
}
#[inline(always)]
fn slot(key: u64) -> usize {
(key.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 54) as usize & (Self::SLOTS - 1)
}
fn of(commands: &ByName<(i16, bool)>) -> Self {
let mut slots = vec![ShortName::default(); Self::SLOTS].into_boxed_slice();
for (name, (arity, container)) in commands {
if name.len() > Self::LONGEST {
continue;
}
let key = Self::key(name.as_bytes());
let mut at = Self::slot(key);
while slots[at].len != 0 {
at = (at + 1) & (Self::SLOTS - 1);
}
slots[at] = ShortName {
key,
len: name.len() as u8,
container: *container,
arity: *arity,
};
}
ShortNames { slots }
}
#[inline(always)]
fn get(&self, name: &[u8]) -> Option<(i16, bool)> {
let key = Self::key(name);
let mut at = Self::slot(key);
loop {
let slot = &self.slots[at];
if slot.len == 0 {
return None;
}
if slot.key == key && slot.len as usize == name.len() {
return Some((slot.arity, slot.container));
}
at = (at + 1) & (Self::SLOTS - 1);
}
}
}
struct Arities {
commands: ByName<(i16, bool)>,
short: ShortNames,
subcommands: ByName<i16>,
containers: AHashSet<&'static str>,
}
static ARITIES: LazyLock<Arities> = LazyLock::new(|| {
let table = || {
arity_table::TABLE
.iter()
.copied()
.filter(|(name, _)| *name != "HSETEX")
};
let containers: AHashSet<&'static str> = table()
.filter_map(|(name, _)| name.split_once('|').map(|(container, _)| container))
.collect();
let commands: ByName<(i16, bool)> = table()
.filter(|(name, _)| !name.contains('|'))
.map(|(name, arity)| (name, (arity, containers.contains(name))))
.collect();
let subcommands = table().filter(|(name, _)| name.contains('|')).collect();
Arities {
short: ShortNames::of(&commands),
commands,
subcommands,
containers,
}
});
fn fits(arity: i16, given: usize) -> bool {
if arity >= 0 {
given == arity as usize
} else {
given >= arity.unsigned_abs() as usize
}
}
fn wrong_number(name: &str) -> Vec<u8> {
format!(
"-ERR wrong number of arguments for '{}' command\r\n",
name.to_ascii_lowercase()
)
.into_bytes()
}
pub fn of(name: &str) -> Option<i16> {
let arities = &*ARITIES;
match arities.commands.get(name) {
Some((arity, _)) => Some(*arity),
None => arities.subcommands.get(name).copied(),
}
}
pub fn subcommands() -> impl Iterator<Item = &'static str> {
arity_table::TABLE
.iter()
.map(|(name, _)| *name)
.filter(|name| name.contains('|'))
}
#[cfg(test)]
pub(crate) fn all_names() -> impl Iterator<Item = &'static str> {
arity_table::TABLE.iter().map(|(name, _)| *name)
}
pub fn is_known(name: &str) -> bool {
ARITIES.commands.contains_key(name)
}
pub fn is_container(name: &str) -> bool {
ARITIES.containers.contains(name)
}
#[inline(always)]
pub fn check(name: &str, cmd: &[&[u8]]) -> Option<Vec<u8>> {
let arities = &*ARITIES;
if (1..=ShortNames::LONGEST).contains(&name.len()) {
let (arity, container) = arities.short.get(name.as_bytes())?;
if fits(arity, cmd.len()) && !container {
return None;
}
return refusal(arities, name, cmd, arity);
}
check_long(arities, name, cmd)
}
#[inline(never)]
fn check_long(arities: &Arities, name: &str, cmd: &[&[u8]]) -> Option<Vec<u8>> {
let (arity, container) = *arities.commands.get(name)?;
if fits(arity, cmd.len()) && !container {
return None;
}
refusal(arities, name, cmd, arity)
}
#[cold]
#[inline(never)]
fn refusal(arities: &Arities, name: &str, cmd: &[&[u8]], arity: i16) -> Option<Vec<u8>> {
if !fits(arity, cmd.len()) {
return Some(wrong_number(name));
}
if let Some(sub) = cmd.get(1) {
let full = format!(
"{name}|{}",
String::from_utf8_lossy(sub).to_ascii_uppercase()
);
if let Some(arity) = arities.subcommands.get(full.as_str())
&& !fits(*arity, cmd.len())
{
return Some(wrong_number(&full));
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_short_names_are_the_same_commands() {
let arities = &*ARITIES;
let mut short = 0;
for (name, entry) in &arities.commands {
if name.len() <= ShortNames::LONGEST {
assert_eq!(arities.short.get(name.as_bytes()), Some(*entry), "{name}");
short += 1;
}
}
assert!(short > 100, "{short}");
for name in [
"G", "GE", "GETT", "XGET", "NOSUCH", "ABCDEFGH", "\0", "GET\0", "\0GET",
] {
assert_eq!(arities.short.get(name.as_bytes()), None, "{name:?}");
}
assert_eq!(checked(&["GET\0"]), None);
assert_eq!(checked(&["GET\0", "a", "b", "c"]), None);
assert!(checked(&["HGETALL"]).is_some());
assert!(checked(&["ZRANGEBYSCORE"]).is_some());
}
fn checked(words: &[&str]) -> Option<String> {
let cmd: Vec<&[u8]> = words.iter().map(|w| w.as_bytes()).collect();
check(&words[0].to_ascii_uppercase(), &cmd)
.map(|reply| String::from_utf8(reply).unwrap().trim_end().to_string())
}
#[test]
fn exact_and_at_least() {
assert_eq!(checked(&["GET", "k"]), None);
assert_eq!(
checked(&["GET"]).unwrap(),
"-ERR wrong number of arguments for 'get' command"
);
assert_eq!(
checked(&["GET", "a", "b"]).unwrap(),
"-ERR wrong number of arguments for 'get' command"
);
assert_eq!(checked(&["DEL", "a", "b", "c"]), None);
assert!(checked(&["DEL"]).is_some());
assert_eq!(
checked(&["ZMPOP", "1", "z"]).unwrap(),
"-ERR wrong number of arguments for 'zmpop' command"
);
}
#[test]
fn subcommands_have_their_own() {
assert_eq!(checked(&["CONFIG", "GET", "maxmemory"]), None);
assert_eq!(
checked(&["CONFIG", "GET"]).unwrap(),
"-ERR wrong number of arguments for 'config|get' command"
);
assert_eq!(
checked(&["CONFIG"]).unwrap(),
"-ERR wrong number of arguments for 'config' command"
);
assert_eq!(checked(&["CONFIG", "NOSUCH", "x"]), None);
}
#[test]
fn what_the_table_does_not_have_is_left_alone() {
assert_eq!(checked(&["FT.SEARCH"]), None);
assert_eq!(checked(&["JSON.GET"]), None);
assert_eq!(checked(&["HSETEX", "k", "10", "f", "v"]), None);
}
}