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
#![allow(clippy::non_ascii_literal)]
#![allow(clippy::module_name_repetitions)]
#![doc = include_str!("../README.md")]
pub struct ThresholdDict<K, V> {
keys: Vec<K>,
values: Vec<V>,
default_value: V,
linear_search_max_len: usize,
}
const DEFAULT_LINEAR_SEARCH_MAX_LEN: usize = 10;
impl<K: PartialOrd, V> ThresholdDict<K, V> {
pub fn new(mut kv: Vec<(K, V)>, default_value: V) -> Self {
kv.sort_by(|lhs, rhs| lhs.0.partial_cmp(&rhs.0).unwrap());
let mut keys = vec![];
let mut values = vec![];
for (k, v) in kv {
keys.push(k);
values.push(v);
}
Self {
keys,
values,
default_value,
linear_search_max_len: DEFAULT_LINEAR_SEARCH_MAX_LEN,
}
}
pub fn with_linear_search_max_len(
kv: Vec<(K, V)>,
default_value: V,
linear_search_max_len: usize,
) -> Self {
let mut dict = Self::new(kv, default_value);
dict.linear_search_max_len = linear_search_max_len;
dict
}
pub fn query(&self, key: &K) -> &V {
if self.keys.is_empty() {
return &self.default_value;
}
if self.keys.len() < self.linear_search_max_len {
self.linear_search(key)
} else {
self.binary_search(key)
}
}
fn linear_search(&self, key: &K) -> &V {
let n = self.keys.len();
for i in 0..n {
if key <= &self.keys[i] {
return self.values.get(i).unwrap();
}
}
&self.default_value
}
fn binary_search(&self, key: &K) -> &V {
let i = self.keys.partition_point(|x| x < key);
if i == self.keys.len() {
return &self.default_value;
}
self.values.get(i).unwrap()
}
}
#[cfg(test)]
mod test {
use super::ThresholdDict;
#[test]
fn test_linear() {
let dict = ThresholdDict::new(vec![(10, 100), (20, 150), (50, 300)], 500);
assert_eq!(dict.linear_search(&0), &100);
assert_eq!(dict.linear_search(&10), &100);
assert_eq!(dict.linear_search(&15), &150);
assert_eq!(dict.linear_search(&50), &300);
assert_eq!(dict.linear_search(&60), &500);
}
#[test]
fn test_binary() {
let dict = ThresholdDict::new(vec![(10, 100), (20, 150), (50, 300)], 500);
assert_eq!(dict.binary_search(&0), &100);
assert_eq!(dict.binary_search(&10), &100);
assert_eq!(dict.binary_search(&15), &150);
assert_eq!(dict.binary_search(&50), &300);
assert_eq!(dict.binary_search(&60), &500);
}
#[test]
fn test_default_value() {
let dict = ThresholdDict::new(vec![], 500);
assert_eq!(dict.query(&0), &500);
assert_eq!(dict.query(&10), &500);
assert_eq!(dict.query(&15), &500);
assert_eq!(dict.query(&50), &500);
assert_eq!(dict.query(&60), &500);
}
}