Skip to content

Commit 3bdf3e7

Browse files
committed
Extract into a function
1 parent 9c12d58 commit 3bdf3e7

1 file changed

Lines changed: 12 additions & 7 deletions

File tree

zjit/src/distribution.rs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,23 +15,28 @@ impl<T: Copy + PartialEq + Default, const N: usize> Distribution<T, N> {
1515
}
1616

1717
pub fn observe(&mut self, item: T) {
18-
for (idx, (bucket, count)) in self.buckets.iter_mut().zip(self.counts.iter_mut()).enumerate() {
18+
for (bucket, count) in self.buckets.iter_mut().zip(self.counts.iter_mut()) {
1919
if *bucket == item || *count == 0 {
2020
*bucket = item;
2121
*count += 1;
2222
// Keep the most frequent item at the front
23-
let mut j = idx;
24-
while j > 0 && self.counts[j] > self.counts[j - 1] {
25-
self.counts.swap(j, j - 1);
26-
self.buckets.swap(j, j - 1);
27-
j -= 1;
28-
}
23+
self.bubble_up();
2924
return;
3025
}
3126
}
3227
self.other += 1;
3328
}
3429

30+
/// Keep the highest counted bucket at index 0
31+
fn bubble_up(&mut self) {
32+
if N == 0 { return; }
33+
let max_index = self.counts.into_iter().enumerate().max_by_key(|(_, val)| *val).unwrap().0;
34+
if max_index != 0 {
35+
self.counts.swap(0, max_index);
36+
self.buckets.swap(0, max_index);
37+
}
38+
}
39+
3540
pub fn each_item(&self) -> impl Iterator<Item = T> + '_ {
3641
self.buckets.iter().zip(self.counts.iter())
3742
.filter_map(|(&bucket, &count)| if count > 0 { Some(bucket) } else { None })

0 commit comments

Comments
 (0)