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
#![feature(allocator_api, alloc_layout_extra, ptr_offset_from)]
use std::ops::{Deref, DerefMut};
use std::{ptr, slice};
use std::cell::RefCell;
use std::mem::{size_of, align_of};
use std::alloc::*;
use std::iter::*;
struct Heap {
bottom: *mut u8,
top: *mut u8,
current: *mut u8,
}
fn align<T>(value: *mut u8) -> *mut u8 {
unsafe { value.add(value.align_offset(align_of::<T>())) }
}
impl Heap {
pub fn usable_size<T>(&self) -> usize {
let aligned = align::<T>(self.current);
let bytes_remaining = unsafe { self.top.offset_from(aligned) };
if bytes_remaining < 0 { 0 } else {
match size_of::<T>() {
0 => std::isize::MAX as usize,
_ => bytes_remaining as usize / size_of::<T>()
}
}
}
pub fn slice<T>(&mut self, count: usize, pool_index: usize) -> StackAlloc<T> {
debug_assert!(self.usable_size::<T>() >= count);
let layout = Layout::new::<T>().repeat(count).unwrap().0;
let restore = self.current;
let base = align::<T>(restore);
self.current = unsafe { base.add(layout.size()) };
StackAlloc {
len: count,
ptr: base as *mut T,
restore,
pool_alloc: pool_index,
}
}
fn layout_u8(size_in_bytes: usize) -> Layout {
Layout::new::<u8>().repeat(size_in_bytes).unwrap().0
}
#[cfg(debug_assertions)]
fn contains(&self, p: *mut u8) -> bool {
unsafe {
!self.bottom.is_null() &&
p.offset_from(self.bottom) >= 0
&& self.top.offset_from(p) >= 0
}
}
pub fn release(&mut self, p: *mut u8) {
#[cfg(debug_assertions)]
debug_assert!(self.contains(p));
unsafe { debug_assert!(p.offset_from(self.current) <= 0, "Out of order release"); }
self.current = p;
}
pub fn bytes_used(&self) -> usize {
unsafe { self.current.offset_from(self.bottom) as usize }
}
pub fn bytes_total(&self) -> usize {
unsafe { self.top.offset_from(self.bottom) as usize }
}
pub fn new(size_in_bytes: usize) -> Heap {
debug_assert!(size_in_bytes >= size_for_i(0));
let layout = Self::layout_u8(size_in_bytes);
debug_assert!(size_in_bytes == layout.size());
unsafe {
let bottom = Global.alloc(layout).unwrap().as_ptr();
Heap {
bottom,
current: bottom,
top: bottom.add(layout.size()),
}
}
}
}
impl Drop for Heap {
fn drop(&mut self) {
debug_assert!(self.bytes_used() == 0);
if let Some(bottom) = ptr::NonNull::new(self.bottom) {
let layout = Self::layout_u8(self.bytes_total());
unsafe { Global.dealloc(bottom, layout); }
}
}
}
impl Default for Heap {
fn default() -> Heap {
Heap {
bottom: ptr::null_mut(),
top: ptr::null_mut(),
current: ptr::null_mut(),
}
}
}
const MIN_POW: usize = 16;
const MAX_POW: usize = 32;
const NUM_POOLS: usize = MAX_POW-MIN_POW;
fn size_for_i(i: usize) -> usize {
1 << (i + MIN_POW)
}
struct StackPool {
pools: [Heap; NUM_POOLS],
top: Option<usize>,
#[cfg(debug_assertions)]
history: Vec<*mut u8>,
}
impl StackPool {
pub fn get_slice<T>(&mut self, count: usize, i: usize) -> StackAlloc<T> {
let result = self.pools[i].slice::<T>(count, i);
#[cfg(debug_assertions)]
self.history.push(result.restore);
result
}
pub fn acquire<T>(&mut self, count: usize) -> StackAlloc<T> {
let pools = &mut self.pools;
let mut prev_used = 0;
let mut next_pool = 0;
if let Some(top) = self.top {
let pool = &pools[top];
if pool.usable_size::<T>() > count {
return self.get_slice(count, top);
}
prev_used = pool.bytes_used();
next_pool = top + 1;
}
let min_bytes = prev_used + size_of::<T>() * count + align_of::<T>();
for i in next_pool..NUM_POOLS {
let size = size_for_i(i);
if size_for_i(i) >= min_bytes {
pools[i] = Heap::new(size);
self.top = Some(i);
return self.get_slice(count, i);
}
}
panic!("Allocation size too large");
}
pub fn release<T>(&mut self, ptr: &StackAlloc<T>) {
#[cfg(debug_assertions)]
debug_assert!(self.history.pop().unwrap() == ptr.restore);
self.pools[ptr.pool_alloc].release(ptr.restore);
if self.top.unwrap() != ptr.pool_alloc {
self.pools[ptr.pool_alloc] = Default::default();
}
}
#[cfg(test)]
fn total_bytes_allocated(&self) -> usize {
if let Some(top) = self.top {
{ 0..=top }
.map(|i| { self.pools[i].bytes_total() })
.sum()
} else {
0
}
}
}
thread_local!(
static THREAD_LOCAL_POOL: RefCell<StackPool> = RefCell::new(
StackPool {
pools: Default::default(), top:None,
#[cfg(debug_assertions)]
history: Vec::new(),
}
));
#[derive(Debug)]
pub struct StackAlloc<T> {
restore: *mut u8,
ptr: *mut T,
len: usize,
pool_alloc: usize,
}
impl<T> Deref for StackAlloc<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe {
slice::from_raw_parts(self.ptr, self.len)
}
}
}
impl<T> DerefMut for StackAlloc<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe {
slice::from_raw_parts_mut(self.ptr, self.len)
}
}
}
impl<T> Drop for StackAlloc<T> {
fn drop(&mut self) {
unsafe { ptr::drop_in_place(&mut self[..]); }
THREAD_LOCAL_POOL.with(|rc| {
rc.borrow_mut().release(&self);
})
}
}
#[cfg(any(test, feature = "experimental"))]
pub unsafe fn acquire_uninitialized<T>(count: usize) -> StackAlloc<T> {
THREAD_LOCAL_POOL.with(|rc| {
rc.borrow_mut().acquire(count)
})
}
pub fn acquire<T, I: Iterator<Item=T>>(items: I) -> StackAlloc<T> {
THREAD_LOCAL_POOL.with(|rc| {
let len = items.size_hint().1.expect("Expected an iterator with an upper bound.");
let mut pool = rc.borrow_mut().acquire(len);
let mut p = pool.ptr;
pool.len = 0;
for item in items.take(len) {
unsafe {
ptr::write(p, item);
p = p.add(1);
}
pool.len += 1;
}
pool
})
}
#[cfg(test)]
mod tests {
use super::*;
use testdrop::TestDrop;
use std::iter::repeat;
#[test]
fn slices_do_no_alias() {
let pool0 = acquire(repeat(0).take(10));
let pool1 = acquire(repeat(1).take(10));
assert!(pool0.iter().all(|p| *p == 0));
assert!(pool1.iter().all(|p| *p == 1));
}
#[test]
fn uninitialized_is_correctly_sized() {
let pool = unsafe { acquire_uninitialized::<u32>(10) };
assert_eq!(pool.len(), 10);
}
#[test]
fn is_correctly_sized() {
let pool = acquire(0..10u8);
assert_eq!(pool.len(), 10);
}
#[test]
fn memory_is_reused() {
{
let _ = acquire(0..10usize);
}
{
let pool1 = unsafe { acquire_uninitialized::<usize>(10) };
for i in 0..pool1.len() {
assert_eq!(pool1[i], i);
}
}
}
#[test]
fn memory_is_not_released_eagerly() {
let current_size = || { THREAD_LOCAL_POOL.with(|rc| { rc.borrow().total_bytes_allocated() } ) };
assert!(current_size() == 0 || current_size() == size_for_i(0));
let small_size = size_for_i(0) / 2;
let large_size = size_for_i(0) - 1;
{
let _pool0 = unsafe { acquire_uninitialized::<u8>(small_size) };
assert_eq!(current_size(), size_for_i(0));
{
let _pool1 = unsafe { acquire_uninitialized::<u8>(large_size) };
assert_eq!(current_size(), size_for_i(0) + size_for_i(1));
}
assert_eq!(current_size(), size_for_i(0) + size_for_i(1));
}
assert_eq!(current_size(), size_for_i(1));
}
#[test]
fn drops() {
let td = TestDrop::new();
let (id, item) = td.new_item();
{
let some = Some(item);
let _ = acquire(some.iter());
td.assert_no_drop(id);
}
td.assert_drop(id);
}
#[test]
fn shrinks_on_large_size_hint() {
struct UndersizedIterator {
remaining: usize
}
impl Iterator for UndersizedIterator {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
None
} else {
self.remaining -= 1;
Some(self.remaining)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining + 20, Some(self.remaining + 20))
}
}
let bad = UndersizedIterator { remaining: 5 };
let values = acquire(bad);
assert!(values.len() == 5);
}
#[test]
fn empty_slice_ok() {
acquire(repeat(0).take(0));
acquire(repeat(0).take(0));
}
#[test]
fn zst_ok() {
let data = acquire(repeat(()).take(10));
debug_assert!(data.len() == 10);
debug_assert!(data[0] == ());
}
}