0

std::ffi

 2 years ago
source link: https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Struct std::ffi::OsString1.0.0[−][src]

pub struct OsString { /* fields omitted */ }

A type that can represent owned, mutable platform-native strings, but is cheaply inter-convertible with Rust strings.

The need for this type arises from the fact that:

  • 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 and OsStr bridge this gap by simultaneously representing Rust and platform-native string values, and in particular allowing a Rust string to be converted into an “OS” string with no cost if possible. A consequence of this is that OsString instances are not NUL terminated; in order to pass to e.g., Unix system call, you should create a CStr.

OsString is to &OsStr as String is to &str: the former in each pair are owned strings; the latter are borrowed references.

Note, OsString and OsStr internally do not necessarily hold strings in the form native to the platform; While on Unix, strings are stored as a sequence of 8-bit values, on Windows, where strings are 16-bit value based as just discussed, strings are also actually stored as a sequence of 8-bit values, encoded in a less-strict variant of UTF-8. This is useful to understand when handling capacity and length values.

Creating an OsString

From a Rust string: OsString implements From<String>, so you can use my_string.from to create an OsString from a normal Rust string.

From slices: Just like you can start with an empty Rust String and then String::push_str &str sub-string slices into it, you can create an empty OsString with the OsString::new method and then push string slices into it with the OsString::push method.

Extracting a borrowed reference to the whole OS string

You can use the OsString::as_os_str method to get an &OsStr from an OsString; this is effectively a borrowed reference to the whole string.

Conversions

See the module’s toplevel documentation about conversions for a discussion on the traits which OsString implements for conversions from/to native representations.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK