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///
11/// This trait is sealed: it cannot be implemented outside the standard library.
12/// This is so that future additional methods are not breaking changes.
13#[stable(feature = "rust1", since = "1.0.0")]
14pub impl(self) trait OsStringExt {
15    /// Creates an [`OsString`] from a byte vector.
16    ///
17    /// See the module documentation for an example.
18    #[stable(feature = "rust1", since = "1.0.0")]
19    fn from_vec(vec: Vec<u8>) -> Self;
20
21    /// Yields the underlying byte vector of this [`OsString`].
22    ///
23    /// See the module documentation for an example.
24    #[stable(feature = "rust1", since = "1.0.0")]
25    fn into_vec(self) -> Vec<u8>;
26}
27
28#[stable(feature = "rust1", since = "1.0.0")]
29impl OsStringExt for OsString {
30    #[inline]
31    fn from_vec(vec: Vec<u8>) -> OsString {
32        FromInner::from_inner(Buf { inner: vec })
33    }
34    #[inline]
35    fn into_vec(self) -> Vec<u8> {
36        self.into_inner().inner
37    }
38}
39
40/// Platform-specific extensions to [`OsStr`].
41///
42/// This trait is sealed: it cannot be implemented outside the standard library.
43/// This is so that future additional methods are not breaking changes.
44#[stable(feature = "rust1", since = "1.0.0")]
45pub impl(self) trait OsStrExt {
46    #[stable(feature = "rust1", since = "1.0.0")]
47    /// Creates an [`OsStr`] from a byte slice.
48    ///
49    /// See the module documentation for an example.
50    fn from_bytes(slice: &[u8]) -> &Self;
51
52    /// Gets the underlying byte view of the [`OsStr`] slice.
53    ///
54    /// See the module documentation for an example.
55    #[stable(feature = "rust1", since = "1.0.0")]
56    fn as_bytes(&self) -> &[u8];
57}
58
59#[stable(feature = "rust1", since = "1.0.0")]
60impl OsStrExt for OsStr {
61    #[inline]
62    fn from_bytes(slice: &[u8]) -> &OsStr {
63        unsafe { mem::transmute(slice) }
64    }
65    #[inline]
66    fn as_bytes(&self) -> &[u8] {
67        &self.as_inner().inner
68    }
69}