heaparray 0.2.0

Heap-allocated array with optional metadata field
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
//! Memory blocks that can hold arbitrary data on the heap.
//! Used to represent the data that all the other types point to.
//!
//! It's not recommended to use these directly; instead, use the pointer types
//! that refer to these, namely `HeapArray`, `FatPtrArray`, and `ThinPtrArray`.
//!
//! *NOTE:* `TPArrayBlock` is marked by the compiler as "Sized". This is incorrect,
//! and thus it's not suggested that you use this type directly. It's suggested
//! that you use one of either `FatPtrArray` or `ThinPtrArray`, cooresponding to
//! `FPArrayBlock` and `TPArrayBlock` respectively.
//!
//! # Invariants
//! These are assumptions that safe code follows, and are maintained by the safe
//! subset of the API to this struct. Please note that the unsafe API does NOT
//! maintain these invariants, but still assumes them to be true.
//!
//! - A valid memory block cannot have a `len` of `core::usize::MAX`.
//! - A valid memory block cannot have an valid index that overflows a `usize`
//! - A valid reference to a memory block cannot have the value of `core::usize::MAX`
//! - A valid memory block will not be zero-sized
//! - A valid thin-pointer memory block has a correctly set capacity.
//!
//! The invariants above are used to reduce the number of checks in the safe API,
//! as well as to have consistent definitions for null pointers. Again, note that
//! calls to unsafe functions do *NOT* check these invariants for you when doing
//! things like constructing new types.
use super::alloc_utils::*;
use core::mem;
use core::ops::{Index, IndexMut};
pub const NULL: usize = core::usize::MAX;
use core::mem::ManuallyDrop;

// TODO Make this function a const function when if statements are stabilized in
// const functions
/// Get the maximum length of a memory block, based on the types that it contains.
/// Maintains the invariants discussed above.
pub fn block_max_len<E, L>() -> usize {
    use core::usize::MAX as MAX_LEN;
    let elem_size = mem::size_of::<E>();
    let label_size = mem::size_of::<L>();
    if elem_size == 0 {
        MAX_LEN - 1
    } else {
        (MAX_LEN - label_size) / elem_size - 1
    }
}

/// This function checks that the given array block pointer is valid, and if it
/// isn't, it panics with an error message. This prevents unsafe code from seg-faulting
/// when corrupt memory is about to be access, but it's a comparison AND a memory
/// dereference, so it's only enabled during testing.
#[cfg(test)]
fn check_null_tp<E, L>(arr: &TPArrayBlock<E, L>, message: &'static str) {
    assert!(
        arr as *const TPArrayBlock<E, L> as usize != NULL && arr.len != NULL,
        message
    );
}

/// This function checks that the given array block pointer is valid, and if it
/// isn't, it panics with an error message. This prevents unsafe code from seg-faulting
/// when corrupt memory is about to be access, but it's two extra comparisons,
/// so it's only enabled during testing.
#[cfg(test)]
fn check_null_fp<E, L>(arr: &FPArrayBlock<E, L>, message: &'static str) {
    assert!(
        arr.elements.len() != NULL && (&arr.label as *const L as usize) != NULL,
        message
    );
}

/// An array block that keeps size information in the block itself.
/// Can additionally hold arbitrary information about the elements in the container,
/// through the `L` generic type.
///
/// TP stands for Thin Pointer, as the pointer to this block is a single pointer.
#[repr(C)]
pub struct TPArrayBlock<E, L = ()> {
    /// Metadata about the block
    pub label: L,
    /// Capacity of the block
    len: usize,
    /// First element in the block
    elements: ManuallyDrop<E>,
}

impl<E, L> TPArrayBlock<E, L> {
    /// Get size and alignment of the memory that this struct uses.
    pub fn memory_layout(len: usize) -> (usize, usize) {
        let l_layout = size_align::<Self>();
        if len <= 1 {
            l_layout
        } else {
            let d_layout = size_align_array::<E>(len - 1);
            size_align_multiple(&[l_layout, size_align::<usize>(), d_layout])
        }
    }

    /// Deallocates a reference to this struct, as well as all objects contained
    /// in it.
    pub unsafe fn dealloc<'a>(&'a mut self) {
        #[cfg(test)]
        check_null_tp(self, "TPArrayBlock::dealloc: Deallocating null pointer!");
        for i in 0..self.len {
            let val = mem::transmute_copy(&self[i]);
            mem::drop::<E>(val);
        }
        let (size, align) = Self::memory_layout(self.len);
        deallocate(self, size, align);
    }

    /// Get a mutable reference to a new block. Array elements are initialized to
    /// garbage (i.e. they are not initialized).
    pub unsafe fn new_ptr_unsafe<'a>(label: L, len: usize) -> &'a mut Self {
        let (size, align) = Self::memory_layout(len);
        let new_ptr = allocate::<Self>(size, align);
        new_ptr.label = label;
        new_ptr.len = len;
        #[cfg(test)]
        check_null_tp(
            new_ptr,
            "TPArrayBlock::new_ptr_unsafe: Allocated null pointer!",
        );
        new_ptr
    }

    /// Returns a null pointer to a memory block. Dereferencing it is undefined
    /// behavior.
    pub unsafe fn null_ptr() -> *mut Self {
        NULL as *mut Self
    }

    /// Uses the invariants discussed above to check whether a reference to a
    /// memory block is null or not. Shouldn't be necessary unless you're using
    /// the unsafe API.
    pub fn is_null(&self) -> bool {
        self as *const Self as usize == NULL
    }

    /// Create a new pointer to an array, using a function to initialize all the
    /// elements.
    pub fn new_ptr<'a, F>(label: L, len: usize, mut func: F) -> &'a mut Self
    where
        F: FnMut(&mut L, usize) -> E,
    {
        assert!(len <= block_max_len::<E, L>());
        let new_ptr = unsafe { Self::new_ptr_unsafe(label, len) };
        for i in 0..new_ptr.len {
            let item = func(&mut new_ptr.label, i);
            let garbage = mem::replace(new_ptr.get_mut(i), item);
            mem::forget(garbage);
            //*item_ref = item; // FIXME Malloc error happening right here. Why?
        }
        new_ptr
    }

    /// Get a reference to an element in this memory block.
    pub fn get<'a>(&'a self, idx: usize) -> &'a E {
        #[cfg(test)]
        check_null_tp(self, "TPArrayBlock::get: Immutable access of null pointer!");
        assert!(idx < self.len);
        unsafe { self.unchecked_access(idx) }
    }

    /// Get a mutable reference to an element in this memory block.
    pub fn get_mut<'a>(&'a mut self, idx: usize) -> &'a mut E {
        #[cfg(test)]
        check_null_tp(
            self,
            "TPArrayBlock::get_mut: Mutable access of null pointer!",
        );
        assert!(idx < self.len);
        unsafe { self.unchecked_access(idx) }
    }

    /// Unsafe access to an element at an index in the block.
    pub unsafe fn unchecked_access<'a>(&'a self, idx: usize) -> &'a mut E {
        #[cfg(test)]
        check_null_tp(
            self,
            "TPArrayBlock::unchecked_access: Memory access on null pointer!",
        );
        let element = &*self.elements as *const E as *mut E;
        let element = element.add(idx);
        &mut *element
    }

    /// Unsafe access to the label of the block.
    pub unsafe fn get_label_unsafe(&self) -> &mut L {
        #[cfg(test)]
        check_null_tp(
            self,
            "TPArrayBlock::get_label_unsafe: Memory access on null pointer!",
        );
        &mut *(&self.label as *const L as *mut L)
    }

    /// Get the capacity of this memory block.
    pub fn len(&self) -> usize {
        #[cfg(test)]
        check_null_tp(self, "TPArrayBlock::len: Length check of null pointer!");
        self.len
    }
    pub fn set_len(&mut self, len: usize) {
        #[cfg(test)]
        check_null_tp(
            self,
            "TPArrayBlock::set_len: Length assignment of null pointer!",
        );
        debug_assert!(self.len >= len);
        self.len = len;
    }
}

impl<E, L> TPArrayBlock<E, L>
where
    E: Default,
{
    /// Get a mutable reference to a new block.
    pub fn new_ptr_default<'a>(label: L, len: usize) -> &'a mut Self {
        let new_ptr = Self::new_ptr(label, len, |_, _| E::default());
        new_ptr
    }
}

impl<E, L> Index<usize> for TPArrayBlock<E, L> {
    type Output = E;
    fn index(&self, idx: usize) -> &E {
        self.get(idx)
    }
}

impl<E, L> IndexMut<usize> for TPArrayBlock<E, L> {
    fn index_mut(&mut self, index: usize) -> &mut E {
        self.get_mut(index)
    }
}

impl<E, L> Clone for &mut TPArrayBlock<E, L>
where
    L: Clone,
    E: Clone,
{
    fn clone(&self) -> Self {
        let new_ptr =
            TPArrayBlock::new_ptr(self.label.clone(), self.len(), |_, idx| self[idx].clone());
        new_ptr
    }
}

/// An array block that keeps size information in the pointer to the block.
/// Can additionally hold arbitrary information about the elements in the container,
/// through the `L` generic type.
///
/// FP stands for Fat Pointer, as the pointer to this block is a pointer and an
/// associated capacity.
#[repr(C)]
pub struct FPArrayBlock<E, L = ()> {
    /// Metadata about the block
    pub label: L,
    /// Slice of elememnts in the block
    pub elements: [E],
}

impl<E, L> FPArrayBlock<E, L> {
    /// Get size and alignment of the memory that this struct uses.
    fn memory_layout(len: usize) -> (usize, usize) {
        let l_layout = size_align::<L>();
        let d_layout = size_align_array::<E>(len);
        size_align_multiple(&[l_layout, d_layout])
    }

    /// Get a mutable reference to a new block. Array elements are initialized to
    /// garbage (i.e. they are not initialized).
    pub unsafe fn new_ptr_unsafe<'a>(label: L, len: usize) -> &'a mut Self {
        let (size, align) = Self::memory_layout(len);
        let new_ptr = allocate::<E>(size, align);
        let new_ptr = core::slice::from_raw_parts(new_ptr, len);
        let new_ptr = &mut *(new_ptr as *const [E] as *mut [E] as *mut Self);
        #[cfg(test)]
        check_null_fp(
            new_ptr,
            "FPArrayBlock::new_ptr_unsafe: Allocated null pointer!",
        );
        new_ptr.label = label;
        new_ptr
    }

    /// Deallocates a reference to this struct, as well as all objects contained
    /// in it.
    pub unsafe fn dealloc<'a>(&'a mut self) {
        #[cfg(test)]
        check_null_fp(self, "FPArrayBlock::dealloc: Deallocating null pointer!");

        for i in 0..self.elements.len() {
            let val = mem::transmute_copy(&self[i]);
            mem::drop::<E>(val);
        }
        let (size, align) = Self::memory_layout(self.elements.len());
        deallocate(&mut self.label, size, align);
    }

    /// Returns a null pointer to a memory block. Dereferencing it is undefined
    /// behavior.
    pub unsafe fn null_ptr() -> *mut Self {
        let new_ptr = core::slice::from_raw_parts(NULL as *const E, NULL);
        &mut *(new_ptr as *const [E] as *mut [E] as *mut Self)
    }

    /// Uses the invariants discussed above to check whether a reference to a
    /// memory block is null or not. Shouldn't be necessary unless you're using
    /// the unsafe API.
    pub fn is_null(&self) -> bool {
        (&self.label as *const L as usize) == NULL
    }

    /// Create a new pointer to an array, using a function to initialize all the
    /// elements
    pub fn new_ptr<'a, F>(label: L, len: usize, mut func: F) -> &'a mut Self
    where
        F: FnMut(&mut L, usize) -> E,
    {
        assert!(len <= block_max_len::<E, L>());
        let new_ptr = unsafe { Self::new_ptr_unsafe(label, len) };
        for i in 0..new_ptr.len() {
            let item = func(&mut new_ptr.label, i);
            let garbage = mem::replace(new_ptr.get_mut(i), item);
            mem::forget(garbage);
        }
        new_ptr
    }

    /// Get a reference to an element in this memory block.
    pub fn get<'a>(&'a self, idx: usize) -> &'a E {
        #[cfg(test)]
        check_null_fp(self, "FPArrayBlock::get: Immutable access of null pointer!");
        assert!(idx < self.len());
        &self.elements[idx]
    }

    /// Get a mutable reference to an element in this memory block.
    pub fn get_mut<'a>(&'a mut self, idx: usize) -> &'a mut E {
        #[cfg(test)]
        check_null_fp(
            self,
            "FPArrayBlock::get_mut: Mutable access of null pointer!",
        );
        assert!(idx < self.len());
        &mut self.elements[idx]
    }

    /// Unsafe access to an element at an index in the block.
    pub unsafe fn unchecked_access(&self, idx: usize) -> &mut E {
        #[cfg(test)]
        check_null_fp(
            self,
            "FPArrayBlock::unchecked_access: Memory access of null pointer!",
        );
        let mut_self = &mut *(self as *const Self as *mut Self);
        mut_self.elements.get_unchecked_mut(idx)
    }

    /// Unsafe access to the label of the block.
    pub unsafe fn get_label_unsafe(&self) -> &mut L {
        #[cfg(test)]
        check_null_fp(
            self,
            "FPArrayBlock::get_label_unsafe: Memory access of null pointer!",
        );
        &mut *(&self.label as *const L as *mut L)
    }

    /// Get the capacity of this memory block
    pub fn len(&self) -> usize {
        #[cfg(test)]
        check_null_fp(self, "FPArrayBlock::len: Length check on null pointer!");
        self.elements.len()
    }
}

impl<E, L> FPArrayBlock<E, L>
where
    E: Default,
{
    /// Get a mutable reference to a new block, initialized to default values.
    pub fn new_ptr_default<'a>(label: L, len: usize) -> &'a mut Self {
        let new_ptr = Self::new_ptr(label, len, |_, _| E::default());
        new_ptr
    }
}

impl<E, L> Index<usize> for FPArrayBlock<E, L> {
    type Output = E;
    fn index(&self, index: usize) -> &E {
        assert!(index < self.len());
        self.get(index)
    }
}

impl<E, L> IndexMut<usize> for FPArrayBlock<E, L> {
    fn index_mut(&mut self, index: usize) -> &mut E {
        self.get_mut(index)
    }
}

impl<E, L> Clone for &mut FPArrayBlock<E, L>
where
    L: Clone,
    E: Clone,
{
    fn clone(&self) -> Self {
        let new_ptr =
            FPArrayBlock::new_ptr(self.label.clone(), self.len(), |_, idx| self[idx].clone());
        new_ptr
    }
}