summaryrefslogtreecommitdiffstats
path: root/third_party/rust/chunky-vec/src/lib.rs
blob: dc815525539bb47f64e030e1d8af901d03ec377e (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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! This crate provides a pin-safe, append-only vector which guarantees never
//! to move the storage for an element once it has been allocated.

use std::{
    ops::{Index, IndexMut},
    slice,
};

struct Chunk<T> {
    /// The elements of this chunk.
    elements: Vec<T>,
}

impl<T> Chunk<T> {
    fn with_capacity(capacity: usize) -> Self {
        let elements = Vec::with_capacity(capacity);
        assert_eq!(elements.capacity(), capacity);
        Self { elements }
    }

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

    /// Returns the number of available empty elements.
    fn available(&self) -> usize {
        self.elements.capacity() - self.elements.len()
    }

    /// Returns a shared reference to the element at the given index.
    ///
    /// # Panics
    ///
    /// Panics if the index is out of bounds.
    pub fn get(&self, index: usize) -> Option<&T> {
        self.elements.get(index)
    }

    /// Returns an exclusive reference to the element at the given index.
    ///
    /// # Panics
    ///
    /// Panics if the index is out of bounds.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        self.elements.get_mut(index)
    }

    /// Pushes a new value into the fixed capacity entry.
    ///
    /// # Panics
    ///
    /// If the entry is already at its capacity.
    /// Note that this panic should never happen since the entry is only ever
    /// accessed by its outer chunk vector that checks before pushing.
    pub fn push(&mut self, new_value: T) {
        if self.available() == 0 {
            panic!("No available elements.")
        }
        self.elements.push(new_value);
    }

    pub fn push_get(&mut self, new_value: T) -> &mut T {
        self.push(new_value);
        unsafe {
            let last = self.elements.len() - 1;
            self.elements.get_unchecked_mut(last)
        }
    }

    /// Returns an iterator over the elements of the chunk.
    pub fn iter(&self) -> slice::Iter<T> {
        self.elements.iter()
    }

    /// Returns an iterator over the elements of the chunk.
    pub fn iter_mut(&mut self) -> slice::IterMut<T> {
        self.elements.iter_mut()
    }
}

impl<T> Index<usize> for Chunk<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<T> IndexMut<usize> for Chunk<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.get_mut(index).expect("index out of bounds")
    }
}

/// Pin safe vector
///
/// An append only vector that never moves the backing store for each element.
pub struct ChunkyVec<T> {
    /// The chunks holding elements
    chunks: Vec<Chunk<T>>,
}

impl<T> Default for ChunkyVec<T> {
    fn default() -> Self {
        Self {
            chunks: Vec::default(),
        }
    }
}

impl<T> Unpin for ChunkyVec<T> {}

impl<T> ChunkyVec<T> {
    const DEFAULT_CAPACITY: usize = 32;

    pub fn len(&self) -> usize {
        if self.chunks.is_empty() {
            0
        } else {
            // # Safety - There is at least one chunk here.
            (self.chunks.len() - 1) * Self::DEFAULT_CAPACITY + self.chunks.last().unwrap().len()
        }
    }

    pub fn is_empty(&self) -> bool {
        // # Safety - Since it's impossible to pop, at least one chunk means we're not empty.
        self.chunks.is_empty()
    }

    /// Returns an iterator that yields shared references to the elements of the bucket vector.
    pub fn iter(&self) -> Iter<T> {
        Iter::new(self)
    }

    /// Returns an iterator that yields exclusive reference to the elements of the bucket vector.
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut::new(self)
    }

    /// Returns a shared reference to the element at the given index if any.
    pub fn get(&self, index: usize) -> Option<&T> {
        let (x, y) = (
            index / Self::DEFAULT_CAPACITY,
            index % Self::DEFAULT_CAPACITY,
        );
        self.chunks.get(x).and_then(|chunk| chunk.get(y))
    }

    /// Returns an exclusive reference to the element at the given index if any.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        let (x, y) = (
            index / Self::DEFAULT_CAPACITY,
            index % Self::DEFAULT_CAPACITY,
        );
        self.chunks.get_mut(x).and_then(|chunk| chunk.get_mut(y))
    }

    /// Pushes a new element onto the bucket vector.
    ///
    /// # Note
    ///
    /// This operation will never move other elements, reallocates or otherwise
    /// invalidate pointers of elements contained by the bucket vector.
    pub fn push(&mut self, new_value: T) {
        self.push_get(new_value);
    }

    pub fn push_get(&mut self, new_value: T) -> &mut T {
        if self.chunks.last().map(Chunk::available).unwrap_or_default() == 0 {
            self.chunks.push(Chunk::with_capacity(Self::DEFAULT_CAPACITY));
        }
        // Safety: Guaranteed to have a chunk with available elements
        unsafe {
            let last = self.chunks.len() - 1;
            self.chunks.get_unchecked_mut(last).push_get(new_value)
        }
    }
}

impl<T> Index<usize> for ChunkyVec<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<T> IndexMut<usize> for ChunkyVec<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.get_mut(index).expect("index out of bounds")
    }
}

/// An iterator yielding shared references to the elements of a ChunkyVec.
#[derive(Clone)]
pub struct Iter<'a, T> {
    /// Chunks iterator.
    chunks: slice::Iter<'a, Chunk<T>>,
    /// Forward iterator for `next`.
    iter: Option<slice::Iter<'a, T>>,
    /// Number of elements that are to be yielded by the iterator.
    len: usize,
}

impl<'a, T> Iter<'a, T> {
    /// Creates a new iterator over the ChunkyVec
    pub(crate) fn new(vec: &'a ChunkyVec<T>) -> Self {
        let len = vec.len();
        Self {
            chunks: vec.chunks.iter(),
            iter: None,
            len,
        }
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(ref mut iter) = self.iter {
                if let front @ Some(_) = iter.next() {
                    self.len -= 1;
                    return front;
                }
            }
            self.iter = Some(self.chunks.next()?.iter());
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len(), Some(self.len()))
    }
}

impl<'a, T> ExactSizeIterator for Iter<'a, T> {
    fn len(&self) -> usize {
        self.len
    }
}

/// An iterator yielding exclusive references to the elements of a ChunkVec.
pub struct IterMut<'a, T> {
    /// Chunks iterator.
    chunks: slice::IterMut<'a, Chunk<T>>,
    /// Forward iterator for `next`.
    iter: Option<slice::IterMut<'a, T>>,
    /// Number of elements that are to be yielded by the iterator.
    len: usize,
}

impl<'a, T> IterMut<'a, T> {
    /// Creates a new iterator over the bucket vector.
    pub(crate) fn new(vec: &'a mut ChunkyVec<T>) -> Self {
        let len = vec.len();
        Self {
            chunks: vec.chunks.iter_mut(),
            iter: None,
            len,
        }
    }
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(ref mut iter) = self.iter {
                if let front @ Some(_) = iter.next() {
                    self.len -= 1;
                    return front;
                }
            }
            self.iter = Some(self.chunks.next()?.iter_mut());
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len(), Some(self.len()))
    }
}

impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
    fn len(&self) -> usize {
        self.len
    }
}
impl<'a, T> IntoIterator for &'a ChunkyVec<T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Iter<'a, T> {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut ChunkyVec<T> {
    type Item = &'a mut T;
    type IntoIter = IterMut<'a, T>;

    fn into_iter(self) -> IterMut<'a, T> {
        self.iter_mut()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn iterate_empty() {
        let v = ChunkyVec::<usize>::default();
        for i in &v {
            println!("{:?}", i);
        }
    }

    #[test]
    fn iterate_multiple_chunks() {
        let mut v = ChunkyVec::<usize>::default();
        for i in 0..33 {
            v.push(i);
        }
        let mut iter = v.iter();
        for _ in 0..32 {
            iter.next();
        }
        assert_eq!(iter.next(), Some(&32));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn index_multiple_chunks() {
        let mut v = ChunkyVec::<usize>::default();
        for i in 0..33 {
            v.push(i);
        }
        assert_eq!(v.get(32), Some(&32));
        assert_eq!(v[32], 32);
    }
}