Skip to content

Commit

Permalink
Wrap eprintln in run_guarded function
Browse files Browse the repository at this point in the history
  • Loading branch information
Christian Koopmann authored and Christian Koopmann committed Jan 30, 2023
1 parent 19c4349 commit a0731bc
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion ch6/ch6-particles/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,32 @@ use rand::prelude::*; // <3>
use std::alloc::{GlobalAlloc, System, Layout}; // <4>

use std::time::Instant; // <5>
//
use std::cell::Cell;


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

struct ReportingAllocator; // <7>
//
//
/// Execute a closure without logging on allocations.
pub fn run_guarded<F>(f: F)
where
F: FnOnce(),
{
thread_local! {
static GUARD: Cell<bool> = Cell::new(false);
}

GUARD.with(|guard| {
if !guard.replace(true) {
f();
guard.set(false)
}
})
}

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

eprintln!("{}\t{}", bytes_requested, time_taken.as_nanos());
run_guarded(|| {eprintln!("{}\t{}", bytes_requested, time_taken.as_nanos())});
ptr
}

Expand Down

0 comments on commit a0731bc

Please sign in to comment.