Rust - Building an id manager from a collection of intervals

Previously published

This article was previously published on len-learns-rust.com. A full index of these articles can be found here.

Now that we have a collection of intervals we can begin to build our id manager.

The id manager turns the collection of intervals on its head a bit in that the intervals represent the available ids, so the manager allocates an id by removing it from the collection.

The simplest id manager looks a bit like this:

pub struct IdManager {
    free_ids: Intervals,
}

impl IdManager {
    pub fn new() -> Self {
        let mut manager = IdManager { free_ids: Intervals::new() };

        manager.free_ids.insert_interval(u8::MIN, u8::MAX);

        manager
    }

    pub fn dump(&self) -> String {
        self.free_ids.dump()
    }

    pub fn can_allocate(&self) -> bool {
        !self.free_ids.is_empty()
    }

    pub fn allocate(&mut self) -> u8 {
        if self.free_ids.is_empty()
        {
            panic!("No Ids available")
        }

        self.free_ids.remove_first_value()
    }

    pub fn free(&mut self, id: u8) {
        if !self.free_ids.insert_value(id)
        {
            panic!("id is not currently allocated");
        }
    }
}

Of course we add the tests that prove all of the above works and then we’re pretty much done. However there are several issues with the code above; it’s missing a lot of the functionality that I detailed here and it’s extremely easy to leak ids and never return them to the manager.

We’ll address the id leakage and ownership issue next…

Join in

The code can be found here on GitHub each step on the journey will have one or more separate directories of code, so this article’s code is here this allows for easy comparison of changes at each stage.

Of course, there may be a better way; leave comments if you’d like to help me learn.