heapsize
heapsize copied to clipboard
Implement HeapSizeOf for PathBuf and friends
In a project I found myself needing to calculate the memory used by a PathBuf and ended up just ignoring the field. It'd be better if PathBuf implemented HeapSizeOf though.
I did a little spelunking through the std source code and it looks like PathBuf is just a newtype'd OsString, which is in turn just a newtype'd std::sys::Buf (os-specific string buffer). I stopped trying to write a PR soon after that because I'd started doing mem::transmutes between newtypes and digging into std::sys's os-specific internals, which felt a bit too hacky.
I think you could get pretty far with something like this:
use std::path::PathBuf;
use std::ffi::OsString;
use std::mem;
impl HeapSizeOf for PathBuf {
fn heap_size_of_children(&self) -> usize {
// PathBuf is just a newtype'd OsString
let os_str: &OsString = unsafe { mem::transmute(self) };
os_str.heap_size_of_children()
}
}
impl HeapSizeOf for OsString {
fn heap_size_of_children(&self) -> usize {
// the easy case, should work 99% of time.
if let Some(s) = self.to_str() {
return unsafe { heap_size_of(s.as_ptr()) };
}
// fall back to a sane default or alternate implementation
...
}
}
See also https://github.com/rust-lang/rust/issues/58234.