Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Strings and Text

Rust OsString and OsStr

Reference for Rust OsString and OsStr: strings in the operating system's own format for paths, arguments and environment variables, with lossless conversions.

The operating system does not promise UTF-8. On Unix, file names, command-line arguments and environment variables are arbitrary bytes. On Windows they are sequences of 16-bit units that may contain unpaired surrogates. OsString (owned) and OsStr (borrowed) hold such text exactly as the platform gave it, so you can pass it back to the OS without losing anything.

Path and PathBuf are thin wrappers around OsStr and OsString. Functions like Path::file_name, env::args_os and env::var_os return these types, and you convert to str only when you must display or parse the text.

Rust
use std::ffi::OsString;
let name = OsString::from("report.txt");

Try it

Rust Creating and converting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Non-UTF-8 data on Unix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn OsString::new() -> OsString
fn OsString::push<T: AsRef<OsStr>>(&mut self, s: T)
fn OsString::into_string(self) -> Result<String, OsString>
fn OsStr::new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr
fn OsStr::to_str(&self) -> Option<&str>
fn OsStr::to_string_lossy(&self) -> Cow<'_, str>
fn OsStr::len(&self) -> usize
fn OsStr::as_encoded_bytes(&self) -> &[u8]
Name Description
s Anything that can be viewed as an OsStr: &str, String, OsString, Path.

Returns: to_str gives Some(&str) only when the contents are valid Unicode. into_string gives the String or hands the OsString back in the Err. to_string_lossy always succeeds, replacing invalid parts with U+FFFD.

Errors / panics / edge cases: none of these panic. The internal encoding is not specified: len() counts bytes of an implementation-defined encoding, and as_encoded_bytes must only be handed back to from_encoded_bytes_unchecked on the same platform and program version.

Usage notes

  • Use OsStr for anything that comes from or goes to the OS: file names, argument lists (env::args_os()), environment variables (env::var_os()), Command arguments.
  • env::args() panics when an argument is not valid Unicode, while args_os() never does. Prefer args_os in tools that handle arbitrary file names.
  • Conversion to str can fail. Handle None from to_str, or use to_string_lossy when the text is only for display or logs.
  • Many things convert for free: String, &str, Path and PathBuf all implement AsRef<OsStr>, so APIs taking impl AsRef<OsStr> accept them all.
  • There are no text operations. OsStr has no split, find or trim in the standard library, because the encoding is opaque. Convert to str, or go through the platform extension traits.
  • Platform extensions: std::os::unix::ffi::{OsStrExt, OsStringExt} convert to and from raw bytes; std::os::windows::ffi::{OsStrExt, OsStringExt} convert to and from UTF-16 (encode_wide, from_wide).
  • Ordering and equality work on the underlying data, so OsString can be a key in HashMap and BTreeMap.
  • Use Path methods (join, extension, file_stem) for file names instead of splitting strings by hand.