Rust の OsString, OsStr と PathBuf, Path
前提
String は Vec<u8> としてデータを保持している
扱われるバイト列は UTF-8 として valid であることが保証される
https://doc.rust-lang.org/std/string/struct.String.html
OsString
UTF-8としてValidである保証がないが、文字列として扱いたいデータを表現する構造体
Rustの外の世界では文字列がUTF-8 encoded である保証がないための需要
- On Unix systems, strings are often arbitrary sequences of non-zero bytes, in many cases interpreted as UTF-8.
- On Windows, strings are often arbitrary sequences of non-zero 16-bit values, interpreted as UTF-16 when it is valid to do so.
- In Rust, strings are always valid UTF-8, which may contain zeros.
OsString in std::ffi - Rust
e.g. ファイル名・環境変数・コマンド引数
Accepting Command Line Arguments - The Rust Programming Language
UTF-16 encoded な値も 8 bit のバイト列( Vec<u8> )として保持するので、capacity や length を扱うときは注意
もちろんnul-terminatedの保証は無いので、システムコールに渡したりしたいときは CStrや CString を使うこと
OsStr
OsString に対する OsStr の関係が String に対する Str の関係に対応
Owned <-> Borrowed
PathBuf
Path
参考
PathBuf と &Path|Rust の文字列の種類と変換トレイトについて
Path - Rust By Example 日本語版
OsString と &OsStr|Rust の文字列の種類と変換トレイトについて