|
16 | 16 | //! As soon as we replace `bumpalo` with our own arena allocator, we'll remove the hack from `get_stats_ref`, |
17 | 17 | //! and make this sound. |
18 | 18 |
|
19 | | -use std::{ |
20 | | - ptr, |
21 | | - sync::atomic::{AtomicUsize, Ordering::SeqCst}, |
22 | | -}; |
| 19 | +use std::{cell::Cell, ptr}; |
23 | 20 |
|
24 | 21 | use bumpalo::Bump; |
25 | 22 |
|
26 | 23 | use crate::{Allocator, allocator::STATS_FIELD_OFFSET}; |
27 | 24 |
|
28 | 25 | /// 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. |
32 | 26 | #[derive(Default)] |
33 | 27 | pub struct AllocationStats { |
34 | 28 | /// Number of allocations |
35 | | - num_alloc: AtomicUsize, |
| 29 | + num_alloc: Cell<usize>, |
36 | 30 | /// Number of reallocations |
37 | | - num_realloc: AtomicUsize, |
| 31 | + num_realloc: Cell<usize>, |
38 | 32 | } |
39 | 33 |
|
40 | 34 | impl AllocationStats { |
41 | 35 | /// Record that an allocation was made. |
42 | 36 | 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)); |
44 | 40 | } |
45 | 41 |
|
46 | 42 | /// Record that a reallocation was made. |
47 | 43 | 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)); |
49 | 47 | } |
50 | 48 |
|
51 | 49 | /// Reset allocation counters. |
52 | 50 | 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); |
55 | 53 | } |
56 | 54 | } |
57 | 55 |
|
58 | 56 | impl Allocator { |
59 | 57 | /// Get number of allocations and reallocations made in this [`Allocator`]. |
60 | 58 | #[doc(hidden)] |
61 | 59 | 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(); |
64 | 62 | (num_alloc, num_realloc) |
65 | 63 | } |
66 | 64 | } |
|
0 commit comments