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
//! Kioku is a growable memory arena/pool

#![allow(clippy::redundant_field_names)]
#![allow(clippy::needless_return)]
#![allow(clippy::mut_from_ref)]
#![allow(clippy::transmute_ptr_to_ptr)]

use std::{
    cell::{Cell, RefCell},
    cmp::max,
    fmt,
    mem::{align_of, size_of, transmute, MaybeUninit},
    slice,
};

const GROWTH_FRACTION: usize = 8; // 1/N  (smaller number leads to bigger allocations)
const DEFAULT_MIN_BLOCK_SIZE: usize = 1 << 10; // 1 KiB
const DEFAULT_MAX_WASTE_PERCENTAGE: usize = 10;

fn alignment_offset(addr: usize, alignment: usize) -> usize {
    (alignment - (addr % alignment)) % alignment
}

/// A growable memory arena for Copy types.
///
/// The arena works by allocating memory in blocks of slowly increasing size.
/// It doles out memory from the current block until an amount of memory is
/// requested that doesn't fit in the remainder of the current block, and then
/// allocates a new block.
///
/// Additionally, it attempts to minimize wasted space through some heuristics.
/// By default, it tries to keep memory waste within the arena below 10%.
#[derive(Default)]
pub struct Arena {
    blocks: RefCell<Vec<Vec<MaybeUninit<u8>>>>,
    min_block_size: usize,
    max_waste_percentage: usize,
    stat_space_occupied: Cell<usize>,
    stat_space_allocated: Cell<usize>,
}

impl fmt::Debug for Arena {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Arena")
            .field("blocks.len():", &self.blocks.borrow().len())
            .field("min_block_size", &self.min_block_size)
            .field("max_waste_percentage", &self.max_waste_percentage)
            .field("stat_space_occupied", &self.stat_space_occupied)
            .field("stat_space_allocated", &self.stat_space_allocated)
            .finish()
    }
}

impl Arena {
    /// Create a new arena, with default minimum block size.
    pub fn new() -> Arena {
        Arena {
            blocks: RefCell::new(vec![Vec::with_capacity(DEFAULT_MIN_BLOCK_SIZE)]),
            min_block_size: DEFAULT_MIN_BLOCK_SIZE,
            max_waste_percentage: DEFAULT_MAX_WASTE_PERCENTAGE,
            stat_space_occupied: Cell::new(DEFAULT_MIN_BLOCK_SIZE),
            stat_space_allocated: Cell::new(0),
        }
    }

    /// Create a new arena, with a specified minimum block size.
    pub fn with_min_block_size(min_block_size: usize) -> Arena {
        assert!(min_block_size > 0);

        Arena {
            blocks: RefCell::new(vec![Vec::with_capacity(min_block_size)]),
            min_block_size: min_block_size,
            max_waste_percentage: DEFAULT_MAX_WASTE_PERCENTAGE,
            stat_space_occupied: Cell::new(min_block_size),
            stat_space_allocated: Cell::new(0),
        }
    }

    /// Create a new arena, with a specified minimum block size and maximum
    /// waste percentage.
    pub fn with_settings(min_block_size: usize, max_waste_percentage: usize) -> Arena {
        assert!(min_block_size > 0);
        assert!(max_waste_percentage > 0 && max_waste_percentage <= 100);

        Arena {
            blocks: RefCell::new(vec![Vec::with_capacity(min_block_size)]),
            min_block_size: min_block_size,
            max_waste_percentage: max_waste_percentage,
            stat_space_occupied: Cell::new(min_block_size),
            stat_space_allocated: Cell::new(0),
        }
    }

    /// Returns statistics about the current usage as a tuple:
    /// (space occupied, space allocated, block count, large block count)
    ///
    /// Space occupied is the amount of real memory that the Arena
    /// is taking up (not counting book keeping).
    ///
    /// Space allocated is the amount of the occupied space that is
    /// actually used.  In other words, it is the sum of the all the
    /// allocation requests made to the arena by client code.
    ///
    /// Block count is the number of blocks that have been allocated.
    pub fn stats(&self) -> (usize, usize, usize) {
        let occupied = self.stat_space_occupied.get();
        let allocated = self.stat_space_allocated.get();
        let blocks = self.blocks.borrow().len();

        (occupied, allocated, blocks)
    }

    /// Frees all memory currently allocated by the arena, resetting itself to
    /// start fresh.
    ///
    /// CAUTION: this is unsafe because it does NOT ensure that all references
    /// to the data are gone, so this can potentially lead to dangling
    /// references.
    pub unsafe fn free_all_and_reset(&self) {
        let mut blocks = self.blocks.borrow_mut();

        blocks.clear();
        blocks.shrink_to_fit();
        blocks.push(Vec::with_capacity(self.min_block_size));

        self.stat_space_occupied.set(self.min_block_size);
        self.stat_space_allocated.set(0);
    }

    /// Allocates memory for and initializes a type T, returning a mutable
    /// reference to it.
    pub fn alloc<T: Copy>(&self, value: T) -> &mut T {
        let memory = self.alloc_uninitialized();
        unsafe {
            *memory.as_mut_ptr() = value;
        }
        unsafe { transmute(memory) }
    }

    /// Allocates memory for and initializes a type T, returning a mutable
    /// reference to it.
    ///
    /// Additionally, the allocation will be made with the given byte alignment
    /// or the type's inherent alignment, whichever is greater.
    pub fn alloc_with_alignment<T: Copy>(&self, value: T, align: usize) -> &mut T {
        let memory = self.alloc_uninitialized_with_alignment(align);
        unsafe {
            *memory.as_mut_ptr() = value;
        }
        unsafe { transmute(memory) }
    }

    /// Allocates memory for a type `T`, returning a mutable reference to it.
    ///
    /// CAUTION: the memory returned is uninitialized.  Make sure to initalize
    /// before using!
    pub fn alloc_uninitialized<T: Copy>(&self) -> &mut MaybeUninit<T> {
        assert!(size_of::<T>() > 0);

        let memory = self.alloc_raw(size_of::<T>(), align_of::<T>()) as *mut MaybeUninit<T>;

        unsafe { memory.as_mut().unwrap() }
    }

    /// Allocates memory for a type `T`, returning a mutable reference to it.
    ///
    /// Additionally, the allocation will be made with the given byte alignment
    /// or the type's inherent alignment, whichever is greater.
    ///
    /// CAUTION: the memory returned is uninitialized.  Make sure to initalize
    /// before using!
    pub fn alloc_uninitialized_with_alignment<T: Copy>(&self, align: usize) -> &mut MaybeUninit<T> {
        assert!(size_of::<T>() > 0);

        let memory =
            self.alloc_raw(size_of::<T>(), max(align, align_of::<T>())) as *mut MaybeUninit<T>;

        unsafe { memory.as_mut().unwrap() }
    }

    /// Allocates memory for `len` values of type `T`, returning a mutable
    /// slice to it.  All elements are initialized to the given `value`.
    pub fn alloc_array<T: Copy>(&self, len: usize, value: T) -> &mut [T] {
        let memory = self.alloc_array_uninitialized(len);

        for v in memory.iter_mut() {
            unsafe {
                *v.as_mut_ptr() = value;
            }
        }

        unsafe { transmute(memory) }
    }

    /// Allocates memory for `len` values of type `T`, returning a mutable
    /// slice to it. All elements are initialized to the given `value`.
    ///
    /// Additionally, the allocation will be made with the given byte alignment
    /// or the type's inherent alignment, whichever is greater.
    pub fn alloc_array_with_alignment<T: Copy>(
        &self,
        len: usize,
        value: T,
        align: usize,
    ) -> &mut [T] {
        let memory = self.alloc_array_uninitialized_with_alignment(len, align);

        for v in memory.iter_mut() {
            unsafe {
                *v.as_mut_ptr() = value;
            }
        }

        unsafe { transmute(memory) }
    }

    /// Allocates and initializes memory to duplicate the given slice,
    /// returning a mutable slice to the new copy.
    pub fn copy_slice<T: Copy>(&self, other: &[T]) -> &mut [T] {
        let memory = self.alloc_array_uninitialized(other.len());

        for (v, other) in memory.iter_mut().zip(other.iter()) {
            unsafe {
                *v.as_mut_ptr() = *other;
            }
        }

        unsafe { transmute(memory) }
    }

    /// Allocates and initializes memory to duplicate the given slice,
    /// returning a mutable slice to the new copy.
    ///
    /// Additionally, the allocation will be made with the given byte alignment
    /// or the type's inherent alignment, whichever is greater.
    pub fn copy_slice_with_alignment<T: Copy>(&self, other: &[T], align: usize) -> &mut [T] {
        let memory = self.alloc_array_uninitialized_with_alignment(other.len(), align);

        for (v, other) in memory.iter_mut().zip(other.iter()) {
            unsafe {
                *v.as_mut_ptr() = *other;
            }
        }

        unsafe { transmute(memory) }
    }

    /// Allocates memory for `len` values of type `T`, returning a mutable
    /// slice to it.
    ///
    /// CAUTION: the memory returned is uninitialized.  Make sure to initalize
    /// before using!
    pub fn alloc_array_uninitialized<T: Copy>(&self, len: usize) -> &mut [MaybeUninit<T>] {
        assert!(size_of::<T>() > 0);

        let array_mem_size = {
            let alignment_padding = alignment_offset(size_of::<T>(), align_of::<T>());
            let aligned_type_size = size_of::<T>() + alignment_padding;
            aligned_type_size * len
        };

        let memory = self.alloc_raw(array_mem_size, align_of::<T>()) as *mut MaybeUninit<T>;

        unsafe { slice::from_raw_parts_mut(memory, len) }
    }

    /// Allocates memory for `len` values of type `T`, returning a mutable
    /// slice to it.
    ///
    /// Additionally, the allocation will be made with the given byte alignment
    /// or the type's inherent alignment, whichever is greater.
    ///
    /// CAUTION: the memory returned is uninitialized.  Make sure to initalize
    /// before using!
    pub fn alloc_array_uninitialized_with_alignment<T: Copy>(
        &self,
        len: usize,
        align: usize,
    ) -> &mut [MaybeUninit<T>] {
        assert!(size_of::<T>() > 0);

        let array_mem_size = {
            let alignment_padding = alignment_offset(size_of::<T>(), align_of::<T>());
            let aligned_type_size = size_of::<T>() + alignment_padding;
            aligned_type_size * len
        };

        let memory =
            self.alloc_raw(array_mem_size, max(align, align_of::<T>())) as *mut MaybeUninit<T>;

        unsafe { slice::from_raw_parts_mut(memory, len) }
    }

    /// Allocates space with a given size and alignment.
    ///
    /// This is the work-horse code of the Arena.
    ///
    /// CAUTION: this returns uninitialized memory.  Make sure to initialize
    /// the memory after calling.
    fn alloc_raw(&self, size: usize, alignment: usize) -> *mut MaybeUninit<u8> {
        assert!(alignment > 0);

        self.stat_space_allocated
            .set(self.stat_space_allocated.get() + size); // Update stats

        let mut blocks = self.blocks.borrow_mut();

        // If it's a zero-size allocation, just point to the beginning of the current block.
        if size == 0 {
            return blocks.first_mut().unwrap().as_mut_ptr();
        }
        // If it's non-zero-size.
        else {
            let start_index = {
                let block_addr = blocks.first().unwrap().as_ptr() as usize;
                let block_filled = blocks.first().unwrap().len();
                block_filled + alignment_offset(block_addr + block_filled, alignment)
            };

            // If it will fit in the current block, use the current block.
            if (start_index + size) <= blocks.first().unwrap().capacity() {
                unsafe {
                    blocks.first_mut().unwrap().set_len(start_index + size);
                }

                let block_ptr = blocks.first_mut().unwrap().as_mut_ptr();
                return unsafe { block_ptr.add(start_index) };
            }
            // If it won't fit in the current block, create a new block and use that.
            else {
                let next_size = if blocks.len() >= GROWTH_FRACTION {
                    let a = self.stat_space_occupied.get() / GROWTH_FRACTION;
                    let b = a % self.min_block_size;
                    if b > 0 {
                        a - b + self.min_block_size
                    } else {
                        a
                    }
                } else {
                    self.min_block_size
                };

                let waste_percentage = {
                    let w1 =
                        ((blocks[0].capacity() - blocks[0].len()) * 100) / blocks[0].capacity();
                    let w2 = ((self.stat_space_occupied.get() - self.stat_space_allocated.get())
                        * 100)
                        / self.stat_space_occupied.get();
                    if w1 < w2 {
                        w1
                    } else {
                        w2
                    }
                };

                // If it's a "large allocation", give it its own memory block.
                if (size + alignment) > next_size || waste_percentage > self.max_waste_percentage {
                    // Update stats
                    self.stat_space_occupied
                        .set(self.stat_space_occupied.get() + size + alignment - 1);

                    blocks.push(Vec::with_capacity(size + alignment - 1));
                    unsafe {
                        blocks.last_mut().unwrap().set_len(size + alignment - 1);
                    }

                    let start_index =
                        alignment_offset(blocks.last().unwrap().as_ptr() as usize, alignment);

                    let block_ptr = blocks.last_mut().unwrap().as_mut_ptr();
                    return unsafe { block_ptr.add(start_index) };
                }
                // Otherwise create a new shared block.
                else {
                    // Update stats
                    self.stat_space_occupied
                        .set(self.stat_space_occupied.get() + next_size);

                    blocks.push(Vec::with_capacity(next_size));
                    let block_count = blocks.len();
                    blocks.swap(0, block_count - 1);

                    let start_index =
                        alignment_offset(blocks.first().unwrap().as_ptr() as usize, alignment);

                    unsafe {
                        blocks.first_mut().unwrap().set_len(start_index + size);
                    }

                    let block_ptr = blocks.first_mut().unwrap().as_mut_ptr();
                    return unsafe { block_ptr.add(start_index) };
                }
            }
        }
    }
}