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
use std::{
alloc::Layout,
mem::{self, ManuallyDrop},
ops::{Deref, DerefMut},
sync::{Mutex, MutexGuard, PoisonError},
vec::Vec,
};
use crate::{
Bump, BumpScope, ErrorBehavior,
alloc::{AllocError, Allocator},
maybe_default_allocator,
settings::{BumpAllocatorSettings, BumpSettings},
};
#[cfg(feature = "panic-on-alloc")]
use crate::panic_on_error;
macro_rules! make_pool {
($($allocator_parameter:tt)*) => {
/// A pool of bump allocators.
///
/// This type allows bump allocations in parallel, with the allocations' lifetimes tied to the pool.
///
/// # Examples
///
/// Using `BumpPool` with parallel iterators from [`rayon`](https://docs.rs/rayon):
/// ```
/// # use bump_scope::BumpPool;
/// # use rayon::prelude::{ParallelIterator, IntoParallelIterator};
/// # if cfg!(miri) { return } // rayon violates strict-provenance :(
/// #
/// let mut pool: BumpPool = BumpPool::new();
///
/// let strings: Vec<&str> = (0..1000)
/// .into_par_iter()
/// .map_init(|| pool.get(), |bump, i| {
/// // do some expensive work
/// bump.alloc_fmt(format_args!("{i}")).into_ref()
/// })
/// .collect();
///
/// dbg!(&strings);
///
/// pool.reset();
///
/// // memory of the strings is freed, trying to access `strings` will result in a lifetime error
/// // dbg!(&strings);
/// ```
///
/// Using `BumpPool` with [`std::thread::scope`]:
/// ```
/// # use bump_scope::BumpPool;
/// let pool: BumpPool = BumpPool::new();
/// let (sender, receiver) = std::sync::mpsc::sync_channel(10);
///
/// std::thread::scope(|s| {
/// s.spawn(|| {
/// let bump = pool.get();
/// let string = bump.alloc_str("Hello");
/// sender.send(string).unwrap();
/// drop(sender);
/// });
///
/// s.spawn(|| {
/// for string in receiver {
/// assert_eq!(string, "Hello");
/// }
/// });
/// });
/// ```
///
#[doc(alias = "Herd")]
#[derive(Debug)]
pub struct BumpPool<$($allocator_parameter)*, S = BumpSettings>
where
A: Allocator,
S: BumpAllocatorSettings,
{
bumps: Mutex<Vec<Bump<A, S>>>,
allocator: A,
}
};
}
maybe_default_allocator!(make_pool);
impl<A, S> Default for BumpPool<A, S>
where
A: Allocator + Default,
S: BumpAllocatorSettings,
{
fn default() -> Self {
Self {
bumps: Mutex::default(),
allocator: Default::default(),
}
}
}
impl<A, S> BumpPool<A, S>
where
A: Allocator + Default,
S: BumpAllocatorSettings,
{
/// Constructs a new `BumpPool`.
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl<A, S> BumpPool<A, S>
where
A: Allocator,
S: BumpAllocatorSettings,
{
/// Constructs a new `BumpPool` with the provided allocator.
#[inline]
#[must_use]
pub const fn new_in(allocator: A) -> Self {
Self {
bumps: Mutex::new(Vec::new()),
allocator,
}
}
/// [`reset`](Bump::reset) all `Bump`s in this pool.
pub fn reset(&mut self) {
for bump in self.bumps() {
bump.reset();
}
}
/// [`reset_to_start`](Bump::reset_to_start) all `Bump`s in this pool.
pub fn reset_to_start(&mut self) {
for bump in self.bumps() {
bump.reset_to_start();
}
}
/// Returns the vector of `Bump`s.
pub fn bumps(&mut self) -> &mut Vec<Bump<A, S>> {
self.bumps.get_mut().unwrap_or_else(PoisonError::into_inner)
}
fn lock(&self) -> MutexGuard<'_, Vec<Bump<A, S>>> {
self.bumps.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl<A, S> BumpPool<A, S>
where
A: Allocator + Clone,
S: BumpAllocatorSettings,
{
/// Borrows a bump allocator from the pool.
/// With this `BumpPoolGuard` you can make allocations that live for as long as the pool lives.
///
/// If this needs to create a new `Bump`, it will be constructed by calling <code>Bump::[new]\()</code>.
///
/// [new]: Bump::new
///
/// # Panics
/// Panics if the allocation fails.
#[must_use]
#[inline(always)]
#[cfg(feature = "panic-on-alloc")]
pub fn get(&self) -> BumpPoolGuard<'_, A, S> {
let bump = match self.lock().pop() {
Some(bump) => bump,
None => Bump::new_in(self.allocator.clone()),
};
BumpPoolGuard {
pool: self,
bump: ManuallyDrop::new(bump),
}
}
/// Borrows a bump allocator from the pool.
/// With this `BumpPoolGuard` you can make allocations that live for as long as the pool lives.
///
/// If this needs to create a new `Bump`, it will be constructed by calling <code>Bump::[try_new]\()</code>.
///
/// [try_new]: Bump::try_new
///
/// # Errors
/// Errors if the allocation fails.
#[inline(always)]
pub fn try_get(&self) -> Result<BumpPoolGuard<'_, A, S>, AllocError> {
let bump = match self.lock().pop() {
Some(bump) => bump,
None => Bump::try_new_in(self.allocator.clone())?,
};
Ok(BumpPoolGuard {
pool: self,
bump: ManuallyDrop::new(bump),
})
}
/// Borrows a bump allocator from the pool.
/// With this `BumpPoolGuard` you can make allocations that live for as long as the pool lives.
///
/// If this needs to create a new `Bump`, it will be constructed by calling <code>Bump::[with_size]\(size)</code>.
///
/// [with_size]: Bump::with_size
///
/// # Panics
/// Panics if the allocation fails.
#[must_use]
#[inline(always)]
#[cfg(feature = "panic-on-alloc")]
pub fn get_with_size(&self, size: usize) -> BumpPoolGuard<'_, A, S> {
panic_on_error(self.generic_get_with_size(size))
}
/// Borrows a bump allocator from the pool.
/// With this `BumpPoolGuard` you can make allocations that live for as long as the pool lives.
///
/// If this needs to create a new `Bump`, it will be constructed by calling <code>Bump::[try_with_size]\(size)</code>.
///
/// [try_with_size]: Bump::try_with_size
///
/// # Errors
/// Errors if the allocation fails.
#[inline(always)]
pub fn try_get_with_size(&self, size: usize) -> Result<BumpPoolGuard<'_, A, S>, AllocError> {
self.generic_get_with_size(size)
}
pub(crate) fn generic_get_with_size<E: ErrorBehavior>(&self, size: usize) -> Result<BumpPoolGuard<'_, A, S>, E> {
let bump = match self.lock().pop() {
Some(bump) => bump,
None => Bump::generic_with_size_in(size, self.allocator.clone())?,
};
Ok(BumpPoolGuard {
pool: self,
bump: ManuallyDrop::new(bump),
})
}
/// Borrows a bump allocator from the pool.
/// With this `BumpPoolGuard` you can make allocations that live for as long as the pool lives.
///
/// If this needs to create a new `Bump`, it will be constructed by calling <code>Bump::[with_capacity]\(layout)</code>.
///
/// [with_capacity]: Bump::with_capacity
///
/// # Panics
/// Panics if the allocation fails.
#[must_use]
#[inline(always)]
#[cfg(feature = "panic-on-alloc")]
pub fn get_with_capacity(&self, layout: Layout) -> BumpPoolGuard<'_, A, S> {
panic_on_error(self.generic_get_with_capacity(layout))
}
/// Borrows a bump allocator from the pool.
/// With this `BumpPoolGuard` you can make allocations that live for as long as the pool lives.
///
/// If this needs to create a new `Bump`, it will be constructed by calling <code>Bump::[try_with_capacity]\(layout)</code>.
///
/// [try_with_capacity]: Bump::try_with_capacity
///
/// # Errors
/// Errors if the allocation fails.
#[inline(always)]
pub fn try_get_with_capacity(&self, layout: Layout) -> Result<BumpPoolGuard<'_, A, S>, AllocError> {
self.generic_get_with_capacity(layout)
}
pub(crate) fn generic_get_with_capacity<E: ErrorBehavior>(&self, layout: Layout) -> Result<BumpPoolGuard<'_, A, S>, E> {
let bump = match self.lock().pop() {
Some(bump) => bump,
None => Bump::generic_with_capacity_in(layout, self.allocator.clone())?,
};
Ok(BumpPoolGuard {
pool: self,
bump: ManuallyDrop::new(bump),
})
}
}
macro_rules! make_pool_guard {
($($allocator_parameter:tt)*) => {
/// This is a wrapper around [`Bump`] that mutably derefs to a [`BumpScope`] and returns its [`Bump`] back to the [`BumpPool`] on drop.
#[derive(Debug)]
pub struct BumpPoolGuard<'a, $($allocator_parameter)*, S = BumpSettings>
where
A: Allocator,
S: BumpAllocatorSettings,
{
bump: ManuallyDrop<Bump<A, S>>,
pool: &'a BumpPool<A, S>,
}
};
}
maybe_default_allocator!(make_pool_guard);
impl<'a, A, S> BumpPoolGuard<'a, A, S>
where
A: Allocator,
S: BumpAllocatorSettings,
{
/// The [`BumpPool`], this [`BumpPoolGuard`] was created from.
pub fn pool(&self) -> &'a BumpPool<A, S> {
self.pool
}
}
impl<'a, A, S> Deref for BumpPoolGuard<'a, A, S>
where
A: Allocator,
S: BumpAllocatorSettings,
{
type Target = BumpScope<'a, A, S>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
// SAFETY: We return allocations for the lifetime of the pool reference
// instead of `bump`s own lifetime. This is fine because `BumpPool` and
// `BumpPoolGuard` don't expose any api to invalidate an allocation for
// lifetime `'a`.
//
// - `BumpPool::reset` requires a mutable reference, and since allocations
// immutably borrow the pool, the compiler doesn't allow you to `reset`
// before all allocations are gone.
//
// - `mem::forget(bump_pool_guard)` will not return the `Bump` to its pool,
// however the `Bump` won't be dropped either, so its allocations will
// live for `'static` which is compatible with `'a`.
unsafe { transmute_lifetime(self.bump.as_scope()) }
}
}
impl<A, S> DerefMut for BumpPoolGuard<'_, A, S>
where
A: Allocator,
S: BumpAllocatorSettings,
{
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { transmute_lifetime_mut(self.bump.as_mut_scope()) }
}
}
impl<A, S> Drop for BumpPoolGuard<'_, A, S>
where
A: Allocator,
S: BumpAllocatorSettings,
{
fn drop(&mut self) {
let bump = unsafe { ManuallyDrop::take(&mut self.bump) };
self.pool.lock().push(bump);
}
}
// This exists as a "safer" transmute that only transmutes the `'a` lifetime parameter.
#[expect(clippy::elidable_lifetime_names)]
unsafe fn transmute_lifetime<'from, 'to, 'b, A, S>(scope: &'b BumpScope<'from, A, S>) -> &'b BumpScope<'to, A, S>
where
S: BumpAllocatorSettings,
{
unsafe { mem::transmute(scope) }
}
// This exists as a "safer" transmute that only transmutes the `'a` lifetime parameter.
#[expect(clippy::elidable_lifetime_names)]
unsafe fn transmute_lifetime_mut<'from, 'to, 'b, A, S>(scope: &'b mut BumpScope<'from, A, S>) -> &'b mut BumpScope<'to, A, S>
where
S: BumpAllocatorSettings,
{
unsafe { mem::transmute(scope) }
}