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
use crate::region::Region;

use std::alloc::Layout;
use std::ops;

pub struct Header {
    /// A function that causes an item to be dropped.
    drop_fn: Option<fn(*mut u8)>,
}

/// A handle to an allocated object of a dynamic vector.
pub struct Handle<T> {
    ptr: *mut T,
}

impl<T> Clone for Handle<T> {
    fn clone(&self) -> Self {
        Self { ptr: self.ptr }
    }
}

impl<T> Copy for Handle<T> {}

impl<T> Handle<T> {
    /// Turns this `Handle` into a `RawHandle`.
    pub fn raw(self) -> RawHandle {
        RawHandle {
            ptr: self.ptr as *mut u8,
        }
    }
}

/// A handle to an allocated object of a dynamic vector that does
/// not own a `T`.
pub struct RawHandle {
    ptr: *mut u8,
}

impl Clone for RawHandle {
    fn clone(&self) -> Self {
        Self { ptr: self.ptr }
    }
}

impl Copy for RawHandle {}

impl<T> From<Handle<T>> for RawHandle {
    fn from(handle: Handle<T>) -> Self {
        handle.raw()
    }
}

impl RawHandle {
    /// Turns this `RawHandle` into a normal one, given it a type.
    ///
    /// # Safety
    /// The type `T` must be the one that created the raw handle.
    pub unsafe fn trust_type<T>(self) -> Handle<T> {
        Handle {
            ptr: self.ptr as *mut T,
        }
    }
}

/// A dynamic vector, able to store any kind of data.
#[derive(Default)]
pub struct RawDynVec<R: Region<Header>> {
    region: R,
}

impl<R: Region<Header>> Drop for RawDynVec<R> {
    fn drop(&mut self) {
        self.clear();
    }
}

impl<R: Region<Header>, T> ops::Index<Handle<T>> for RawDynVec<R> {
    type Output = T;

    fn index(&self, index: Handle<T>) -> &Self::Output {
        self.get(index)
    }
}

impl<R: Region<Header>, T> ops::IndexMut<Handle<T>> for RawDynVec<R> {
    fn index_mut(&mut self, index: Handle<T>) -> &mut Self::Output {
        self.get_mut(index)
    }
}

impl<R: Region<Header>> RawDynVec<R> {
    /// Creates a new `RawDynVec` with the given region.
    pub fn with_region(region: R) -> Self {
        Self { region }
    }

    /// Returns the number of items this vector stores.
    pub fn count(&self) -> usize {
        self.region.count()
    }

    /// Tries to insert a `T` into the vector and returns a Handle
    /// to this `T`. If the `T` cannot be allocated, it gets
    /// returned as the error.
    pub fn try_insert<T>(&mut self, item: T) -> Result<Handle<T>, T> {
        let layout = Layout::new::<T>();
        
        let drop_fn: Option<fn(*mut u8)> = if std::mem::needs_drop::<T>() {
            Some(|ptr: *mut u8| unsafe { std::ptr::drop_in_place(ptr as *mut T) })
        } else {
            None
        };
        
        match unsafe { self.insert_raw(layout, drop_fn) } {
            Ok(handle) => {
                unsafe {
                    handle.ptr.cast::<T>().write(item);
                    Ok(handle.trust_type::<T>())
                }
            },

            Err(()) => Err(item),
        }
    }

    /// Clears the whole vector, leaving it empty.
    pub fn clear(&mut self) {
        for (ptr, header) in self.region.deallocate_all() {
            if let Some(drop_fn) = header.drop_fn {
                // the allocated item needed to be dropped
                drop_fn(ptr)
            }
        }
    }

    /// Inserts a `T` into the vector and returns a Handle to this `T`.
    ///
    /// # Panics
    /// This function panics if the `T` could not be allocated.
    pub fn insert<T>(&mut self, item: T) -> Handle<T> {
        match self.try_insert(item) {
            Ok(handle) => handle,
            Err(_) => {
                panic!("Failed to allocate the item");
            }
        }
    }

    /// Allocates memory as described by the given layout. If the allocation
    /// is a success, a raw handle to the allocation is returned. In this case,
    /// it is up to the caller to initialize the allocated value because the
    /// vector now assumes it is initialized.
    /// 
    /// # Safety
    /// * The `drop_fn` function must cause the object to be dropped.
    /// * The allocated data must get initialized before it being dropped.
    pub unsafe fn insert_raw(
        &mut self,
        layout: Layout,
        drop_fn: Option<fn(*mut u8)>,
    ) -> Result<RawHandle, ()> {
        let header = Header {
            drop_fn,
        };

        match self.region.allocate(layout, header) {
            Ok(ptr) => {
                Ok(RawHandle { ptr, })
            }

            Err(_) => Err(()),
        }
    }

    /// Tries to remove the `T` located by the given handle. If the handle
    /// was invalid, `Err(())` is returned.
    pub fn remove<T>(&mut self, handle: Handle<T>) -> Result<T, ()> {
        if let Some(_) = self.region.deallocate(handle.ptr as *mut u8) {
            // the region successfuly deallocated the object
            // this means that we were able to initialize it before
            let item = unsafe { handle.ptr.read() };

            // we don't need to drop the item
            // this will be up to the caller
            Ok(item)
        } else {
            Err(())
        }
    }

    /// Tries to remove an item out of the vector. If the handle was
    /// invalid `Err(())` is returned.
    ///
    /// As the handle is raw, the item cannot be returned. But it is
    /// still dropped properly.
    pub fn remove_raw(&mut self, handle: RawHandle) -> Result<(), ()> {
        if let Some(header) = self.region.deallocate(handle.ptr) {
            if let Some(drop_fn) = header.drop_fn {
                // the item needed to be dropped
                drop_fn(handle.ptr);
            }

            Ok(())
        } else {
            Err(())
        }
    }

    /// Gets a pointer to the data located by the given handle.
    ///
    /// # Safety
    /// If the null pointer is returned, the handle was invalid.
    pub fn get_ptr<T>(&self, handle: Handle<T>) -> *const T {
        if self.region.has_allocated(handle.ptr as *mut u8) {
            handle.ptr
        } else {
            std::ptr::null()
        }
    }

    /// Gets a pointer to the data located by the given handle.
    ///
    /// # Safety
    /// If the null pointer is returned, the handle was invalid.
    pub fn get_mut_ptr<T>(&self, handle: Handle<T>) -> *mut T {
        if self.region.has_allocated(handle.ptr as *mut u8) {
            handle.ptr
        } else {
            std::ptr::null_mut()
        }
    }

    /// Gets a pointer to the data located by the given handle.
    ///
    /// # Safety
    /// If the null pointer is returned, the handle was invalid.
    pub fn get_ptr_raw(&mut self, handle: RawHandle) -> *const u8 {
        if self.region.has_allocated(handle.ptr) {
            handle.ptr
        } else {
            std::ptr::null()
        }
    }

    /// Gets a pointer to the data located by the given handle.
    ///
    /// # Safety
    /// If the null pointer is returned, the handle was invalid.
    pub fn get_mut_ptr_raw(&mut self, handle: RawHandle) -> *mut u8 {
        if self.region.has_allocated(handle.ptr) {
            handle.ptr
        } else {
            std::ptr::null_mut()
        }
    }

    /// Tries to get a reference to the data located by the given handle.
    pub fn try_get<T>(&self, handle: Handle<T>) -> Option<&T> {
        // if the handle is invalid, the null pointer is returned
        // this will transmute into `None`
        unsafe { std::mem::transmute(self.get_ptr(handle)) }
    }

    /// Tries to get a reference to the data located by the given handle.
    pub fn try_get_mut<T>(&mut self, handle: Handle<T>) -> Option<&mut T> {
        unsafe { std::mem::transmute(self.get_mut_ptr(handle)) }
    }

    /// Gets a reference to the data located by the given handle.
    ///
    /// # Panics
    /// If the handle is valid, this function panics.
    pub fn get<T>(&self, handle: Handle<T>) -> &T {
        self.try_get(handle).expect("Invalid handle")
    }

    /// Gets a reference to the data located by the given handle.
    ///
    /// # Panics
    /// If the handle is valid, this function panics.
    pub fn get_mut<T>(&mut self, handle: Handle<T>) -> &mut T {
        self.try_get_mut(handle).expect("Invalid handle")
    }
}

#[cfg(test)]
#[test]
fn properly_dropped() {
    use std::cell::Cell;
    use std::rc::Rc;

    use crate::region::block::Block;

    let drop_count = Rc::new(Cell::new(0u16));
    struct DropCheck(Rc<Cell<u16>>);
    impl Drop for DropCheck {
        fn drop(&mut self) {
            self.0.set(self.0.get() + 1);
        }
    }

    {
        let mut vec = RawDynVec::with_region(Block::new(2048));

        for _ in 0..100 {
            vec.insert(DropCheck(Rc::clone(&drop_count)));
        }

        // vec should be dropped now
    }

    assert_eq!(drop_count.get(), 100);
}

#[cfg(test)]
#[test]
fn normal_use() {
    use crate::region::block::Block;

    let mut vec = RawDynVec::with_region(Block::new(2048));

    let h_i32 = vec.insert(5i32);
    let h_vec = vec.insert(vec![1u8, 2, 3]);

    assert_eq!(vec[h_i32], 5i32);
    assert_eq!(vec[h_vec][1], 2u8);

    vec[h_vec].push(8);

    assert_eq!(vec.get(h_vec).last(), Some(&8));

    let other_vec = vec.remove(h_vec).unwrap();

    assert_eq!(&other_vec[..], &[1, 2, 3, 8][..]);

    assert_eq!(vec.try_get(h_vec), None);
}