Append an additional extension?

I don't believe there's a function for it in std. How about this?

fn add_extension(path: &mut std::path::PathBuf, extension: impl AsRef<std::path::Path>) {
    match path.extension() {
        Some(ext) => {
            let mut ext = ext.to_os_string();
            ext.push(".");
            ext.push(extension.as_ref());
            path.set_extension(ext)
        }
        None => path.set_extension(extension.as_ref()),
    };
}

fn main() {
    let mut path = std::path::PathBuf::from("/var/log/kern.log");
    add_extension(&mut path, "gz");
    assert_eq!(path.as_os_str(), "/var/log/kern.log.gz");
}

If you only need to do it once, or you know for sure the path has an extension, you can do it without a function or in fewer lines.

5 Likes