abstraction for correct filepath buffer reuse
  • Rust 99.3%
  • Just 0.7%
Find a file
2025-11-01 14:44:27 -05:00
benches add DirBuf::join_lit 2024-11-21 16:27:40 -06:00
src fix hardcoded string in shared docs 2025-11-01 14:42:46 -05:00
tests fix needless mut 2025-01-22 14:44:35 -06:00
.gitignore init 2024-11-15 13:24:17 -06:00
Cargo.lock chore: Release dirbuf version 0.1.2 2025-11-01 14:44:27 -05:00
Cargo.toml chore: Release dirbuf version 0.1.2 2025-11-01 14:44:27 -05:00
justfile add justfile, setup clippy, address lints 2025-11-01 13:45:19 -05:00
README.md fix typos 2025-11-01 13:35:22 -05:00

Reusable directory buffers

This library implements a simple [DirBuf] type in order to easily perform a simple optimization: re-using a heap buffer when opening multiple files in a single dir.

Consider this example:

// allocation 1
let data_dir = get_my_app_data_dir();
// allocation 2
let config_a = data_dir.join("a.conf");
// allocation 3
let config_b = data_dir.join("b.conf");
// allocation 3
let config_c = data_dir.join("c.conf");
let config_d = data_dir.join("d.conf");

Using DirBuf allows you to implement this pattern while only using a single allocation.

The API is designed so it can be a drop-in replacement for Path/PathBuf in common cases.

It also works when using a subdir within the main directory:

use dirbuf::DirBuf;

let mut conf_dir = DirBuf::new("/some/config/dir");

let main_config = conf_dir.join("config.toml");
// handle main config here
let mut themes = conf_dir.join("themes");
let light_theme = themes.join("light.toml");
// load light theme here
let dark_theme = themes.join("dark.toml");
// load dark theme here

Limitations

Trivial Paths

All join* methods require "trivial paths", meaning the path does not contain any kind of components other than CurDir and/or Normal.

This means no .., no absolute paths, and, on windows, no path prefixes, such as drive letters, verbatim paths, or UNC prefixes.

If you need to append a non-trivial path to a DirBuf, you can do so by first converting it to a Path:

use dirbuf::DirBuf;

let mut dir = DirBuf::new("some/dir");
let a = dir.join("a");
let b = dir.as_path().join("../b");
let c = dir.join("c");

Feature flags

nightly-safe-impl

This library relies on the ability to truncate a Path/OsString, which currently requires unsafe code. However, the unstable library feature os_string_truncate allows this to be done safely.

Enabling this feature will cause dirbuf to use OsString::truncate instead of unsafe code to truncate the path.