Palisand
Palisand

Reputation: 1362

Best way to format a file name based on another path in Rust

Is there a more concise way of writing the following?

use std::path::Path;

let path = Path::new("/path/to/foo.txt");
let formatted = &format!("{}%d.{}", path.file_stem().unwrap().to_str().unwrap(), path.extension().unwrap().to_str().unwrap());

assert_eq!("foo%d.txt", formatted);

(I want to convert /path/to/foo.txt to foo%d.txt)

Upvotes: 2

Views: 2834

Answers (1)

Shepmaster
Shepmaster

Reputation: 432079

No, there's not really anything better than what you have. A path is not a UTF-8 string, and a path might not have a file_stem or extension. You have to deal with all of those cases, this is what makes Rust a nice language.

The only thing I can suggest is to avoid transforming to a UTF-8 string at all. You can also use placeholder empty values or conditionally act if a component is missing:

use std::path::Path;
use std::ffi::OsStr;

fn main() {
    let path = Path::new("/path/to/foo.txt");

    let stem = path.file_stem().unwrap_or(OsStr::new(""));

    let mut filename = stem.to_os_string();
    filename.push("%d.");

    if let Some(extension) = path.extension() {
        filename.push(extension);
    }

    assert_eq!(OsStr::new("foo%d.txt"), filename);
}

Upvotes: 5

Related Questions