Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(allocator): Remove wrong assertions and add tests #9252

Merged
merged 7 commits into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions crates/swc_allocator/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ pub struct Allocator {

impl Allocator {
/// Invokes `f` in a scope where the allocations are done in this allocator.
///
/// # Safety
///
/// [Allocator] must be dropped after dropping all [crate::boxed::Box] and
/// [crate::vec::Vec] created in the scope.
#[inline(always)]
pub fn scope<'a, F, R>(&'a self, f: F) -> R
where
Expand Down Expand Up @@ -116,11 +121,6 @@ unsafe impl allocator_api2::alloc::Allocator for FastAlloc {
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
#[cfg(feature = "scoped")]
if self.alloc.is_some() {
debug_assert!(
ALLOC.get().is_some(),
"Deallocating a pointer allocated with arena mode with a non-arena mode allocator"
);

self.with_allocator(|alloc, _| alloc.deallocate(ptr, layout));
return;
}
Expand Down
12 changes: 12 additions & 0 deletions crates/swc_allocator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,15 @@ pub struct FastAlloc {
#[cfg(feature = "scoped")]
alloc: Option<&'static Allocator>,
}

impl FastAlloc {
/// [crate::boxed::Box] or [crate::vec::Vec] created with this instance is
/// managed by the global allocator and it can outlive the
/// [crate::Allocator] instance used for [Allocator::scope].
pub const fn global() -> Self {
Self {
#[cfg(feature = "scoped")]
alloc: None,
}
}
}
24 changes: 24 additions & 0 deletions crates/swc_allocator/tests/escape.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use swc_allocator::{boxed::Box, Allocator, FastAlloc};

#[test]
fn escape() {
let allocator = Allocator::default();

let obj = allocator.scope(|| Box::new(1234));

assert_eq!(*obj, 1234);
// It should not segfault, because the allocator is still alive.
drop(obj);
}

#[test]
fn global_allocator() {
let allocator = Allocator::default();

let obj = allocator.scope(|| Box::new_in(1234, FastAlloc::global()));

assert_eq!(*obj, 1234);
drop(allocator);
// Object created with global allocator should outlive the allocator.
drop(obj);
}
Loading