OsStr And OsString Boundary Conversions

Convert OS strings deliberately at boundaries: to_str for strict UTF-8, to_string_lossy for display, and into_string to reclaim an owned String.

RustData Integrity

Code

rustsnippet
34 lines
use std::ffi::{OsStr, OsString};
use std::path::Path;

fn main() {
    // 路径 API 返回 &OsStr:文件名并不保证是合法 UTF-8
    let ext: &OsStr = Path::new("report.q4.csv").extension().unwrap_or_default();
    println!("extension: {}", ext.to_string_lossy());

    // 严格转换:合法 UTF-8 才拿到 Some(&str)
    match ext.to_str() {
        Some(text) => println!("strict: {text}"),
        None => println!("strict: not utf-8"),
    }

    // OsString 拥有所有权,可以像字符串一样拼接
    let mut filename = OsString::from("backup-");
    filename.push("2026.log");
    println!("built: {}", filename.to_string_lossy());

    // 只有确为 UTF-8 时才能拿回 String;失败时原 OsString 原样归还
    match filename.into_string() {
        Ok(owned) => println!("owned string: {owned}"),
        Err(original) => println!("kept as OsString: {}", original.to_string_lossy()),
    }

    // Unix 上路径可能含非 UTF-8 字节:严格转换失败,lossy 用 U+FFFD 替换
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        let raw = OsStr::from_bytes(&[0x64, 0x61, 0xff]);
        println!("raw strict: {:?}", raw.to_str());
        println!("raw lossy: {}", raw.to_string_lossy());
    }
}

What the code does

OsStr And OsString Boundary Conversions is built around the function main.

Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Caveats

  • By construction there is no dependency — nothing in a registry, nothing in a lockfile.

Using it

Signature: fn main()

The run emits 8 labeled sections — extension:, strict:, strict: not utf-8, built:, owned string:, kept as OsString:, raw strict:, raw lossy: — one per step.

Key statements

let ext: &OsStr = Path::new("report.q4.csv").extension().unwrap_or_default();
match filename.into_string() {
    Ok(owned) => println!("owned string: {owned}"),
    Err(original) => println!("kept as OsString: {}", original.to_string_lossy()),
}
match ext.to_str() {
    Some(text) => println!("strict: {text}"),
    None => println!("strict: not utf-8"),
}

Interactive Tools for This Topic

FAQ

What does OsStr And OsString Boundary Conversions print when run?
The script runs standalone; its 8 labeled outputs include `extension:`, `strict:`, `strict: not utf-8`.