]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/os_str_bytes.rs
323165cda6bd5387f7cdf2bd9f4f1d8adff42070
[rust.git] / library / std / src / sys_common / os_str_bytes.rs
1 //! The underlying OsString/OsStr implementation on Unix and many other
2 //! systems: just a `Vec<u8>`/`[u8]`.
3
4 use crate::borrow::Cow;
5 use crate::ffi::{OsStr, OsString};
6 use crate::fmt;
7 use crate::mem;
8 use crate::rc::Rc;
9 use crate::str;
10 use crate::sync::Arc;
11 use crate::sys_common::bytestring::debug_fmt_bytestring;
12 use crate::sys_common::{AsInner, FromInner, IntoInner};
13
14 use core::str::lossy::Utf8Lossy;
15
16 #[derive(Clone, Hash)]
17 pub(crate) struct Buf {
18     pub inner: Vec<u8>,
19 }
20
21 // FIXME:
22 // `Buf::as_slice` current implementation relies
23 // on `Slice` being layout-compatible with `[u8]`.
24 // When attribute privacy is implemented, `Slice` should be annotated as `#[repr(transparent)]`.
25 // Anyway, `Slice` representation and layout are considered implementation detail, are
26 // not documented and must not be relied upon.
27 pub(crate) struct Slice {
28     pub inner: [u8],
29 }
30
31 impl fmt::Debug for Slice {
32     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
33         debug_fmt_bytestring(&self.inner, formatter)
34     }
35 }
36
37 impl fmt::Display for Slice {
38     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39         fmt::Display::fmt(&Utf8Lossy::from_bytes(&self.inner), formatter)
40     }
41 }
42
43 impl fmt::Debug for Buf {
44     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
45         fmt::Debug::fmt(self.as_slice(), formatter)
46     }
47 }
48
49 impl fmt::Display for Buf {
50     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
51         fmt::Display::fmt(self.as_slice(), formatter)
52     }
53 }
54
55 impl IntoInner<Vec<u8>> for Buf {
56     fn into_inner(self) -> Vec<u8> {
57         self.inner
58     }
59 }
60
61 impl AsInner<[u8]> for Buf {
62     fn as_inner(&self) -> &[u8] {
63         &self.inner
64     }
65 }
66
67 impl Buf {
68     pub fn from_string(s: String) -> Buf {
69         Buf { inner: s.into_bytes() }
70     }
71
72     #[inline]
73     pub fn with_capacity(capacity: usize) -> Buf {
74         Buf { inner: Vec::with_capacity(capacity) }
75     }
76
77     #[inline]
78     pub fn clear(&mut self) {
79         self.inner.clear()
80     }
81
82     #[inline]
83     pub fn capacity(&self) -> usize {
84         self.inner.capacity()
85     }
86
87     #[inline]
88     pub fn reserve(&mut self, additional: usize) {
89         self.inner.reserve(additional)
90     }
91
92     #[inline]
93     pub fn reserve_exact(&mut self, additional: usize) {
94         self.inner.reserve_exact(additional)
95     }
96
97     #[inline]
98     pub fn shrink_to_fit(&mut self) {
99         self.inner.shrink_to_fit()
100     }
101
102     #[inline]
103     pub fn shrink_to(&mut self, min_capacity: usize) {
104         self.inner.shrink_to(min_capacity)
105     }
106
107     #[inline]
108     pub fn as_slice(&self) -> &Slice {
109         // Safety: Slice just wraps [u8],
110         // and &*self.inner is &[u8], therefore
111         // transmuting &[u8] to &Slice is safe.
112         unsafe { mem::transmute(&*self.inner) }
113     }
114
115     #[inline]
116     pub fn as_mut_slice(&mut self) -> &mut Slice {
117         // Safety: Slice just wraps [u8],
118         // and &mut *self.inner is &mut [u8], therefore
119         // transmuting &mut [u8] to &mut Slice is safe.
120         unsafe { mem::transmute(&mut *self.inner) }
121     }
122
123     pub fn into_string(self) -> Result<String, Buf> {
124         String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() })
125     }
126
127     pub fn push_slice(&mut self, s: &Slice) {
128         self.inner.extend_from_slice(&s.inner)
129     }
130
131     #[inline]
132     pub fn into_box(self) -> Box<Slice> {
133         unsafe { mem::transmute(self.inner.into_boxed_slice()) }
134     }
135
136     #[inline]
137     pub fn from_box(boxed: Box<Slice>) -> Buf {
138         let inner: Box<[u8]> = unsafe { mem::transmute(boxed) };
139         Buf { inner: inner.into_vec() }
140     }
141
142     #[inline]
143     pub fn into_arc(&self) -> Arc<Slice> {
144         self.as_slice().into_arc()
145     }
146
147     #[inline]
148     pub fn into_rc(&self) -> Rc<Slice> {
149         self.as_slice().into_rc()
150     }
151 }
152
153 impl Slice {
154     #[inline]
155     fn from_u8_slice(s: &[u8]) -> &Slice {
156         unsafe { mem::transmute(s) }
157     }
158
159     #[inline]
160     pub fn from_str(s: &str) -> &Slice {
161         Slice::from_u8_slice(s.as_bytes())
162     }
163
164     pub fn to_str(&self) -> Option<&str> {
165         str::from_utf8(&self.inner).ok()
166     }
167
168     pub fn to_string_lossy(&self) -> Cow<'_, str> {
169         String::from_utf8_lossy(&self.inner)
170     }
171
172     pub fn to_owned(&self) -> Buf {
173         Buf { inner: self.inner.to_vec() }
174     }
175
176     pub fn clone_into(&self, buf: &mut Buf) {
177         self.inner.clone_into(&mut buf.inner)
178     }
179
180     #[inline]
181     pub fn into_box(&self) -> Box<Slice> {
182         let boxed: Box<[u8]> = self.inner.into();
183         unsafe { mem::transmute(boxed) }
184     }
185
186     pub fn empty_box() -> Box<Slice> {
187         let boxed: Box<[u8]> = Default::default();
188         unsafe { mem::transmute(boxed) }
189     }
190
191     #[inline]
192     pub fn into_arc(&self) -> Arc<Slice> {
193         let arc: Arc<[u8]> = Arc::from(&self.inner);
194         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) }
195     }
196
197     #[inline]
198     pub fn into_rc(&self) -> Rc<Slice> {
199         let rc: Rc<[u8]> = Rc::from(&self.inner);
200         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) }
201     }
202
203     #[inline]
204     pub fn make_ascii_lowercase(&mut self) {
205         self.inner.make_ascii_lowercase()
206     }
207
208     #[inline]
209     pub fn make_ascii_uppercase(&mut self) {
210         self.inner.make_ascii_uppercase()
211     }
212
213     #[inline]
214     pub fn to_ascii_lowercase(&self) -> Buf {
215         Buf { inner: self.inner.to_ascii_lowercase() }
216     }
217
218     #[inline]
219     pub fn to_ascii_uppercase(&self) -> Buf {
220         Buf { inner: self.inner.to_ascii_uppercase() }
221     }
222
223     #[inline]
224     pub fn is_ascii(&self) -> bool {
225         self.inner.is_ascii()
226     }
227
228     #[inline]
229     pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
230         self.inner.eq_ignore_ascii_case(&other.inner)
231     }
232 }
233
234 /// Platform-specific extensions to [`OsString`].
235 #[stable(feature = "rust1", since = "1.0.0")]
236 pub trait OsStringExt {
237     /// Creates an [`OsString`] from a byte vector.
238     ///
239     /// See the module documentation for an example.
240     #[stable(feature = "rust1", since = "1.0.0")]
241     fn from_vec(vec: Vec<u8>) -> Self;
242
243     /// Yields the underlying byte vector of this [`OsString`].
244     ///
245     /// See the module documentation for an example.
246     #[stable(feature = "rust1", since = "1.0.0")]
247     fn into_vec(self) -> Vec<u8>;
248 }
249
250 #[stable(feature = "rust1", since = "1.0.0")]
251 impl OsStringExt for OsString {
252     fn from_vec(vec: Vec<u8>) -> OsString {
253         FromInner::from_inner(Buf { inner: vec })
254     }
255     fn into_vec(self) -> Vec<u8> {
256         self.into_inner().inner
257     }
258 }
259
260 /// Platform-specific extensions to [`OsStr`].
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub trait OsStrExt {
263     #[stable(feature = "rust1", since = "1.0.0")]
264     /// Creates an [`OsStr`] from a byte slice.
265     ///
266     /// See the module documentation for an example.
267     fn from_bytes(slice: &[u8]) -> &Self;
268
269     /// Gets the underlying byte view of the [`OsStr`] slice.
270     ///
271     /// See the module documentation for an example.
272     #[stable(feature = "rust1", since = "1.0.0")]
273     fn as_bytes(&self) -> &[u8];
274 }
275
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl OsStrExt for OsStr {
278     #[inline]
279     fn from_bytes(slice: &[u8]) -> &OsStr {
280         unsafe { mem::transmute(slice) }
281     }
282     #[inline]
283     fn as_bytes(&self) -> &[u8] {
284         &self.as_inner().inner
285     }
286 }