Skip to main content

std/os/unix/ffi/
os_str.rs

1use crate::ffi::{OsStr, OsString};
2use crate::mem;
3use crate::sys::os_str::Buf;
4use crate::sys::{AsInner, FromInner, IntoInner};
5
6// Note: this file is currently reused in other `std::os::{platform}::ffi` modules to reduce duplication.
7// Keep this in mind when applying changes to this file that only apply to `unix`.
8
9/// Platform-specific extensions to [`OsString`].
10#[stable(feature = "rust1", since = "1.0.0")]
11pub impl(self) trait OsStringExt {
12    /// Creates an [`OsString`] from a byte vector.
13    ///
14    /// See the module documentation for an example.
15    #[stable(feature = "rust1", since = "1.0.0")]
16    fn from_vec(vec: Vec<u8>) -> Self;
17
18    /// Yields the underlying byte vector of this [`OsString`].
19    ///
20    /// See the module documentation for an example.
21    #[stable(feature = "rust1", since = "1.0.0")]
22    fn into_vec(self) -> Vec<u8>;
23}
24
25#[stable(feature = "rust1", since = "1.0.0")]
26impl OsStringExt for OsString {
27    #[inline]
28    fn from_vec(vec: Vec<u8>) -> OsString {
29        FromInner::from_inner(Buf { inner: vec })
30    }
31    #[inline]
32    fn into_vec(self) -> Vec<u8> {
33        self.into_inner().inner
34    }
35}
36
37/// Platform-specific extensions to [`OsStr`].
38#[stable(feature = "rust1", since = "1.0.0")]
39pub impl(self) trait OsStrExt {
40    #[stable(feature = "rust1", since = "1.0.0")]
41    /// Creates an [`OsStr`] from a byte slice.
42    ///
43    /// See the module documentation for an example.
44    fn from_bytes(slice: &[u8]) -> &Self;
45
46    /// Gets the underlying byte view of the [`OsStr`] slice.
47    ///
48    /// See the module documentation for an example.
49    #[stable(feature = "rust1", since = "1.0.0")]
50    fn as_bytes(&self) -> &[u8];
51}
52
53#[stable(feature = "rust1", since = "1.0.0")]
54impl OsStrExt for OsStr {
55    #[inline]
56    fn from_bytes(slice: &[u8]) -> &OsStr {
57        unsafe { mem::transmute(slice) }
58    }
59    #[inline]
60    fn as_bytes(&self) -> &[u8] {
61        &self.as_inner().inner
62    }
63}