1 use crate::std::ffi::{OsStr, OsString}; 2 use crate::std::mem; 3 use crate::std::sealed::Sealed; 4 use crate::std::sys::os_str::Buf; 5 use crate::std::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 pub trait OsStringExt: Sealed { 15 /// Creates an [`OsString`] from a byte vector. 16 /// 17 /// See the module documentation for an example. 18 fn from_vec(vec: Vec<u8>) -> Self; 19 20 /// Yields the underlying byte vector of this [`OsString`]. 21 /// 22 /// See the module documentation for an example. 23 fn into_vec(self) -> Vec<u8>; 24 } 25 26 impl 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 /// 39 /// This trait is sealed: it cannot be implemented outside the standard library. 40 /// This is so that future additional methods are not breaking changes. 41 pub trait OsStrExt: Sealed { 42 /// Creates an [`OsStr`] from a byte slice. 43 /// 44 /// See the module documentation for an example. 45 fn from_bytes(slice: &[u8]) -> &Self; 46 47 /// Gets the underlying byte view of the [`OsStr`] slice. 48 /// 49 /// See the module documentation for an example. 50 fn as_bytes(&self) -> &[u8]; 51 } 52 53 impl OsStrExt for OsStr { 54 #[inline] 55 fn from_bytes(slice: &[u8]) -> &OsStr { 56 unsafe { mem::transmute(slice) } 57 } 58 #[inline] 59 fn as_bytes(&self) -> &[u8] { 60 &self.as_inner().inner 61 } 62 } 63