bump-local 0.1.0

A thread-safe bump allocator backed by bumpalo crate.
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
#![cfg_attr(feature = "allocator_api", feature(allocator_api))]

//! A `Sync + Send` allocator wrapper around [bumpalo](https://docs.rs/bumpalo) using per-thread bump allocators.
//!
//! # Examples
//!
//! With bumpalo's collections:
//!
//! ```
//! use bump_local::Bump;
//!
//! let bump = Bump::new();
//! // Get the current thread's instance
//! let local = bump.local();
//! let mut vec = bumpalo::collections::Vec::new_in(local.as_inner());
//! vec.push(1);
//! vec.push(2);
//! ```
//!
//! With stable Rust and `allocator-api2` feature:
//!
//! ```rust,ignore
//! use allocator_api2::vec::Vec;
//! use bump_local::Bump;
//!
//! let bump = Bump::new();
//! let mut vec = Vec::new_in(bump.clone());
//! vec.push(1);
//! vec.push(2);
//! ```
//!
//! With nightly Rust and `allocator_api` feature:
//!
//! ```rust,ignore
//! #![feature(allocator_api)]
//!
//! use bump_local::Bump;
//!
//! let bump = Bump::new();
//! let mut vec = Vec::new_in(bump.clone());
//! vec.push(1);
//! vec.push(2);
//! ```

extern crate alloc;

use std::{
    cell::UnsafeCell,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

use thread_local::ThreadLocal;

mod error;
pub use error::ResetError;

#[cfg(any(feature = "allocator_api", feature = "allocator-api2"))]
mod alloc_api;

#[cfg(any(feature = "allocator_api", feature = "allocator-api2"))]
pub use alloc_api::Allocator;

struct ThreadGuard {
    alive: Arc<AtomicBool>,
}

impl ThreadGuard {
    fn new() -> Self {
        Self {
            alive: Arc::new(AtomicBool::new(true)),
        }
    }
}

impl Drop for ThreadGuard {
    fn drop(&mut self) {
        self.alive.store(false, Ordering::Release);
    }
}

thread_local! {
    static THREAD_GUARD: ThreadGuard = ThreadGuard::new();
}

/// A thread-safe bump allocator that provides `Sync + Send` semantics.
///
/// Each thread gets its own [`BumpLocal`] instance.
#[derive(Default, Clone)]
pub struct Bump {
    inner: Arc<BumpInner>,
}

impl Bump {
    /// Creates a new [`Bump`] allocator.
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns a [`BumpBuilder`] for configuring a [`Bump`] allocator.
    ///
    /// # Examples
    ///
    /// ```
    /// use bump_local::Bump;
    ///
    /// let bump = Bump::builder()
    ///     .threads_capacity(8)
    ///     .bump_capacity(4096)
    ///     .build();
    /// ```
    pub fn builder() -> BumpBuilder {
        BumpBuilder::new()
    }

    /// Returns the [`BumpLocal`] for the current thread,
    /// or creates it if it doesn't exist.
    ///
    /// If [`reset_all`] was called earlier,
    /// this would reset the current thread's allocator which is O(1).
    ///
    /// [`reset_all`]: Self::reset_all
    #[inline]
    pub fn local(&self) -> &BumpLocal {
        self.inner.local()
    }

    /// Resets all threads' bump allocators, deallocating all previously allocated memory.
    ///
    /// # Safety Contract
    ///
    /// - At the moment of reset it must be the only handle to the [`Bump`].
    /// - Like [`bumpalo::Bump::reset()`], callers must ensure no references to allocated memory
    ///   are used after calling this method.
    /// - This does not run any `Drop` implementations.
    #[inline]
    pub fn reset_all(&mut self) -> Result<(), ResetError> {
        match Arc::get_mut(&mut self.inner) {
            Some(inner) => {
                inner.reset_all();
                Ok(())
            }
            None => Err(ResetError),
        }
    }
}

/// Builder for configuring a [`Bump`] allocator.
#[derive(Default)]
pub struct BumpBuilder {
    threads_capacity: Option<usize>,
    bump_alloc_limit: Option<usize>,
    bump_capacity: usize,
}

impl BumpBuilder {
    /// Creates a new [`BumpBuilder`] with default configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the initial capacity hint for the number of threads that will access this allocator.
    ///
    /// This can reduce allocations in the underlying `ThreadLocal` storage when you know
    /// how many threads will use the allocator.
    pub fn threads_capacity(mut self, capacity: usize) -> Self {
        self.threads_capacity = Some(capacity);
        self
    }

    /// Sets the allocation limit for each per-thread bump allocator.
    ///
    /// Once the limit is reached, further allocations will fail.
    pub fn bump_allocation_limit(mut self, limit: usize) -> Self {
        self.bump_alloc_limit = Some(limit);
        self
    }

    /// Sets the initial capacity for each per-thread bump allocator.
    ///
    /// This pre-allocates memory for each thread's allocator, which can improve performance
    /// if you know approximately how much memory each thread will need.
    pub fn bump_capacity(mut self, capacity: usize) -> Self {
        self.bump_capacity = capacity;
        self
    }

    /// Builds the [`Bump`] allocator with the configured parameters.
    pub fn build(self) -> Bump {
        Bump {
            inner: Arc::new(BumpInner {
                locals: match self.threads_capacity {
                    Some(cap) => ThreadLocal::with_capacity(cap),
                    None => ThreadLocal::new(),
                },
                capacity: self.bump_capacity,
                alloc_limit: self.bump_alloc_limit,
            }),
        }
    }
}

/// Per-thread wrapper around a `bumpalo::Bump` allocator.
pub struct BumpLocal {
    inner: UnsafeCell<Option<BumpLocalInner>>,
}

impl BumpLocal {
    fn new(capacity: usize, limit: Option<usize>, thread_alive: Arc<AtomicBool>) -> Self {
        let bump = bumpalo::Bump::with_capacity(capacity);
        bump.set_allocation_limit(limit);

        Self {
            inner: UnsafeCell::new(Some(BumpLocalInner {
                inner: bump,
                thread_alive,
            })),
        }
    }

    /// Returns a reference to the underlying `bumpalo::Bump` allocator.
    ///
    /// The returned reference provides access to all `bumpalo::Bump` allocation methods.
    #[inline]
    pub fn as_inner(&self) -> &bumpalo::Bump {
        // SAFETY:
        // - BumpLocal is only constructed inside ThreadLocal,
        //   which ensures it's only accessed by one thread.
        // - The returned reference is !Send since bumpalo::Bump is !Sync.
        // - The reference lifetime is bound to the parent Bump allocator.
        unsafe { &(*self.inner.get()).as_ref().unwrap().inner }
    }

    /// Resets the allocator, deallocating all previously allocated memory.
    ///
    /// # Note
    ///
    /// - This does not run any `Drop` implementations.
    /// - Like [`bumpalo::Bump::reset()`], callers must ensure no references to allocated memory
    ///   are used after calling this method.
    #[inline]
    pub fn reset(&self) {
        // SAFETY: ThreadLocal ensures single-thread access to this BumpLocal.
        unsafe {
            (*self.inner.get()).as_mut().unwrap().inner.reset();
        }
    }

    #[inline]
    fn needs_init(&self) -> bool {
        // SAFETY: ThreadLocal ensures single-thread access to this BumpLocal.
        unsafe { (*self.inner.get()).is_none() }
    }

    #[cold]
    fn init(&self, capacity: usize, limit: Option<usize>, thread_alive: Arc<AtomicBool>) {
        let bump = bumpalo::Bump::with_capacity(capacity);
        bump.set_allocation_limit(limit);

        // SAFETY: ThreadLocal ensures single-thread access to this BumpLocal.
        unsafe {
            *self.inner.get() = Some(BumpLocalInner {
                inner: bump,
                thread_alive,
            })
        }
    }

    #[cold]
    fn clear(&mut self) {
        #[cold]
        fn drop_inner(bump: &mut BumpLocal) {
            // SAFETY: ThreadLocal ensures single-thread access to this BumpLocal.
            unsafe {
                let _ = (*bump.inner.get()).take();
            }
        }

        // SAFETY: ThreadLocal ensures single-thread access to this BumpLocal.
        let inner = unsafe { &*self.inner.get() };
        let Some(inner) = inner.as_ref() else {
            return;
        };

        if inner.thread_alive.load(Ordering::Acquire) {
            self.reset();
        } else {
            drop_inner(self);
        }
    }
}

struct BumpLocalInner {
    inner: bumpalo::Bump,
    thread_alive: Arc<AtomicBool>,
}

// Shared `Bump` state.
#[derive(Default)]
struct BumpInner {
    locals: ThreadLocal<BumpLocal>,
    capacity: usize,
    alloc_limit: Option<usize>,
}

impl BumpInner {
    #[inline]
    fn local(&self) -> &BumpLocal {
        let bump = self.locals.get_or(|| {
            let thread_alive = THREAD_GUARD.with(|guard| guard.alive.clone());
            BumpLocal::new(self.capacity, self.alloc_limit, thread_alive)
        });

        if bump.needs_init() {
            self.reinit_local(bump);
        }

        bump
    }

    #[cold]
    fn reinit_local(&self, bump: &BumpLocal) {
        let thread_alive = THREAD_GUARD.with(|guard| guard.alive.clone());
        bump.init(self.capacity, self.alloc_limit, thread_alive);
    }

    #[inline]
    fn reset_all(&mut self) {
        for local in self.locals.iter_mut() {
            local.clear();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::thread;

    use super::*;

    #[test]
    fn thread_guard_sets_alive_false_on_drop() {
        let handle = thread::spawn(move || THREAD_GUARD.with(|g| g.alive.clone()));

        let alive = handle.join().unwrap();
        assert!(!alive.load(Ordering::Acquire));
    }

    #[test]
    fn reset_resets_alive_thread() {
        let mut bump = Bump::builder().bump_capacity(100).build();

        let (tx, rx) = std::sync::mpsc::channel();
        let handle = {
            let bump = bump.clone();
            thread::spawn(move || {
                let _ = bump.local().as_inner().alloc(1_u8);
                let capacity_before = bump.local().as_inner().chunk_capacity();
                drop(bump);

                tx.send(capacity_before).unwrap();
                thread::park();
            })
        };

        let capacity_before = rx.recv().unwrap();

        // reset while thread is still alive
        bump.reset_all().unwrap();

        // check if bump was reset, not dropped
        let inner = Arc::get_mut(&mut bump.inner).unwrap();
        let locals: Vec<_> = inner.locals.iter_mut().collect();
        assert_eq!(locals.len(), 1);
        let local = locals.first().unwrap();
        assert!(!local.needs_init());
        assert!(local.as_inner().chunk_capacity() > capacity_before);

        handle.thread().unpark();
        handle.join().unwrap();
    }

    #[test]
    fn reset_drops_dead_thread_bump() {
        let mut bump = Bump::builder().bump_capacity(100).build();

        let handle = {
            let bump = bump.clone();
            thread::spawn(move || {
                let _ = bump.local().as_inner().alloc(1_u8);
            })
        };

        handle.join().unwrap();

        // reset_all should detect dead thread and drop its bump
        bump.reset_all().unwrap();

        let inner = Arc::get_mut(&mut bump.inner).unwrap();
        let locals: Vec<_> = inner.locals.iter_mut().collect();
        assert_eq!(locals.len(), 1);
        let local = locals.first().unwrap();
        assert!(local.needs_init());
    }
}