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