Skip to content

Commit 1e22ad0

Browse files
committed
refactor(allocator): replace AtomicUsize with Cell<usize> in AllocationStats
1 parent 32c7632 commit 1e22ad0

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

crates/oxc_allocator/src/tracking.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,51 +16,49 @@
1616
//! As soon as we replace `bumpalo` with our own arena allocator, we'll remove the hack from `get_stats_ref`,
1717
//! and make this sound.
1818
19-
use std::{
20-
ptr,
21-
sync::atomic::{AtomicUsize, Ordering::SeqCst},
22-
};
19+
use std::{cell::Cell, ptr};
2320

2421
use bumpalo::Bump;
2522

2623
use crate::{Allocator, allocator::STATS_FIELD_OFFSET};
2724

2825
/// Counters of allocations and reallocations made in an [`Allocator`].
29-
//
30-
// Note: These fields could be `Cell<usize>` instead of `AtomicUsize`, because `Allocator` should not
31-
// be `Sync`. But currently it is (which is unsound!) because of other terrible hacks.
3226
#[derive(Default)]
3327
pub struct AllocationStats {
3428
/// Number of allocations
35-
num_alloc: AtomicUsize,
29+
num_alloc: Cell<usize>,
3630
/// Number of reallocations
37-
num_realloc: AtomicUsize,
31+
num_realloc: Cell<usize>,
3832
}
3933

4034
impl AllocationStats {
4135
/// Record that an allocation was made.
4236
pub(crate) fn record_allocation(&self) {
43-
self.num_alloc.fetch_add(1, SeqCst);
37+
// Counter maxes out at `usize::MAX`, but if there's that many allocations,
38+
// the exact number is not important
39+
self.num_alloc.set(self.num_alloc.get().saturating_add(1));
4440
}
4541

4642
/// Record that a reallocation was made.
4743
pub(crate) fn record_reallocation(&self) {
48-
self.num_realloc.fetch_add(1, SeqCst);
44+
// Counter maxes out at `usize::MAX`, but if there's that many allocations,
45+
// the exact number is not important
46+
self.num_realloc.set(self.num_realloc.get().saturating_add(1));
4947
}
5048

5149
/// Reset allocation counters.
5250
pub(crate) fn reset(&self) {
53-
self.num_alloc.store(0, SeqCst);
54-
self.num_realloc.store(0, SeqCst);
51+
self.num_alloc.set(0);
52+
self.num_realloc.set(0);
5553
}
5654
}
5755

5856
impl Allocator {
5957
/// Get number of allocations and reallocations made in this [`Allocator`].
6058
#[doc(hidden)]
6159
pub fn get_allocation_stats(&self) -> (usize, usize) {
62-
let num_alloc = self.stats.num_alloc.load(SeqCst);
63-
let num_realloc = self.stats.num_realloc.load(SeqCst);
60+
let num_alloc = self.stats.num_alloc.get();
61+
let num_realloc = self.stats.num_realloc.get();
6462
(num_alloc, num_realloc)
6563
}
6664
}

0 commit comments

Comments
 (0)