Skip to content
This repository has been archived by the owner on Jul 10, 2023. It is now read-only.

Commit

Permalink
Make heap_size_of() unsafe, fix #9.
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonSapin committed Feb 8, 2016
1 parent 201f76d commit 1143c79
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "heapsize"
version = "0.2.5"
version = "0.3.0"
authors = [ "The Servo Project Developers" ]
description = "Infrastructure for measuring the total runtime size of an object on the heap"
license = "MPL-2.0"
Expand Down
28 changes: 20 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,16 @@ extern {
fn je_malloc_usable_size(ptr: *const c_void) -> size_t;
}

// A wrapper for je_malloc_usable_size that handles `EMPTY` and returns `usize`.
pub fn heap_size_of(ptr: *const c_void) -> usize {
/// A wrapper for je_malloc_usable_size that handles `EMPTY` and returns `usize`.
///
/// `unsafe` because the caller must ensure that the pointer is from jemalloc.
/// FIXME: This probably interacts badly with custom allocators:
/// https://doc.rust-lang.org/book/custom-allocators.html
pub unsafe fn heap_size_of(ptr: *const c_void) -> usize {
if ptr == 0x01 as *const c_void {
0
} else {
unsafe { je_malloc_usable_size(ptr) as usize }
je_malloc_usable_size(ptr) as usize
}
}

Expand Down Expand Up @@ -71,13 +75,17 @@ pub trait HeapSizeOf {
impl<T: HeapSizeOf> HeapSizeOf for Box<T> {
fn heap_size_of_children(&self) -> usize {
// Measure size of `self`.
heap_size_of(&**self as *const T as *const c_void) + (**self).heap_size_of_children()
unsafe {
heap_size_of(&**self as *const T as *const c_void) + (**self).heap_size_of_children()
}
}
}

impl HeapSizeOf for String {
fn heap_size_of_children(&self) -> usize {
heap_size_of(self.as_ptr() as *const c_void)
unsafe {
heap_size_of(self.as_ptr() as *const c_void)
}
}
}

Expand Down Expand Up @@ -146,16 +154,20 @@ impl<T: HeapSizeOf + Copy> HeapSizeOf for Cell<T> {

impl<T: HeapSizeOf> HeapSizeOf for Vec<T> {
fn heap_size_of_children(&self) -> usize {
heap_size_of(self.as_ptr() as *const c_void) +
self.iter().fold(0, |n, elem| n + elem.heap_size_of_children())
unsafe {
heap_size_of(self.as_ptr() as *const c_void)
+ self.iter().fold(0, |n, elem| n + elem.heap_size_of_children())
}
}
}

impl<T> HeapSizeOf for Vec<Rc<T>> {
fn heap_size_of_children(&self) -> usize {
// The fate of measuring Rc<T> is still undecided, but we still want to measure
// the space used for storing them.
heap_size_of(self.as_ptr() as *const c_void)
unsafe {
heap_size_of(self.as_ptr() as *const c_void)
}
}
}

Expand Down

0 comments on commit 1143c79

Please sign in to comment.