Skip to content

Instantly share code, notes, and snippets.

@Mart-Bogdan
Created November 19, 2022 01:27
Show Gist options
  • Save Mart-Bogdan/93a8724ca7c3bafc164f6da418bcb300 to your computer and use it in GitHub Desktop.
Save Mart-Bogdan/93a8724ca7c3bafc164f6da418bcb300 to your computer and use it in GitHub Desktop.
Rust allocator to debug allocations
use std::alloc::{System, GlobalAlloc};
static SYS_ALLOC: System = System;
struct CountingAlloc {
bytes_allocated: AtomicIsize,
bytes_used: AtomicIsize
}
#[global_allocator]
static COUNTING_ALLOC: CountingAlloc = CountingAlloc{bytes_allocated:AtomicIsize::new(0),bytes_used:AtomicIsize::new(0)};
impl Display for CountingAlloc {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Allocated: {} Current Ram usage: {}", COUNTING_ALLOC.bytes_allocated.fetch_add(0, std::sync::atomic::Ordering::AcqRel), COUNTING_ALLOC.bytes_used.fetch_add(0, std::sync::atomic::Ordering::AcqRel))
}
}
unsafe impl GlobalAlloc for CountingAlloc {
unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 {
let ptr = SYS_ALLOC.alloc_zeroed(layout);
if ptr != std::ptr::null_mut() {
self.bytes_allocated.fetch_add(layout.size() as isize, std::sync::atomic::Ordering::Relaxed);
self.bytes_used.fetch_add(layout.size() as isize, std::sync::atomic::Ordering::Relaxed);
}
ptr
}
unsafe fn realloc(&self, ptr: *mut u8, layout: std::alloc::Layout, new_size: usize) -> *mut u8 {
let ptr = SYS_ALLOC.realloc(ptr, layout, new_size);
if ptr != std::ptr::null_mut() {
self.bytes_allocated.fetch_add( std::cmp::min(0, new_size as isize - (layout.size() as isize)), std::sync::atomic::Ordering::Relaxed);
self.bytes_used.fetch_add(new_size as isize - (layout.size() as isize), std::sync::atomic::Ordering::Relaxed);
}
ptr
}
unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 {
let ptr = SYS_ALLOC.alloc(layout);
if ptr != std::ptr::null_mut() {
self.bytes_allocated.fetch_add(layout.size() as isize, std::sync::atomic::Ordering::Relaxed);
self.bytes_used.fetch_add(layout.size() as isize, std::sync::atomic::Ordering::Relaxed);
}
ptr
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: std::alloc::Layout) {
self.bytes_used.fetch_sub(layout.size() as isize, std::sync::atomic::Ordering::Relaxed);
SYS_ALLOC.dealloc(ptr, layout)
}
}
// println!("{}", &COUNTING_ALLOC);
// return Ok(());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment