department 0.2.6

Implementation of the proposed Storages API
Documentation
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use core::borrow::{Borrow, BorrowMut};
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut, Index, IndexMut};
use core::{fmt, mem, ptr, slice};

use crate::base::Storage;
use crate::error::Result;

/// Storage based implementation of [`Vec`](`std::vec::Vec`)
pub struct Vec<T, S>
where
    S: Storage,
{
    handle: S::Handle<[MaybeUninit<T>]>,
    len: usize,
    storage: S,
}

impl<T, S> Vec<T, S>
where
    S: Storage + Default,
{
    /// Create a new, empty [`Vec`], creating a default instance of the desired storage.
    ///
    /// # Panics
    ///
    /// If the backing allocation fails for any reason
    pub fn new() -> Vec<T, S> {
        let mut storage = S::default();

        Vec {
            handle: storage.allocate_single(0).unwrap(),
            len: 0,
            storage,
        }
    }

    /// Attempt to create a new, empty [`Vec`], creating a default instance of the desired storage.
    pub fn try_new() -> Result<Vec<T, S>> {
        let mut storage = S::default();

        Ok(Vec {
            handle: storage.allocate_single(0)?,
            len: 0,
            storage,
        })
    }

    /// Create a new [`Vec`], with a pre-allocated capacity equal to `size`.
    /// Uses a new default instance of the desired storage.
    ///
    /// # Panics
    ///
    /// If the backing allocation fails for any reason
    pub fn with_capacity(size: usize) -> Vec<T, S> {
        let mut storage = S::default();

        Vec {
            handle: storage.allocate_single(size).unwrap(),
            len: 0,
            storage,
        }
    }
}

impl<T, S> Vec<T, S>
where
    S: Storage,
{
    /// Create a new, empty [`Vec`], using the provided storage instance.
    ///
    /// # Panics
    ///
    /// If the backing allocation fails for any reason
    pub fn new_in(mut storage: S) -> Vec<T, S> {
        Vec {
            handle: storage.allocate_single(0).unwrap(),
            len: 0,
            storage,
        }
    }

    /// Attempt to create a new, empty [`Vec`], using the provided storage instance.
    pub fn try_new_in(mut storage: S) -> Result<Vec<T, S>> {
        Ok(Vec {
            handle: storage.allocate_single(0)?,
            len: 0,
            storage,
        })
    }

    /// Create a new [`Vec`], with a pre-allocated capacity equal to `size`.
    /// Uses the provided instance of the desired storage.
    ///
    /// # Panics
    ///
    /// If the backing allocation fails for any reason
    pub fn with_capacity_in(size: usize, mut storage: S) -> Vec<T, S> {
        Vec {
            handle: storage.allocate_single(size).unwrap(),
            len: 0,
            storage,
        }
    }

    /// Check if the vector contains no element
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Get the current length of the vector
    pub fn len(&self) -> usize {
        self.len
    }

    /// Check the vector's current capacity, the maximum length it can grow to without reallocating
    pub fn capacity(&self) -> usize {
        // SAFETY: Handle is guaranteed valid by internal invariant
        let ptr = unsafe { self.storage.get(self.handle) };
        // SAFETY: Valid handles are guaranteed to return a valid pointer
        unsafe { ptr.as_ref().len() }
    }

    /// Add a new element onto the end of the vector
    pub fn push(&mut self, val: T) {
        let old_capacity = self.capacity();

        if self.len + 1 > old_capacity {
            let new_capacity = if old_capacity == 0 {
                2
            } else {
                old_capacity * 2
            };

            // SAFETY: Handle is guaranteed valid by internal invariant
            //         New capacity cannot be less than old due to how it's calculated
            unsafe {
                self.handle = self
                    .storage
                    .try_grow(self.handle, new_capacity)
                    .expect("Couldn't grow Vec buffer");
            }
        }

        // SAFETY: Handle is guaranteed valid by internal invariant
        let mut ptr = unsafe { self.storage.get(self.handle) };
        // SAFETY: Valid handles are guaranteed to return valid pointers
        unsafe { ptr.as_mut()[self.len] = MaybeUninit::new(val) };
        self.len += 1;
    }

    /// Remove the element at the end of the vector and return it
    pub fn pop(&mut self) -> T {
        self.len -= 1;

        // SAFETY: Handle is guaranteed valid by internal invariant
        let mut ptr = unsafe { self.storage.get(self.handle) };
        // SAFETY: Valid handles are guaranteed to return valid pointers
        let item = unsafe { &mut ptr.as_mut()[self.len] };
        let out = mem::replace(item, MaybeUninit::uninit());
        // SAFETY: Popped element must be initialized, as length counts initialized items
        unsafe { out.assume_init() }
    }

    /// Remove the element at a specific position in the vector and return it
    pub fn remove(&mut self, pos: usize) -> T {
        self.len -= 1;

        // SAFETY: Handle is valid by internal invariant
        let mut ptr = unsafe { self.storage.get::<[MaybeUninit<T>]>(self.handle) };

        // SAFETY: Valid handles are guaranteed to return valid pointers
        let slice = unsafe { ptr.as_mut() };
        let item = &mut slice[pos];
        let out = mem::replace(item, MaybeUninit::uninit());

        // Move all items after it back one
        // SAFETY: New range is shorter than old, so this can't overrun
        unsafe {
            ptr::copy(
                slice[pos + 1].as_ptr(),
                slice[pos].as_mut_ptr(),
                self.len - pos + 1,
            );
        }

        // SAFETY: Popped element must be initialized, as length counts initialized items
        unsafe { out.assume_init() }
    }
}

impl<T, S> fmt::Debug for Vec<T, S>
where
    T: fmt::Debug,
    S: Storage,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.as_ref())
    }
}

impl<T, S> Default for Vec<T, S>
where
    S: Storage + Default,
{
    fn default() -> Vec<T, S> {
        Vec::new()
    }
}

impl<T, S> AsRef<[T]> for Vec<T, S>
where
    S: Storage,
{
    fn as_ref(&self) -> &[T] {
        self
    }
}

impl<T, S> AsMut<[T]> for Vec<T, S>
where
    S: Storage,
{
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

impl<T, S> Borrow<[T]> for Vec<T, S>
where
    S: Storage,
{
    fn borrow(&self) -> &[T] {
        self
    }
}

impl<T, S> BorrowMut<[T]> for Vec<T, S>
where
    S: Storage,
{
    fn borrow_mut(&mut self) -> &mut [T] {
        self
    }
}

impl<T, S> Deref for Vec<T, S>
where
    S: Storage,
{
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        // SAFETY: Handle is guaranteed valid by internal invariant
        let ptr = unsafe { self.storage.get(self.handle) };
        // SAFETY: Valid handles are guaranteed to return valid pointers
        //         Length counts initialized items, safe to interpret as `T`
        unsafe { slice::from_raw_parts(ptr.cast().as_ptr(), self.len) }
    }
}

impl<T, S> DerefMut for Vec<T, S>
where
    S: Storage,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        // SAFETY: Handle is guaranteed valid by internal invariant
        let ptr = unsafe { self.storage.get(self.handle) };
        // SAFETY: Valid handles are guaranteed to return valid pointers
        //         Length counts initialized items, safe to interpret as `T`
        unsafe { slice::from_raw_parts_mut(ptr.cast().as_ptr(), self.len) }
    }
}

impl<T, S> Drop for Vec<T, S>
where
    S: Storage,
{
    fn drop(&mut self) {
        for i in self.as_mut() {
            // SAFETY: This is `drop`, so no one else will observe these values
            unsafe { ptr::drop_in_place(i) }
        }
        // SAFETY: Handle is guaranteed valid by internal invariant
        unsafe { self.storage.deallocate_single(self.handle) }
    }
}

impl<T, S> Index<usize> for Vec<T, S>
where
    S: Storage,
{
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        &self.as_ref()[index]
    }
}

impl<T, S> IndexMut<usize> for Vec<T, S>
where
    S: Storage,
{
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.as_mut()[index]
    }
}

impl<T, S> Clone for Vec<T, S>
where
    T: Clone,
    S: Storage + Clone,
{
    fn clone(&self) -> Self {
        let mut new_storage = self.storage.clone();
        let new_handle = new_storage
            .allocate_single::<[MaybeUninit<T>]>(self.len())
            .expect("Couldn't allocate new array");

        // SAFETY: New handle is guaranteed valid as allocate succeeded
        let mut ptr = unsafe { new_storage.get(new_handle) };
        // SAFETY: Valid handles are guaranteed to return valid pointers
        let new_iter = unsafe { ptr.as_mut().iter_mut() };
        for (old, new) in self.as_ref().iter().zip(new_iter) {
            new.write(old.clone());
        }

        Vec {
            handle: new_handle,
            len: self.len(),
            storage: new_storage,
        }
    }
}

impl<T, S> From<&[T]> for Vec<T, S>
where
    T: Clone,
    S: Storage + Default,
{
    fn from(val: &[T]) -> Self {
        let mut v = Vec::with_capacity(val.len());
        v.extend(val.iter().cloned());
        v
    }
}

impl<T, S, const N: usize> From<[T; N]> for Vec<T, S>
where
    S: Storage + Default,
{
    fn from(val: [T; N]) -> Self {
        let mut v = Vec::with_capacity(N);
        v.extend(val);
        v
    }
}

impl<T, S> From<(&[T], S)> for Vec<T, S>
where
    T: Clone,
    S: Storage,
{
    fn from(val: (&[T], S)) -> Self {
        let mut v = Vec::with_capacity_in(val.0.len(), val.1);
        v.extend(val.0.iter().cloned());
        v
    }
}

impl<T, S, const N: usize> From<([T; N], S)> for Vec<T, S>
where
    S: Storage,
{
    fn from(val: ([T; N], S)) -> Self {
        let mut v = Vec::with_capacity_in(N, val.1);
        v.extend(val.0);
        v
    }
}

impl<T, S> Extend<T> for Vec<T, S>
where
    S: Storage,
{
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        iter.into_iter().for_each(|i| self.push(i));
    }
}

#[cfg(test)]
mod tests {
    use crate::inline::SingleInline;

    type Vec<T> = super::Vec<T, SingleInline<[usize; 16]>>;

    #[test]
    fn vec_new() {
        let v = Vec::<u32>::new();
        assert_eq!(v.len(), 0);
        assert_eq!(v.as_ref(), &[]);
    }

    #[test]
    fn vec_push() {
        let mut v = Vec::<u32>::new();
        v.push(1);
        v.push(2);

        assert_eq!(v.len(), 2);
        assert_eq!(v.as_ref(), &[1, 2]);
    }

    #[test]
    fn vec_pop() {
        let mut v = Vec::<u32>::new();
        v.push(1);
        v.push(2);

        assert_eq!(v.pop(), 2);
        assert_eq!(v.pop(), 1);
        assert_eq!(v.len(), 0);
    }

    #[test]
    fn vec_clone() {
        let mut v = Vec::<u32>::new();
        v.push(1);
        v.push(2);

        let v2 = v.clone();

        assert_eq!(v2.as_ref(), &[1, 2]);
    }

    #[test]
    fn vec_zst() {
        let mut v = Vec::<()>::new();
        v.push(());
        v.pop();
    }
}