From 6801c81b86d07c81edbe3d27e8abb0f53548020e Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Mon, 20 Jan 2025 15:21:16 +0000 Subject: [PATCH] feat(allocator): add `Allocator::new` and `with_capacity` methods (#8620) Add `Allocator::with_capacity` method to allow specifying initial capacity when creating `Allocator`. Also add `Allocator::new` as an alternative to `Allocator::default` (does the same thing). --- crates/oxc_allocator/src/lib.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/oxc_allocator/src/lib.rs b/crates/oxc_allocator/src/lib.rs index 265827cc3a07a..8613e8fe6d291 100644 --- a/crates/oxc_allocator/src/lib.rs +++ b/crates/oxc_allocator/src/lib.rs @@ -89,6 +89,35 @@ pub struct Allocator { } impl Allocator { + /// Create a new [`Allocator`] with no initial capacity. + /// + /// This method does not reserve any memory to back the allocator. Memory for allocator's initial + /// chunk will be reserved lazily, when you make the first allocation into this [`Allocator`] + /// (e.g. with [`Allocator::alloc`], [`Box::new_in`], [`Vec::new_in`], [`HashMap::new_in`]). + /// + /// If you can estimate the amount of memory the allocator will require to fit what you intend to + /// allocate into it, it is generally preferable to create that allocator with [`with_capacity`] + /// which reserves that amount of memory upfront. This will avoid further system calls to allocate + /// further chunks later on. + /// + /// [`with_capacity`]: Allocator::with_capacity + // + // `#[inline(always)]` because just delegates to `bumpalo` method + #[expect(clippy::inline_always)] + #[inline(always)] + pub fn new() -> Self { + Self { bump: Bump::new() } + } + + /// Create a new [`Allocator`] with specified capacity. + // + // `#[inline(always)]` because just delegates to `bumpalo` method + #[expect(clippy::inline_always)] + #[inline(always)] + pub fn with_capacity(capacity: usize) -> Self { + Self { bump: Bump::with_capacity(capacity) } + } + /// Allocate an object in this [`Allocator`] and return an exclusive reference to it. /// /// # Panics