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

Implement HeapSizeOf for PathBuf and friends #99

@Michael-F-Bryan

Description

@Michael-F-Bryan

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
    ...
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions