Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a cross-platform way to clear and reuse a Rust PathBuf?

Tags:

rust

In an effort to keep overhead as low as possible when processing a large number of filesystem paths, I want to avoid allocating memory for each path. Is there a way to clear and reuse a PathBuf?

From what I could find in the docs, reusing a PathBuf is possible when dealing with absolute paths via a PathBuf::push (at least on POSIX systems), but I haven't found a way to reuse a PathBuf when dealing with a relative path.

Is there a way to do this in a cross-platform manner or am I forced to process these paths in a platform specific way?

like image 469
Tenders McChiken Avatar asked Sep 24 '18 08:09

Tenders McChiken


1 Answers

One way is to convert the PathBuf to its internal storage, clear that, and convert it back to the PathBuf. This requires no extra allocation:

use std::path::PathBuf;

fn main() {
    let path = PathBuf::from("../tmp");
    let mut path = path.into_os_string();
    path.clear();
    let mut path = PathBuf::from(path);
    path.push("../etc");
    assert_eq!(path, PathBuf::from("../etc"));
}

(Permalink to the playground)

like image 140
mcarton Avatar answered Nov 02 '22 18:11

mcarton