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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use serde::{Deserialize, Serialize};
use std::{
    cmp::{Eq, Ord, PartialEq, PartialOrd},
    fmt,
    marker::PhantomData,
};

/// Type safe index into Depot
#[derive(Deserialize, Serialize, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id<T> {
    idx: u32,
    gen: u32,
    phantom: PhantomData<T>,
}

impl<T> Id<T> {
    pub fn id(&self) -> u64 { self.idx as u64 | ((self.gen as u64) << 32) }
}

impl<T> fmt::Debug for Id<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Id<{}>({}, {})",
            std::any::type_name::<T>(),
            self.idx,
            self.gen
        )
    }
}

struct Entry<T> {
    gen: u32,
    item: Option<T>,
}

/// A general-purpose high performance allocator, basically Vec with type safe
/// indices (Id)
pub struct Depot<T> {
    entries: Vec<Entry<T>>,
    len: usize,
}

impl<T> Default for Depot<T> {
    fn default() -> Self {
        Self {
            entries: Vec::new(),
            len: 0,
        }
    }
}

impl<T> Depot<T> {
    pub fn is_empty(&self) -> bool { self.len == 0 }

    pub fn len(&self) -> usize { self.len }

    pub fn contains(&self, id: Id<T>) -> bool {
        self.entries
            .get(id.idx as usize)
            .map(|e| e.gen == id.gen && e.item.is_some())
            .unwrap_or(false)
    }

    pub fn get(&self, id: Id<T>) -> Option<&T> {
        if let Some(entry) = self.entries.get(id.idx as usize) {
            if entry.gen == id.gen {
                entry.item.as_ref()
            } else {
                None
            }
        } else {
            None
        }
    }

    pub fn get_mut(&mut self, id: Id<T>) -> Option<&mut T> {
        if let Some(entry) = self.entries.get_mut(id.idx as usize) {
            if entry.gen == id.gen {
                entry.item.as_mut()
            } else {
                None
            }
        } else {
            None
        }
    }

    pub fn ids(&self) -> impl Iterator<Item = Id<T>> + '_ { self.iter().map(|(id, _)| id) }

    pub fn values(&self) -> impl Iterator<Item = &T> + '_ { self.iter().map(|(_, item)| item) }

    pub fn values_mut(&mut self) -> impl Iterator<Item = &mut T> + '_ {
        self.iter_mut().map(|(_, item)| item)
    }

    pub fn iter(&self) -> impl Iterator<Item = (Id<T>, &T)> + '_ {
        self.entries
            .iter()
            .enumerate()
            .filter_map(move |(idx, entry)| {
                Some(Id {
                    idx: idx as u32,
                    gen: entry.gen,
                    phantom: PhantomData,
                })
                .zip(entry.item.as_ref())
            })
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = (Id<T>, &mut T)> + '_ {
        self.entries
            .iter_mut()
            .enumerate()
            .filter_map(move |(idx, entry)| {
                Some(Id {
                    idx: idx as u32,
                    gen: entry.gen,
                    phantom: PhantomData,
                })
                .zip(entry.item.as_mut())
            })
    }

    pub fn insert(&mut self, item: T) -> Id<T> {
        if self.len < self.entries.len() {
            // TODO: Make this more efficient with a lookahead system
            let (idx, entry) = self
                .entries
                .iter_mut()
                .enumerate()
                .find(|(_, e)| e.item.is_none())
                .unwrap();
            entry.item = Some(item);
            assert!(entry.gen < u32::MAX);
            entry.gen += 1;
            self.len += 1;
            Id {
                idx: idx as u32,
                gen: entry.gen,
                phantom: PhantomData,
            }
        } else {
            assert!(self.entries.len() < (u32::MAX - 1) as usize);
            let id = Id {
                idx: self.entries.len() as u32,
                gen: 0,
                phantom: PhantomData,
            };
            self.entries.push(Entry {
                gen: 0,
                item: Some(item),
            });
            self.len += 1;
            id
        }
    }

    pub fn remove(&mut self, id: Id<T>) -> Option<T> {
        if let Some(item) = self
            .entries
            .get_mut(id.idx as usize)
            .and_then(|e| if e.gen == id.gen { e.item.take() } else { None })
        {
            self.len -= 1;
            Some(item)
        } else {
            None
        }
    }

    pub fn recreate_id(&self, i: u64) -> Option<Id<T>> {
        if i as usize >= self.entries.len() {
            None
        } else {
            Some(Id {
                idx: i as u32,
                gen: self
                    .entries
                    .get(i as usize)
                    .map(|e| e.gen)
                    .unwrap_or_default(),
                phantom: PhantomData,
            })
        }
    }
}