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
use std::{
alloc::AllocError,
cell::{Cell, UnsafeCell},
fmt::Debug,
ops::{Deref, DerefMut},
ptr::NonNull,
};
use crate::*;
thread_local! {
pub static BUMP_ALLOC: BumpAlloc = BumpAlloc::default();
}
pub struct BumpAllocRef(());
impl Drop for BumpAllocRef {
#[inline]
fn drop(&mut self) {
BUMP_ALLOC.with(|alloc| alloc.drop_ref(self));
}
}
impl !Send for BumpAllocRef {}
impl !Sync for BumpAllocRef {}
unsafe impl std::alloc::Allocator for BumpAllocRef {
fn allocate(&self, layout: std::alloc::Layout) -> Result<NonNull<[u8]>, AllocError> {
Ok(BUMP_ALLOC.with(|alloc| alloc.allocator().alloc(layout, true)))
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: std::alloc::Layout) {
BUMP_ALLOC.with(|alloc| alloc.allocator().try_free(ptr, layout));
}
unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: std::alloc::Layout,
new_layout: std::alloc::Layout,
) -> Result<NonNull<[u8]>, AllocError> {
debug_assert!(
new_layout.size() >= old_layout.size(),
"`new_layout.size()` must be greater than or equal to `old_layout.size()`"
);
Ok(BUMP_ALLOC.with(|alloc| alloc.allocator().grow(ptr.cast(), old_layout, new_layout)))
}
}
#[derive(Default)]
pub struct BumpAlloc {
refs: Cell<usize>,
allocator: UnsafeCell<Allocator>,
}
impl BumpAlloc {
fn allocator(&self) -> &mut Allocator {
unsafe { &mut *self.allocator.get() }
}
#[inline]
fn create_ref(&self) -> BumpAllocRef {
self.refs.set(self.refs.get() + 1);
BumpAllocRef(())
}
#[inline]
fn drop_ref(&self, _: &mut BumpAllocRef) {
if self.refs.replace(self.refs.get() - 1) == 1 {
#[cold]
#[inline(never)]
fn clear(s: &BumpAlloc) {
unsafe { s.allocator().clear() };
}
clear(self)
}
}
}
pub struct BumpVec<T> {
inner: Vec<T, BumpAllocRef>,
}
impl<T: Debug> Debug for BumpVec<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(self.inner.iter()).finish()
}
}
impl<T> From<BumpVec<T>> for Vec<T, BumpAllocRef> {
fn from(bump_vec: BumpVec<T>) -> Self {
bump_vec.inner
}
}
impl<T> BumpVec<T> {
pub fn new() -> Self {
Self {
inner: Vec::new_in(BUMP_ALLOC.with(|b| b.create_ref())),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
inner: Vec::with_capacity_in(capacity, BUMP_ALLOC.with(|b| b.create_ref())),
}
}
}
impl<T> Default for BumpVec<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> IntoIterator for BumpVec<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T, BumpAllocRef>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.inner.into_iter()
}
}
impl<T> FromIterator<T> for BumpVec<T> {
#[inline]
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let iter = iter.into_iter();
let (size_hint, _) = iter.size_hint();
let mut s = Self::with_capacity(size_hint);
s.extend(iter);
s
}
}
impl<T> Deref for BumpVec<T> {
type Target = Vec<T, BumpAllocRef>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> DerefMut for BumpVec<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
pub trait ToBumpVec<T> {
fn to_bumpvec(&self) -> BumpVec<T>;
}
impl<T: Clone> ToBumpVec<T> for [T] {
#[inline]
fn to_bumpvec(&self) -> BumpVec<T> {
let mut vec = BumpVec::new();
vec.extend_from_slice(self);
vec
}
}
#[macro_export]
macro_rules! bumpvec {
() => {
$crate::BumpVec::new()
};
($($x:expr),+) => {
{
let mut vec = $crate::BumpVec::new();
vec.extend([$($x),*]);
vec
}
};
($expr:expr; $len:expr) => {
{
let mut v = $crate::BumpVec::new();
v.resize($len, $expr);
v
}
};
(cap $cap:expr) => {
$crate::BumpVec::with_capacity($cap)
};
}
#[cfg(test)]
mod test {
use super::*;
#[test]
#[cfg_attr(miri, ignore)]
fn burst_alloc_comparison() {
bench(&[
("normal-vec", |timer| {
timer.start();
let mut ptr = 0;
for _ in 0..1_000_000 {
let vec = Vec::<usize>::with_capacity(100);
ptr += vec.as_ptr() as usize;
}
timer.stop();
println!("{ptr:?}");
}),
("bump-vec", |timer| {
let vec: BumpVec<usize> = bumpvec!(cap 100);
timer.start();
let mut ptr = 0;
for _ in 0..1_000_000 {
let vec = BumpVec::<usize>::with_capacity(100);
ptr += vec.as_ptr() as usize;
}
timer.stop();
drop(vec);
println!("{ptr:?}");
}),
("no-alloc", |timer| {
let vec = vec![0; 100].as_ptr();
timer.start();
let mut ptr = 0;
for _ in 0..1_000_000 {
ptr += vec as usize;
ptr /= 3;
ptr *= 2;
}
timer.stop();
println!("{ptr:?}");
}),
])
}
#[derive(Default)]
struct Timer {
from: Option<std::time::Instant>,
to: Option<std::time::Instant>,
}
impl Timer {
fn start(&mut self) {
self.from = Some(std::time::Instant::now());
}
fn stop(&mut self) {
self.to = Some(std::time::Instant::now());
}
fn summary(self, name: &str) {
let start = self.from.unwrap();
let end = self.to.unwrap_or_else(std::time::Instant::now);
println!("{name} {:?}", end.duration_since(start));
}
}
type BenchTasks<'a> = &'a [(&'a str, fn(&mut Timer))];
fn bench(task: BenchTasks) {
std::thread::scope(|s| {
for (name, f) in task {
s.spawn(|| {
let mut timer = Timer::default();
timer.start();
f(&mut timer);
timer.summary(name);
});
}
});
}
}