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
//! Efficiently generate and reclaim slot IDs from a numerical range.
//!
//! The [`SlotGenerator`](crate::SlotGenerator) type works by maintaining a list of unused slot
//! ranges, and pulls the lowest available value from the slot pool whenever the user requests
//! one. Slots can be reclaimed and placed back in the generator pool with the `replace_slot`
//! methods. It's not a terribly complex implementation, and it shouldn't be used if you need to
//! generate secure IDs, but you don't always need a secure generator and the complexity that comes
//! from that.

use std::{
    cmp::Ordering,
    ops::Range,
};
use num_traits::PrimInt;

/// The slot generator.
#[derive(Debug, Clone)]
pub struct SlotGenerator<T>
where
    T: PrimInt,
    Range<T>: ExactSizeIterator,
{
    slots: Vec<Range<T>>,
}

impl<T> SlotGenerator<T>
where
    T: PrimInt,
    Range<T>: ExactSizeIterator,
{
    /// Create a new `SlotGenerator` with the specified range.
    pub fn new(range: Range<T>) -> SlotGenerator<T> {
        SlotGenerator { slots: vec![range] }
    }

    /// Generate a new slot.
    ///
    /// # Panics
    /// Will panic if no more slots are available.
    pub fn generate_slot(&mut self) -> T {
        match self.try_generate_slot() {
            Some(t) => t,
            None => panic!("attempted to generate slot, but no slots were left!"),
        }
    }

    /// Attempts to generate a new slot.
    ///
    /// Will return `None` if no slots are available.
    pub fn try_generate_slot(&mut self) -> Option<T> {
        if self.slots.len() == 0 {
            return None;
        }
        let range = self.slots.last_mut().unwrap();
        let slot = range.start;
        range.start = range.start + T::one();
        if range.len() == 0 {
            self.slots.pop();
        }
        Some(slot)
    }

    /// Reclaim a slot that has been generated by the `SlotGenerator`.
    ///
    /// # Panics
    /// Will panic if the slot is already in the slot pool.
    pub fn replace_slot(&mut self, slot: T)
        where T: std::fmt::Debug,
    {
        match self.try_replace_slot(slot) {
            Ok(()) => (),
            Err(slot) => panic!("attempted to replace slot {:?}, but slot was already taken!", slot),
        }
    }

    /// Attempt to reclaim a slot that has been generated by the `SlotGenerator`.
    ///
    /// Will return `Err(slot)` if the slot is already in the slot pool.
    pub fn try_replace_slot(&mut self, slot: T) -> Result<(), T> {
        let _1 = T::one();
        let index = self.slots.binary_search_by(|range| {
            let equal =
                range.start.checked_sub(&_1) == Some(slot) || range.end == slot || range.contains(&slot);
            if equal {
                Ordering::Equal
            } else {
                slot.cmp(&range.start)
            }
        });
        match index {
            Err(i) => self.slots.insert(i, slot..slot+_1),
            Ok(i) => {
                let range = &mut self.slots[i];
                if range.start.checked_sub(&_1) == Some(slot) {
                    range.start = slot;
                } else if range.end == slot {
                    range.end = range.end + _1;
                } else {
                    return Err(slot);
                }
                let range = range.clone();
                let prev_range = i.checked_sub(1).map(|i| &mut self.slots[i]);
                if let Some(prev_range) = prev_range {
                    if prev_range.start == range.end {
                        prev_range.start = range.start;
                        self.slots.remove(i);
                    }
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn exhaust_slots() {
        let mut slots = SlotGenerator::new(1..4);
        assert_eq!(Some(1), slots.try_generate_slot());
        assert_eq!(Some(2), slots.try_generate_slot());
        assert_eq!(Some(3), slots.try_generate_slot());
        assert_eq!(None, slots.try_generate_slot());
        slots.replace_slot(2);
        assert_eq!(Some(2), slots.try_generate_slot());
    }

    #[test]
    #[should_panic]
    fn replace_filled_slots() {
        let mut slots = SlotGenerator::new(1..4);
        assert_eq!(Err(2), slots.try_replace_slot(2));
        slots.replace_slot(2);
    }

    #[test]
    fn generate_slots() {
        let mut slots = SlotGenerator::new(1..u32::max_value());
        assert_eq!(1, slots.generate_slot());
        assert_eq!(2, slots.generate_slot());
        assert_eq!(3, slots.generate_slot());
    }

    #[test]
    fn replace_slots() {
        let mut slots = SlotGenerator::new(1..u32::max_value());
        let a = slots.generate_slot();
        let b = slots.generate_slot();
        let c = slots.generate_slot();
        let d = slots.generate_slot();
        assert_eq!(1, a);
        assert_eq!(2, b);
        assert_eq!(3, c);
        assert_eq!(4, d);

        slots.replace_slot(a);
        slots.replace_slot(c);
        slots.replace_slot(b);
        slots.replace_slot(d);
        assert_eq!(1, slots.slots.len());
    }
}