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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use ordered_linked_list::{OrderedLinkedList, OrderedLinkedListIndex, OrderedLinkedListIter};
use std::{
cmp, collections::{hash_map::Entry, HashMap}, fmt::{self, Debug}, hash::Hash, iter, ops
};
use twox_hash::RandomXxHashBuilder;
#[derive(Clone, Serialize, Deserialize)]
struct Node<T, C>(T, C);
impl<T, C: Ord> Ord for Node<T, C> {
#[inline(always)]
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.1.cmp(&other.1)
}
}
impl<T, C: PartialOrd> PartialOrd for Node<T, C> {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.1.partial_cmp(&other.1)
}
}
impl<T, C: PartialEq> PartialEq for Node<T, C> {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.1.eq(&other.1)
}
}
impl<T, C: Eq> Eq for Node<T, C> {}
#[derive(Clone, Serialize, Deserialize)]
pub struct MostFrequent<T: Hash + Eq + Clone> {
map: HashMap<T, OrderedLinkedListIndex<'static>, RandomXxHashBuilder>,
list: OrderedLinkedList<Node<T, usize>>,
base: usize,
}
impl<T: Hash + Eq + Clone> MostFrequent<T> {
pub fn new(n: usize) -> Self {
Self {
map: HashMap::with_capacity_and_hasher(n, RandomXxHashBuilder::default()),
list: OrderedLinkedList::new(n),
base: 0,
}
}
fn assert(&self) {
if !cfg!(feature = "assert") {
return;
}
for (k, &v) in &self.map {
assert!(&self.list[v].0 == k);
}
let mut cur = self.list[self.list.head().unwrap()].1;
for &Node(_, count) in self.list.iter() {
assert!(cur >= count);
cur = count;
}
assert!(cur >= self.base);
}
pub fn capacity(&self) -> usize {
self.list.capacity()
}
pub fn push(&mut self, item: T) {
let entry = self.map.entry(item.clone());
match entry {
Entry::Occupied(entry) => {
let offset = *entry.get();
self.list
.mutate(offset, |Node(t, count)| Node(t, count + 1));
}
Entry::Vacant(entry) => {
if self.list.len() < self.list.capacity() {
let new = self.list.push_back(Node(item, self.base + 1));
let new = unsafe { new.staticify() };
let _ = entry.insert(new);
} else if self.list[self.list.tail().unwrap()].1 == self.base {
let old = self.list.pop_back().0;
let new = self.list.push_back(Node(item, self.base + 1));
let new = unsafe { new.staticify() };
let _ = entry.insert(new);
let _ = self.map.remove(&old).unwrap();
} else {
self.base += 1;
}
}
}
self.assert();
}
pub fn iter(&self) -> MostFrequentIter<'_, T> {
MostFrequentIter {
list_iter: self.list.iter(),
}
}
}
impl<'a, T: Hash + Eq + Clone + Debug> Debug for MostFrequent<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
pub struct MostFrequentIter<'a, T: Hash + Eq + Clone + 'a> {
list_iter: OrderedLinkedListIter<'a, Node<T, usize>>,
}
impl<'a, T: Hash + Eq + Clone> Clone for MostFrequentIter<'a, T> {
fn clone(&self) -> Self {
Self {
list_iter: self.list_iter.clone(),
}
}
}
impl<'a, T: Hash + Eq + Clone> Iterator for MostFrequentIter<'a, T> {
type Item = (&'a T, usize);
fn next(&mut self) -> Option<(&'a T, usize)> {
self.list_iter.next().map(|x| (&x.0, x.1))
}
}
impl<'a, T: Hash + Eq + Clone + Debug> Debug for MostFrequentIter<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
impl<T: Hash + Eq + Clone> iter::Sum for MostFrequent<T> {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
let mut total = Self::new(0);
for sample in iter {
total += sample;
}
total
}
}
impl<T: Hash + Eq + Clone> ops::Add for MostFrequent<T> {
type Output = Self;
fn add(mut self, other: Self) -> Self {
self += other;
self
}
}
impl<T: Hash + Eq + Clone> ops::AddAssign for MostFrequent<T> {
fn add_assign(&mut self, other: Self) {
if self.capacity() > 0 {
assert_eq!(self.capacity(), other.capacity());
let mut scores = HashMap::new();
for (url, count) in self.iter() {
*scores.entry(url.clone()).or_insert(0) += count;
}
for (url, count) in other.iter() {
*scores.entry(url.clone()).or_insert(0) += count;
}
let mut top = Self::new(self.capacity());
for (url, count) in scores {
for _ in 0..count {
top.push(url.clone());
}
}
*self = top;
} else {
*self = other;
}
}
}