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.
use std::ffi::OsString; let name = OsString::from("report.txt");
Try it
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.
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
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
OsStrfor anything that comes from or goes to the OS: file names, argument lists (env::args_os()), environment variables (env::var_os()),Commandarguments. env::args()panics when an argument is not valid Unicode, whileargs_os()never does. Preferargs_osin tools that handle arbitrary file names.- Conversion to
strcan fail. HandleNonefromto_str, or useto_string_lossywhen the text is only for display or logs. - Many things convert for free:
String,&str,PathandPathBufall implementAsRef<OsStr>, so APIs takingimpl AsRef<OsStr>accept them all. - There are no text operations.
OsStrhas nosplit,findortrimin the standard library, because the encoding is opaque. Convert tostr, 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
OsStringcan be a key inHashMapandBTreeMap. - Use
Pathmethods (join,extension,file_stem) for file names instead of splitting strings by hand.
Related
CStringandCStr,String,from_utf8,as_bytes- Lessons: Strings, Strings overview