Skip to content

Commit

Permalink
exposing sn_malloc_usable_size as a mean to assess how much the
Browse files Browse the repository at this point in the history
underlying allocator actually rounded up the allocated size.

Signed-off-by: David Carlier <[email protected]>
  • Loading branch information
devnexen committed Feb 11, 2024
1 parent e0e4bfa commit eca7ee8
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ unsafe impl GlobalAlloc for SnMalloc {
}
}

impl SnMalloc {
/// Returns the available bytes in a memory block.
///
/// Note that the value could be higher than the allocation size and
/// depends very much on the underlying operating system.
#[inline(always)]
pub fn usable_size(&self, ptr: *const u8) -> usize {
unsafe { ffi::sn_malloc_usable_size(ptr as *const _) }
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -123,4 +134,17 @@ mod tests {
alloc.dealloc(ptr, layout);
}
}

#[test]
fn it_usable_size() {
unsafe {
let layout = Layout::from_size_align(8, 8).unwrap();
let alloc = SnMalloc;

let ptr = alloc.alloc(layout);
let usz = alloc.usable_size(ptr);
alloc.dealloc(ptr, layout);
assert!(usz >= 8);
}
}
}

0 comments on commit eca7ee8

Please sign in to comment.