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