FAQ - Help and questions

Why does Path::to_str return None, and how do I show a file name that is not valid UTF-8?

#paths#utf-8#windows#macospublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Paths belong to the operating system, not to Rust, and need not be valid Unicode. to_str returns None for such a name. Keep values as Path or OsString inside the program, use to_string_lossy when you only need to display a name, and never use it to find the file again. A Windows example is run below.

Checked with rustc 1.93.0, Windows 11; compiled and run. The example builds a name that Windows allows and Rust cannot hold as UTF-8; the macOS side is from std's documentation and was not run.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A Rust String is always valid UTF-8. A file name is not: Windows names are sequences of 16-bit units that may contain unpaired surrogates, and Unix-like systems (macOS among them) store names as bytes that std does not require to be UTF-8. So Rust has OsStr, OsString, Path and PathBuf for names as the system sees them, and conversions to str return an Option for the case where the name does not fit.

src/main.rsrust
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::path::PathBuf;

fn main() {
    // A Windows file name can hold an unpaired UTF-16 surrogate, which has no UTF-8 form.
    let wide: Vec<u16> = vec![b'a' as u16, 0xD800, b'.' as u16, b't' as u16];
    let name = PathBuf::from(OsString::from_wide(&wide));
    println!("to_str():          {:?}", name.to_str());
    println!("to_string_lossy(): {}", name.to_string_lossy());
    println!("Debug:             {:?}", name);
}
text
to_str():          None
to_string_lossy(): a�.t
Debug:             "a\u{d800}.t"

(The program imports a Windows-only extension trait, so it builds on Windows only; that is why it is a good example of the next topic, conditional compilation.)

Rules:

  1. Keep Path all the way. Read the name from the system as a Path, give it back to the system as a Path (to open, rename, delete). Nothing is lost.
  2. Convert only to display. to_string_lossy() replaces unrepresentable parts with the replacement character �. Good for a list in a window; wrong for finding the file again, because the name is changed.
  3. Convert to String only when you must store it, for example in a JSON settings file. Decide the policy: skip such files, show an error, or store the bytes in a form of your own.
  4. Do not unwrap() to_str(). One odd file name in a folder then crashes your app.

Common mistakes#

  • Using to_string_lossy().to_string() and then opening that string as a path.
  • Assuming file names are valid text because you only ever saw English ones.

Does this really happen?#

Rarely, but a program that opens users' folders meets all kinds of names, and old archives and downloads are where it shows up.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet