Struct OsString
struct OsString { ... }
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.
Capacity of OsString
Capacity uses units of UTF-8 bytes for OS strings which were created from valid unicode, and
uses units of bytes in an unspecified encoding for other contents. On a given target, all
OsString and OsStr values use the same units for capacity, so the following will work:
use ;
Creating an OsString
From a Rust string: OsString implements
[From]<[String]>, so you can use my_string.into() 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 some &[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.
Implementations
impl OsString
const fn new() -> OsStringConstructs a new empty
OsString.Examples
use OsString; let os_string = new;unsafe fn from_encoded_bytes_unchecked(bytes: Vec<u8>) -> SelfConverts bytes to an
OsStringwithout checking that the bytes contains validOsStr-encoded data.The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8. By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit ASCII.
See the module's toplevel documentation about conversions for safe, cross-platform conversions from/to native representations.
Safety
As the encoding is unspecified, callers must pass in bytes that originated as a mixture of validated UTF-8 and bytes from
OsStr::as_encoded_bytesfrom within the same Rust version built for the same target platform. For example, reconstructing anOsStringfrom bytes sent over the network or stored in a file will likely violate these safety rules.Due to the encoding being self-synchronizing, the bytes from
OsStr::as_encoded_bytescan be split either immediately before or immediately after any valid non-empty UTF-8 substring.Example
use OsStr; let os_str = new; let bytes = os_str.as_encoded_bytes; let words = bytes.split; let words: = words.map.collect;fn as_os_str(self: &Self) -> &OsStrConverts to an
OsStrslice.Examples
use ; let os_string = from; let os_str = new; assert_eq!;fn into_encoded_bytes(self: Self) -> Vec<u8>Converts the
OsStringinto a byte vector. To convert the byte vector back into anOsString, use theOsString::from_encoded_bytes_uncheckedfunction.The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8. By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit ASCII.
Note: As the encoding is unspecified, any sub-slice of bytes that is not valid UTF-8 should be treated as opaque and only comparable within the same Rust version built for the same target platform. For example, sending the bytes over the network or storing it in a file will likely result in incompatible data. See
OsStringfor more encoding details andstd::ffifor platform-specific, specified conversions.fn into_string(self: Self) -> Result<String, OsString>Converts the
OsStringinto aStringif it contains valid Unicode data.On failure, ownership of the original
OsStringis returned.Examples
use OsString; let os_string = from; let string = os_string.into_string; assert_eq!;fn push<T: AsRef<OsStr>>(self: &mut Self, s: T)Extends the string with the given
&[OsStr]slice.Examples
use OsString; let mut os_string = from; os_string.push; assert_eq!;fn with_capacity(capacity: usize) -> OsStringCreates a new
OsStringwith at least the given capacity.The string will be able to hold at least
capacitylength units of other OS strings without reallocating. This method is allowed to allocate for more units thancapacity. Ifcapacityis 0, the string will not allocate.See the main
OsStringdocumentation information about encoding and capacity units.Examples
use OsString; let mut os_string = with_capacity; let capacity = os_string.capacity; // This push is done without reallocating os_string.push; assert_eq!;fn clear(self: &mut Self)Truncates the
OsStringto zero length.Examples
use OsString; let mut os_string = from; assert_eq!; os_string.clear; assert_eq!;fn capacity(self: &Self) -> usizeReturns the capacity this
OsStringcan hold without reallocating.See the main
OsStringdocumentation information about encoding and capacity units.Examples
use OsString; let os_string = with_capacity; assert!;fn reserve(self: &mut Self, additional: usize)Reserves capacity for at least
additionalmore capacity to be inserted in the givenOsString. Does nothing if the capacity is already sufficient.The collection may reserve more space to speculatively avoid frequent reallocations.
See the main
OsStringdocumentation information about encoding and capacity units.Examples
use OsString; let mut s = new; s.reserve; assert!;fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve capacity for at least
additionalmore length units in the givenOsString. The string may reserve more space to speculatively avoid frequent reallocations. After callingtry_reserve, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.See the main
OsStringdocumentation information about encoding and capacity units.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use ; use TryReserveError; # process_data.expect;fn reserve_exact(self: &mut Self, additional: usize)Reserves the minimum capacity for at least
additionalmore capacity to be inserted in the givenOsString. Does nothing if the capacity is already sufficient.Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer
reserveif future insertions are expected.See the main
OsStringdocumentation information about encoding and capacity units.Examples
use OsString; let mut s = new; s.reserve_exact; assert!;fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve the minimum capacity for at least
additionalmore length units in the givenOsString. After callingtry_reserve_exact, capacity will be greater than or equal toself.len() + additionalif it returnsOk(()). Does nothing if the capacity is already sufficient.Note that the allocator may give the
OsStringmore space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefertry_reserveif future insertions are expected.See the main
OsStringdocumentation information about encoding and capacity units.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use ; use TryReserveError; # process_data.expect;fn shrink_to_fit(self: &mut Self)Shrinks the capacity of the
OsStringto match its length.See the main
OsStringdocumentation information about encoding and capacity units.Examples
use OsString; let mut s = from; s.reserve; assert!; s.shrink_to_fit; assert_eq!;fn shrink_to(self: &mut Self, min_capacity: usize)Shrinks the capacity of the
OsStringwith a lower bound.The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
See the main
OsStringdocumentation information about encoding and capacity units.Examples
use OsString; let mut s = from; s.reserve; assert!; s.shrink_to; assert!; s.shrink_to; assert!;fn into_boxed_os_str(self: Self) -> Box<OsStr>Converts this
OsStringinto a boxedOsStr.Examples
use ; let s = from; let b: = s.into_boxed_os_str;fn leak<'a>(self: Self) -> &'a mut OsStrConsumes and leaks the
OsString, returning a mutable reference to the contents,&'a mut OsStr.The caller has free choice over the returned lifetime, including 'static. Indeed, this function is ideally used for data that lives for the remainder of the program’s life, as dropping the returned reference will cause a memory leak.
It does not reallocate or shrink the
OsString, so the leaked allocation may include unused capacity that is not part of the returned slice. If you want to discard excess capacity, callinto_boxed_os_str, and thenBox::leakinstead. However, keep in mind that trimming the capacity may result in a reallocation and copy.fn truncate(self: &mut Self, len: usize)Truncate the
OsStringto the specified length.Panics
Panics if
lendoes not lie on a validOsStrboundary (as described inOsStr::slice_encoded_bytes).
impl AsRef for OsString
fn as_ref(self: &Self) -> &OsStr
impl AsRef for crate::ffi::OsString
fn as_ref(self: &Self) -> &Path
impl Borrow for OsString
fn borrow(self: &Self) -> &OsStr
impl Clone for OsString
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)Clones the contents of
sourceintoself.This method is preferred over simply assigning
source.clone()toself, as it avoids reallocation if possible.
impl Debug for OsString
fn fmt(self: &Self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result
impl Default for OsString
fn default() -> OsStringConstructs an empty
OsString.
impl Deref for OsString
fn deref(self: &Self) -> &OsStr
impl DerefMut for OsString
fn deref_mut(self: &mut Self) -> &mut OsStr
impl Eq for OsString
impl Extend for OsString
fn extend<T: IntoIterator<Item = OsString>>(self: &mut Self, iter: T)
impl Freeze for OsString
impl From for OsString
impl From for OsString
fn from(boxed: Box<OsStr>) -> OsStringConverts a
[Box]<[OsStr]>into anOsStringwithout copying or allocating.
impl From for crate::ffi::OsString
impl FromIterator for OsString
fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self
impl FromStr for OsString
fn from_str(s: &str) -> Result<Self, <Self as >::Err>
impl Hash for OsString
fn hash<H: Hasher>(self: &Self, state: &mut H)
impl Index for OsString
fn index(self: &Self, _index: ops::RangeFull) -> &OsStr
impl IndexMut for OsString
fn index_mut(self: &mut Self, _index: ops::RangeFull) -> &mut OsStr
impl Ord for OsString
fn cmp(self: &Self, other: &OsString) -> cmp::Ordering
impl OsStringExt for crate::ffi::OsString
fn from_vec(vec: Vec<u8>) -> OsStringfn into_vec(self: Self) -> Vec<u8>
impl OsStringExt for crate::ffi::OsString
fn from_wide(wide: &[u16]) -> OsString
impl OsStringExt for crate::ffi::OsString
fn from_vec(vec: Vec<u8>) -> OsStringfn into_vec(self: Self) -> Vec<u8>
impl PartialEq for OsString
fn eq(self: &Self, other: &str) -> bool
impl PartialEq for OsString
fn eq(self: &Self, other: &&str) -> bool
impl PartialEq for OsString
fn eq(self: &Self, other: &OsString) -> bool
impl PartialEq for crate::ffi::OsString
fn eq(self: &Self, other: &PathBuf) -> bool
impl PartialEq for crate::ffi::OsString
fn eq(self: &Self, other: &Path) -> bool
impl PartialOrd for OsString
fn partial_cmp(self: &Self, other: &str) -> Option<cmp::Ordering>
impl PartialOrd for OsString
fn partial_cmp(self: &Self, other: &OsString) -> Option<cmp::Ordering>fn lt(self: &Self, other: &OsString) -> boolfn le(self: &Self, other: &OsString) -> boolfn gt(self: &Self, other: &OsString) -> boolfn ge(self: &Self, other: &OsString) -> bool
impl PartialOrd for crate::ffi::OsString
fn partial_cmp(self: &Self, other: &PathBuf) -> Option<cmp::Ordering>
impl PartialOrd for crate::ffi::OsString
fn partial_cmp(self: &Self, other: &Path) -> Option<cmp::Ordering>
impl RefUnwindSafe for OsString
impl Send for OsString
impl Sync for OsString
impl Unpin for OsString
impl UnwindSafe for OsString
impl Write for OsString
fn write_str(self: &mut Self, s: &str) -> fmt::Result
impl<'a> Extend for OsString
fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(self: &mut Self, iter: T)
impl<'a> Extend for OsString
fn extend<T: IntoIterator<Item = &'a OsStr>>(self: &mut Self, iter: T)
impl<'a> From for OsString
fn from(s: Cow<'a, OsStr>) -> SelfConverts a
Cow<'a, OsStr>into anOsString, by copying the contents if they are borrowed.
impl<'a> FromIterator for OsString
fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self
impl<'a> FromIterator for OsString
fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self
impl<'a> PartialEq for crate::ffi::OsString
fn eq(self: &Self, other: &&'a Path) -> bool
impl<'a> PartialEq for crate::ffi::OsString
fn eq(self: &Self, other: &Cow<'a, Path>) -> bool
impl<'a> PartialOrd for crate::ffi::OsString
fn partial_cmp(self: &Self, other: &&'a Path) -> Option<cmp::Ordering>
impl<'a> PartialOrd for crate::ffi::OsString
fn partial_cmp(self: &Self, other: &Cow<'a, Path>) -> Option<cmp::Ordering>
impl<'a, 'b> PartialEq for OsString
fn eq(self: &Self, other: &OsStr) -> bool
impl<'a, 'b> PartialEq for OsString
fn eq(self: &Self, other: &&'a OsStr) -> bool
impl<'a, 'b> PartialEq for OsString
fn eq(self: &Self, other: &Cow<'a, OsStr>) -> bool
impl<'a, 'b> PartialOrd for OsString
fn partial_cmp(self: &Self, other: &OsStr) -> Option<cmp::Ordering>
impl<'a, 'b> PartialOrd for OsString
fn partial_cmp(self: &Self, other: &&'a OsStr) -> Option<cmp::Ordering>
impl<'a, 'b> PartialOrd for OsString
fn partial_cmp(self: &Self, other: &Cow<'a, OsStr>) -> Option<cmp::Ordering>
impl<P, T> Receiver for OsString
impl<T> Any for OsString
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for OsString
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for OsString
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for OsString
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for OsString
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for OsString
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for OsString
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for OsString
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for OsString
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<T: ?Sized + AsRef<OsStr>> From for OsString
fn from(s: &T) -> OsStringCopies any value implementing
[AsRef]<[OsStr]>into a newly allocatedOsString.