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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With