1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Unix-specific extension to the primitives in the `std::ffi` module
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use ffi::{OsStr, OsString};
18 use sys_common::{FromInner, IntoInner, AsInner};
20 /// Unix-specific extensions to `OsString`.
21 #[stable(feature = "rust1", since = "1.0.0")]
22 pub trait OsStringExt {
23 /// Creates an [`OsString`] from a byte vector.
28 /// use std::ffi::OsString;
29 /// use std::os::unix::ffi::OsStringExt;
31 /// let bytes = b"foo".to_vec();
32 /// let os_string = OsString::from_vec(bytes);
33 /// assert_eq!(os_string.to_str(), Some("foo"));
36 /// [`OsString`]: ../../../ffi/struct.OsString.html
37 #[stable(feature = "rust1", since = "1.0.0")]
38 fn from_vec(vec: Vec<u8>) -> Self;
40 /// Yields the underlying byte vector of this [`OsString`].
45 /// use std::ffi::OsString;
46 /// use std::os::unix::ffi::OsStringExt;
48 /// let mut os_string = OsString::new();
49 /// os_string.push("foo");
50 /// let bytes = os_string.into_vec();
51 /// assert_eq!(bytes, b"foo");
54 /// [`OsString`]: ../../../ffi/struct.OsString.html
55 #[stable(feature = "rust1", since = "1.0.0")]
56 fn into_vec(self) -> Vec<u8>;
59 #[stable(feature = "rust1", since = "1.0.0")]
60 impl OsStringExt for OsString {
61 fn from_vec(vec: Vec<u8>) -> OsString {
62 FromInner::from_inner(Buf { inner: vec })
64 fn into_vec(self) -> Vec<u8> {
65 self.into_inner().inner
69 /// Unix-specific extensions to `OsStr`.
70 #[stable(feature = "rust1", since = "1.0.0")]
72 #[stable(feature = "rust1", since = "1.0.0")]
73 /// Creates an [`OsStr`] from a byte slice.
78 /// use std::ffi::OsStr;
79 /// use std::os::unix::ffi::OsStrExt;
81 /// let bytes = b"foo";
82 /// let os_str = OsStr::from_bytes(bytes);
83 /// assert_eq!(os_str.to_str(), Some("foo"));
86 /// [`OsStr`]: ../../../ffi/struct.OsStr.html
87 fn from_bytes(slice: &[u8]) -> &Self;
89 /// Gets the underlying byte view of the [`OsStr`] slice.
94 /// use std::ffi::OsStr;
95 /// use std::os::unix::ffi::OsStrExt;
97 /// let mut os_str = OsStr::new("foo");
98 /// let bytes = os_str.as_bytes();
99 /// assert_eq!(bytes, b"foo");
102 /// [`OsStr`]: ../../../ffi/struct.OsStr.html
103 #[stable(feature = "rust1", since = "1.0.0")]
104 fn as_bytes(&self) -> &[u8];
107 #[stable(feature = "rust1", since = "1.0.0")]
108 impl OsStrExt for OsStr {
109 fn from_bytes(slice: &[u8]) -> &OsStr {
110 unsafe { mem::transmute(slice) }
112 fn as_bytes(&self) -> &[u8] {
113 &self.as_inner().inner