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

Implement HeapSizeOf for PathBuf and friends #99

Open
Michael-F-Bryan opened this issue Aug 19, 2018 · 1 comment
Open

Implement HeapSizeOf for PathBuf and friends #99

Michael-F-Bryan opened this issue Aug 19, 2018 · 1 comment

Comments

@Michael-F-Bryan
Copy link

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
    ...
  }
}
@Mark-Simulacrum
Copy link

See also rust-lang/rust#58234.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants