1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#![no_std]
#![warn(missing_docs)]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::style))]
use core::mem::MaybeUninit;
use core::fmt;
use xxhash_rust::{xxh3, const_xxh3};
#[repr(transparent)]
pub struct Function<ARGS, R>(pub fn(ARGS) -> R);
impl<ARGS, R> Clone for Function<ARGS, R> {
#[inline(always)]
fn clone(&self) -> Self {
Function(self.0)
}
}
impl<ARGS, R> Copy for Function<ARGS, R> {
}
impl<ARGS, R> fmt::Debug for Function<ARGS, R> {
#[inline(always)]
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("Function")
}
}
pub struct Matcher<const N: usize, ARGS=(), R=()> {
hashes: [u128; N],
branches: [MaybeUninit<Function<ARGS, R>>; N],
default: Function<ARGS, R>,
}
impl<const N: usize, ARGS, R> Matcher<N, ARGS, R> {
pub const fn new(patterns: [(&[u8], Function<ARGS, R>); N], default: Function<ARGS, R>) -> Self {
let mut hashes = [0u128; N];
let mut branches = [MaybeUninit::uninit(); N];
let mut pattern_idx = 0;
while pattern_idx < patterns.len() {
let (key, function) = patterns[pattern_idx];
let key_hash = const_xxh3::xxh3_128(key);
let mut matches_idx = 0;
while matches_idx < hashes.len() {
let matches_key = hashes[matches_idx];
if matches_key == 0 {
hashes[matches_idx] = key_hash;
branches[matches_idx] = MaybeUninit::new(function);
break;
} else if matches_key == key_hash {
panic!("Collision detected");
} else if key_hash > matches_key {
matches_idx += 1;
} else {
let mut matches_end_idx = hashes.len() - 1;
while matches_end_idx > matches_idx {
hashes[matches_end_idx] = hashes[matches_end_idx - 1];
branches[matches_end_idx] = branches[matches_end_idx - 1];
matches_end_idx -= 1;
}
hashes[matches_idx] = key_hash;
branches[matches_idx] = MaybeUninit::new(function);
break;
}
}
pattern_idx += 1;
}
#[cfg(debug_assertions)]
{
pattern_idx = 1;
while pattern_idx < hashes.len() {
assert!(hashes[pattern_idx - 1] <= hashes[pattern_idx], "Programming error, unsorted matcher");
pattern_idx += 1;
}
}
Self {
hashes,
branches,
default,
}
}
#[inline]
pub fn call(&self, pattern: &[u8], args: ARGS) -> R {
let key = xxh3::xxh3_128(pattern);
match self.hashes.binary_search(&key) {
Ok(idx) => unsafe {
(self.branches.get_unchecked(idx).assume_init().0)(args)
},
Err(_) => (self.default.0)(args)
}
}
}