Once a message arrives, it is pushed to the back of the array when the upheap operation "bubbles up" the item until it finds its proper place. In Rust code, this is what that looks like:
pub fn add(&mut self, notification: MessageNotification) {
self.heap.push(Box::new(notification));
self.length = self.heap.len();
if self.length > 1 {
let mut i = self.length;
while i / 2 > 0 && self.has_more_messages(i, i / 2) {
self.swap(i, i / 2);
i /= 2;
}
}
}
Initially, the new notification lives in a Box at the back of the Vec<T>, inserted via push(). A simple while loop then bubbles up the new addition by repeatedly swapping it whenever the has_more_messages() function is true. When is it true? Let's see the code:
fn has_more_messages(&self, pos1: usize, pos2: usize) -> bool {
let a = &self.heap[pos1 - 1];
let b = &self.heap[pos2 - 1];
a.no_messages >= b...