Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Getting An Absolute PathBuf Path In Rust With Leading Slash

".strip_prefix()" removes leading slashes.

Code

use std::path::PathBuf;

fn main() {
  let dir_path = PathBuf::from("/alfa/bravo");
  let target_path = PathBuf::from("/alfa/bravo/charlie/delta.html");
  let cut_path = target_path.strip_prefix(dir_path);
  println!("{}", cut_path.unwrap().display());
}

Results

charlie/delta.html

This is how I'm adding it back in to make absolute URLs for my site:

Code

use std::path::PathBuf;

fn main() {
  let mut absolute_url = PathBuf::from("/");
  let source_dir = PathBuf::from("/alfa/bravo");
  let source_path = PathBuf::from("/alfa/bravo/charlie/delta.html");
  let relative_path = source_path.strip_prefix(source_dir).unwrap();
  absolute_url.push(relative_path);
  println!("{}", absolute_url.display());
}

Results

/charlie/delta.html