Sub topic 15
OsString, Path, and CString
This chapter assumes you know the difference between &str and String, and that Rust strings are always valid UTF-8. It also assumes you are comfortable with Option and Result. Some text does not fit that guarantee, so the standard library has extra string types for it.
Why String is not always enough
String must hold valid UTF-8. Two places where text comes from break that rule:
- The operating system. On Linux, a file name is any bytes except
/and the nul byte. On Windows, names are 16-bit units that may contain unpaired surrogates. Neither is always valid UTF-8. - C code. C strings end with a nul byte (
\0) and cannot contain one inside. A RustStringmay contain\0anywhere.
Rust gives each case its own type, so the compiler stops you from mixing them up.
| Owned | Borrowed | Use it for |
|---|---|---|
| `OsString` | `OsStr` | Text from the OS: environment variables, arguments, file names |
| `PathBuf` | `Path` | File system paths |
| `CString` | `CStr` | Nul-terminated strings passed to or from C |
The owned and borrowed pairs follow the same pattern as String and &str.
OsString and OsStr
An OsStr holds text in the platform's native form. Converting to &str can fail, so to_str returns an Option. When you only need something to display, to_string_lossy replaces invalid parts with the character � and returns a Cow<str>.
Path and PathBuf
Path wraps OsStr and adds methods for path parts. PathBuf is the owned, growable version. Use push to add components, so you don't need to handle separators yourself.
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
fn main() {
let name: OsString = OsString::from("report.txt");
let os: &OsStr = name.as_os_str();
match os.to_str() {
Some(s) => println!("valid UTF-8: {s}"),
None => println!("not valid UTF-8"),
}
println!("{}", os.to_string_lossy());
let mut dir = PathBuf::from("/tmp");
dir.push("logs");
dir.push("app.log");
let p: &Path = dir.as_path();
println!("{}", p.display());
println!("{:?}", p.file_name());
println!("{:?}", p.extension());
println!("{:?}", p.parent());
}Paths do not implement Display, because a path may not be printable as UTF-8. Call display() to get a printable wrapper, which is lossy.
CString and CStr
CString::new checks that the input has no interior nul byte, and it adds the terminating nul. It returns a Result because the check can fail. CStr is the borrowed form. You get a raw pointer with as_ptr to hand to C. The CString must stay alive for as long as C uses that pointer.
use std::ffi::{CStr, CString};
fn main() {
let c = CString::new("hi").unwrap();
println!("{:?}", c.as_bytes_with_nul());
match CString::new("a\0b") {
Ok(_) => println!("created"),
Err(e) => println!("nul byte at index {}", e.nul_position()),
}
let borrowed: &CStr = c.as_c_str();
println!("{}", borrowed.to_str().unwrap());
}The first line prints [104, 105, 0]: the two letters plus the terminator. The second prints nul byte at index 1.
Choosing a type
Common errors
- Calling
unwraponCString::newwith user input. A nul byte in that input causes a panic. Handle theErrcase. - Using
to_str().unwrap()on a file name. A non-UTF-8 name crashes the program. Useto_string_lossyfor display, or handleNone. - Dropping a
CStringwhile C still holds its pointer. CallingCString::new("x").unwrap().as_ptr()leaves the pointer dangling at the end of the statement. - Building paths with
format!("{dir}/{file}"). This hard-codes the separator. UsePath::joinorPathBuf::push.
Exercise
Why does CString::new return a Result, and why does Path have no Display implementation?
Show answer
CString::new fails when the input contains an interior nul byte, because C would treat that byte as the end of the string. Path has no Display because a path is not guaranteed to be valid UTF-8, so printing it could lose information. The display() method gives a lossy printable form.