Skip to content

Commit a0731bc

Browse files
Christian KoopmannChristian Koopmann
authored andcommitted
Wrap eprintln in run_guarded function
1 parent 19c4349 commit a0731bc

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

ch6/ch6-particles/src/main.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,32 @@ use rand::prelude::*; // <3>
77
use std::alloc::{GlobalAlloc, System, Layout}; // <4>
88

99
use std::time::Instant; // <5>
10+
//
11+
use std::cell::Cell;
1012

1113

1214
#[global_allocator] // <6>
1315
static ALLOCATOR: ReportingAllocator = ReportingAllocator;
1416

1517
struct ReportingAllocator; // <7>
18+
//
19+
//
20+
/// Execute a closure without logging on allocations.
21+
pub fn run_guarded<F>(f: F)
22+
where
23+
F: FnOnce(),
24+
{
25+
thread_local! {
26+
static GUARD: Cell<bool> = Cell::new(false);
27+
}
28+
29+
GUARD.with(|guard| {
30+
if !guard.replace(true) {
31+
f();
32+
guard.set(false)
33+
}
34+
})
35+
}
1636

1737
unsafe impl GlobalAlloc for ReportingAllocator {
1838
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
@@ -22,7 +42,7 @@ unsafe impl GlobalAlloc for ReportingAllocator {
2242
let time_taken = end - start;
2343
let bytes_requested = layout.size();
2444

25-
eprintln!("{}\t{}", bytes_requested, time_taken.as_nanos());
45+
run_guarded(|| {eprintln!("{}\t{}", bytes_requested, time_taken.as_nanos())});
2646
ptr
2747
}
2848

0 commit comments

Comments
 (0)