Skip to main content

std/os/unix/ffi/
os_str.rs

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