aboutsummaryrefslogtreecommitdiff
path: root/src/common/slot_map.rs
blob: 110ee598e966a848e44f28c57b9c1d29c6f259ff (plain)
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
use std::collections::HashMap;

pub struct SlotMap<T> {
    bitmap: u64,
    map: HashMap<u32, T>,
}

impl<T> SlotMap<T> {
    pub fn new() -> Self {
        Self {
            bitmap: u64::MAX,
            map: HashMap::new(),
        }
    }

    pub fn insert(&mut self, value: T) -> Option<u32> {
        let slot = self.get_free_slot()?;
        self.map.insert(slot, value);
        self.use_slot(slot);

        Some(slot)
    }

    pub fn remove(&mut self, slot: u32) -> Option<T> {
        let value = self.map.remove(&slot)?;
        self.release_slot(slot);

        Some(value)
    }

    pub fn get(&self, slot: u32) -> Option<&T> {
        self.map.get(&slot)
    }

    pub fn get_mut(&mut self, slot: u32) -> Option<&mut T> {
        self.map.get_mut(&slot)
    }

    fn get_free_slot(&self) -> Option<u32> {
        let leading_zeros = self.bitmap.leading_zeros();

        if leading_zeros > 63 {
            None
        } else {
            Some(63 - leading_zeros)
        }
    }

    fn use_slot(&mut self, slot: u32) {
        let mask = u64::MAX;
        println!("{:0b}", self.bitmap);
        self.bitmap &= !(1 << slot) & mask;
    }

    fn release_slot(&mut self, slot: u32) {
        self.bitmap |= 1 << slot;
    }
}

#[test]
fn releases_a_slot_after_removal() {
    let mut slot_map = SlotMap::new();

    assert_eq!(slot_map.insert(1), Some(63));
    assert_eq!(slot_map.insert(2), Some(62));
    assert_eq!(slot_map.insert(3), Some(61));

    assert_eq!(slot_map.remove(&62), Some(2));

    assert_eq!(slot_map.insert(4), Some(62));
    assert_eq!(slot_map.insert(5), Some(60));
}

#[test]
fn uses_all_available_slots() {
    let mut slot_map = SlotMap::new();

    for x in 0..64 {
        assert_eq!(slot_map.insert(0), Some(63 - x));
    }

    assert_eq!(slot_map.insert(0), None);
    assert_eq!(slot_map.remove(&43), Some(0));
    assert_eq!(slot_map.insert(0), Some(43));
}