15141
|
1 |
use std::{
|
|
2 |
iter,
|
|
3 |
mem::replace,
|
|
4 |
ops::{Index, IndexMut},
|
|
5 |
};
|
|
6 |
|
|
7 |
pub struct IndexSlab<T> {
|
|
8 |
data: Vec<Option<T>>,
|
|
9 |
}
|
|
10 |
|
|
11 |
impl<T> IndexSlab<T> {
|
|
12 |
pub fn new() -> Self {
|
|
13 |
Self { data: Vec::new() }
|
|
14 |
}
|
|
15 |
|
|
16 |
pub fn with_capacity(capacity: usize) -> Self {
|
|
17 |
Self {
|
|
18 |
data: Vec::with_capacity(capacity),
|
|
19 |
}
|
|
20 |
}
|
|
21 |
|
15465
|
22 |
pub fn get(&self, index: usize) -> Option<&T> {
|
|
23 |
self.data[index].as_ref()
|
|
24 |
}
|
|
25 |
|
|
26 |
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
|
|
27 |
self.data[index].as_mut()
|
|
28 |
}
|
|
29 |
|
15141
|
30 |
pub fn insert(&mut self, index: usize, value: T) {
|
|
31 |
if index >= self.data.len() {
|
|
32 |
self.data.reserve(index - self.data.len() + 1);
|
|
33 |
self.data.extend((self.data.len()..index).map(|_| None));
|
|
34 |
self.data.push(Some(value))
|
|
35 |
} else {
|
|
36 |
self.data[index] = Some(value);
|
|
37 |
}
|
|
38 |
}
|
|
39 |
|
|
40 |
pub fn contains(&self, index: usize) -> bool {
|
|
41 |
self.data.get(index).and_then(|x| x.as_ref()).is_some()
|
|
42 |
}
|
|
43 |
|
|
44 |
pub fn remove(&mut self, index: usize) -> Option<T> {
|
|
45 |
if let Some(x) = self.data.get_mut(index) {
|
|
46 |
replace(x, None)
|
|
47 |
} else {
|
|
48 |
None
|
|
49 |
}
|
|
50 |
}
|
|
51 |
|
15463
|
52 |
pub fn iter(&self) -> impl Iterator<Item = (usize, &T)> + Clone {
|
15141
|
53 |
self.data
|
|
54 |
.iter()
|
|
55 |
.enumerate()
|
|
56 |
.filter_map(|(index, opt)| opt.as_ref().and_then(|x| Some((index, x))))
|
|
57 |
}
|
|
58 |
|
|
59 |
pub fn iter_mut(&mut self) -> impl Iterator<Item = (usize, &mut T)> {
|
|
60 |
self.data
|
|
61 |
.iter_mut()
|
|
62 |
.enumerate()
|
|
63 |
.filter_map(|(index, opt)| opt.as_mut().and_then(|x| Some((index, x))))
|
|
64 |
}
|
|
65 |
}
|
|
66 |
|
|
67 |
impl<T> Index<usize> for IndexSlab<T> {
|
|
68 |
type Output = T;
|
|
69 |
|
|
70 |
fn index(&self, index: usize) -> &Self::Output {
|
|
71 |
self.data[index].as_ref().unwrap()
|
|
72 |
}
|
|
73 |
}
|
|
74 |
|
|
75 |
impl<T> IndexMut<usize> for IndexSlab<T> {
|
|
76 |
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
|
|
77 |
self.data[index].as_mut().unwrap()
|
|
78 |
}
|
|
79 |
}
|