Skip to Content
Hands-On Data Structures and Algorithms with Rust
book

Hands-On Data Structures and Algorithms with Rust

by Claus Matzinger
January 2019
Intermediate to advanced
316 pages
8h 8m
English
Packt Publishing
Content preview from Hands-On Data Structures and Algorithms with Rust

Getting messages in

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Hands-On Data Structures and Algorithms in Rust

Hands-On Data Structures and Algorithms in Rust

Matthew Stoodley

Publisher Resources

ISBN: 9781788995528Supplemental Content