]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/os_str.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / libstd / ffi / os_str.rs
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.
4 //
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.
10
11 //! A type that can represent all platform-native strings, but is cheaply
12 //! interconvertable with Rust strings.
13 //!
14 //! The need for this type arises from the fact that:
15 //!
16 //! * On Unix systems, strings are often arbitrary sequences of non-zero
17 //!   bytes, in many cases interpreted as UTF-8.
18 //!
19 //! * On Windows, strings are often arbitrary sequences of non-zero 16-bit
20 //!   values, interpreted as UTF-16 when it is valid to do so.
21 //!
22 //! * In Rust, strings are always valid UTF-8, but may contain zeros.
23 //!
24 //! The types in this module bridge this gap by simultaneously representing Rust
25 //! and platform-native string values, and in particular allowing a Rust string
26 //! to be converted into an "OS" string with no cost.
27 //!
28 //! **Note**: At the moment, these types are extremely bare-bones, usable only
29 //! for conversion to/from various other string types. Eventually these types
30 //! will offer a full-fledged string API.
31
32 #![unstable(feature = "os",
33             reason = "recently added as part of path/io reform")]
34
35 use core::prelude::*;
36
37 use borrow::{Borrow, ToOwned};
38 use fmt::{self, Debug};
39 use mem;
40 use string::{String, CowString};
41 use ops;
42 use cmp;
43 use hash::{Hash, Hasher};
44 #[cfg(stage0)] use hash::Writer;
45 use old_path::{Path, GenericPath};
46
47 use sys::os_str::{Buf, Slice};
48 use sys_common::{AsInner, IntoInner, FromInner};
49 use super::AsOsStr;
50
51 /// Owned, mutable OS strings.
52 #[derive(Clone)]
53 pub struct OsString {
54     inner: Buf
55 }
56
57 /// Slices into OS strings.
58 pub struct OsStr {
59     inner: Slice
60 }
61
62 impl OsString {
63     /// Constructs an `OsString` at no cost by consuming a `String`.
64     pub fn from_string(s: String) -> OsString {
65         OsString { inner: Buf::from_string(s) }
66     }
67
68     /// Constructs an `OsString` by copying from a `&str` slice.
69     ///
70     /// Equivalent to: `OsString::from_string(String::from_str(s))`.
71     pub fn from_str(s: &str) -> OsString {
72         OsString { inner: Buf::from_str(s) }
73     }
74
75     /// Constructs a new empty `OsString`.
76     pub fn new() -> OsString {
77         OsString { inner: Buf::from_string(String::new()) }
78     }
79
80     /// Convert the `OsString` into a `String` if it contains valid Unicode data.
81     ///
82     /// On failure, ownership of the original `OsString` is returned.
83     pub fn into_string(self) -> Result<String, OsString> {
84         self.inner.into_string().map_err(|buf| OsString { inner: buf} )
85     }
86
87     /// Extend the string with the given `&OsStr` slice.
88     pub fn push_os_str(&mut self, s: &OsStr) {
89         self.inner.push_slice(&s.inner)
90     }
91 }
92
93 impl ops::Index<ops::RangeFull> for OsString {
94     type Output = OsStr;
95
96     #[inline]
97     fn index(&self, _index: &ops::RangeFull) -> &OsStr {
98         unsafe { mem::transmute(self.inner.as_slice()) }
99     }
100 }
101
102 impl ops::Deref for OsString {
103     type Target = OsStr;
104
105     #[inline]
106     fn deref(&self) -> &OsStr {
107         &self[..]
108     }
109 }
110
111 impl Debug for OsString {
112     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
113         fmt::Debug::fmt(&**self, formatter)
114     }
115 }
116
117 impl PartialEq for OsString {
118     fn eq(&self, other: &OsString) -> bool {
119         &**self == &**other
120     }
121 }
122
123 impl PartialEq<str> for OsString {
124     fn eq(&self, other: &str) -> bool {
125         &**self == other
126     }
127 }
128
129 impl PartialEq<OsString> for str {
130     fn eq(&self, other: &OsString) -> bool {
131         &**other == self
132     }
133 }
134
135 impl Eq for OsString {}
136
137 impl PartialOrd for OsString {
138     #[inline]
139     fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
140         (&**self).partial_cmp(&**other)
141     }
142     #[inline]
143     fn lt(&self, other: &OsString) -> bool { &**self < &**other }
144     #[inline]
145     fn le(&self, other: &OsString) -> bool { &**self <= &**other }
146     #[inline]
147     fn gt(&self, other: &OsString) -> bool { &**self > &**other }
148     #[inline]
149     fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
150 }
151
152 impl PartialOrd<str> for OsString {
153     #[inline]
154     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
155         (&**self).partial_cmp(other)
156     }
157 }
158
159 impl Ord for OsString {
160     #[inline]
161     fn cmp(&self, other: &OsString) -> cmp::Ordering {
162         (&**self).cmp(&**other)
163     }
164 }
165
166 #[cfg(stage0)]
167 impl<'a, S: Hasher + Writer> Hash<S> for OsString {
168     #[inline]
169     fn hash(&self, state: &mut S) {
170         (&**self).hash(state)
171     }
172 }
173 #[cfg(not(stage0))]
174 #[stable(feature = "rust1", since = "1.0.0")]
175 impl Hash for OsString {
176     #[inline]
177     fn hash<H: Hasher>(&self, state: &mut H) {
178         (&**self).hash(state)
179     }
180 }
181
182 impl OsStr {
183     /// Coerce directly from a `&str` slice to a `&OsStr` slice.
184     pub fn from_str(s: &str) -> &OsStr {
185         unsafe { mem::transmute(Slice::from_str(s)) }
186     }
187
188     /// Yield a `&str` slice if the `OsStr` is valid unicode.
189     ///
190     /// This conversion may entail doing a check for UTF-8 validity.
191     pub fn to_str(&self) -> Option<&str> {
192         self.inner.to_str()
193     }
194
195     /// Convert an `OsStr` to a `CowString`.
196     ///
197     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
198     pub fn to_string_lossy(&self) -> CowString {
199         self.inner.to_string_lossy()
200     }
201
202     /// Copy the slice into an owned `OsString`.
203     pub fn to_os_string(&self) -> OsString {
204         OsString { inner: self.inner.to_owned() }
205     }
206
207     /// Get the underlying byte representation.
208     ///
209     /// Note: it is *crucial* that this API is private, to avoid
210     /// revealing the internal, platform-specific encodings.
211     fn bytes(&self) -> &[u8] {
212         unsafe { mem::transmute(&self.inner) }
213     }
214 }
215
216 impl PartialEq for OsStr {
217     fn eq(&self, other: &OsStr) -> bool {
218         self.bytes().eq(other.bytes())
219     }
220 }
221
222 impl PartialEq<str> for OsStr {
223     fn eq(&self, other: &str) -> bool {
224         *self == *OsStr::from_str(other)
225     }
226 }
227
228 impl PartialEq<OsStr> for str {
229     fn eq(&self, other: &OsStr) -> bool {
230         *other == *OsStr::from_str(self)
231     }
232 }
233
234 impl Eq for OsStr {}
235
236 impl PartialOrd for OsStr {
237     #[inline]
238     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
239         self.bytes().partial_cmp(other.bytes())
240     }
241     #[inline]
242     fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
243     #[inline]
244     fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
245     #[inline]
246     fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
247     #[inline]
248     fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
249 }
250
251 impl PartialOrd<str> for OsStr {
252     #[inline]
253     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
254         self.partial_cmp(OsStr::from_str(other))
255     }
256 }
257
258 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
259 // have more flexible coherence rules.
260
261 impl Ord for OsStr {
262     #[inline]
263     fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
264 }
265
266 #[cfg(stage0)]
267 impl<'a, S: Hasher + Writer> Hash<S> for OsStr {
268     #[inline]
269     fn hash(&self, state: &mut S) {
270         self.bytes().hash(state)
271     }
272 }
273 #[cfg(not(stage0))]
274 #[stable(feature = "rust1", since = "1.0.0")]
275 impl Hash for OsStr {
276     #[inline]
277     fn hash<H: Hasher>(&self, state: &mut H) {
278         self.bytes().hash(state)
279     }
280 }
281
282 impl Debug for OsStr {
283     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
284         self.inner.fmt(formatter)
285     }
286 }
287
288 impl Borrow<OsStr> for OsString {
289     fn borrow(&self) -> &OsStr { &self[..] }
290 }
291
292 impl ToOwned for OsStr {
293     type Owned = OsString;
294     fn to_owned(&self) -> OsString { self.to_os_string() }
295 }
296
297 impl<'a, T: AsOsStr + ?Sized> AsOsStr for &'a T {
298     fn as_os_str(&self) -> &OsStr {
299         (*self).as_os_str()
300     }
301 }
302
303 impl AsOsStr for OsStr {
304     fn as_os_str(&self) -> &OsStr {
305         self
306     }
307 }
308
309 impl AsOsStr for OsString {
310     fn as_os_str(&self) -> &OsStr {
311         &self[..]
312     }
313 }
314
315 impl AsOsStr for str {
316     fn as_os_str(&self) -> &OsStr {
317         OsStr::from_str(self)
318     }
319 }
320
321 impl AsOsStr for String {
322     fn as_os_str(&self) -> &OsStr {
323         OsStr::from_str(&self[..])
324     }
325 }
326
327 #[cfg(unix)]
328 impl AsOsStr for Path {
329     fn as_os_str(&self) -> &OsStr {
330         unsafe { mem::transmute(self.as_vec()) }
331     }
332 }
333
334 #[cfg(windows)]
335 impl AsOsStr for Path {
336     fn as_os_str(&self) -> &OsStr {
337         // currently .as_str() is actually infallible on windows
338         OsStr::from_str(self.as_str().unwrap())
339     }
340 }
341
342 impl FromInner<Buf> for OsString {
343     fn from_inner(buf: Buf) -> OsString {
344         OsString { inner: buf }
345     }
346 }
347
348 impl IntoInner<Buf> for OsString {
349     fn into_inner(self) -> Buf {
350         self.inner
351     }
352 }
353
354 impl AsInner<Slice> for OsStr {
355     fn as_inner(&self) -> &Slice {
356         &self.inner
357     }
358 }