]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/os_str.rs
Auto merge of #22517 - brson:relnotes, 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 core::borrow::{BorrowFrom, 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, Writer};
44 use old_path::{Path, GenericPath};
45
46 use sys::os_str::{Buf, Slice};
47 use sys_common::{AsInner, IntoInner, FromInner};
48 use super::AsOsStr;
49
50 /// Owned, mutable OS strings.
51 #[derive(Clone)]
52 pub struct OsString {
53     inner: Buf
54 }
55
56 /// Slices into OS strings.
57 pub struct OsStr {
58     inner: Slice
59 }
60
61 impl OsString {
62     /// Constructs an `OsString` at no cost by consuming a `String`.
63     pub fn from_string(s: String) -> OsString {
64         OsString { inner: Buf::from_string(s) }
65     }
66
67     /// Constructs an `OsString` by copying from a `&str` slice.
68     ///
69     /// Equivalent to: `OsString::from_string(String::from_str(s))`.
70     pub fn from_str(s: &str) -> OsString {
71         OsString { inner: Buf::from_str(s) }
72     }
73
74     /// Constructs a new empty `OsString`.
75     pub fn new() -> OsString {
76         OsString { inner: Buf::from_string(String::new()) }
77     }
78
79     /// Convert the `OsString` into a `String` if it contains valid Unicode data.
80     ///
81     /// On failure, ownership of the original `OsString` is returned.
82     pub fn into_string(self) -> Result<String, OsString> {
83         self.inner.into_string().map_err(|buf| OsString { inner: buf} )
84     }
85
86     /// Extend the string with the given `&OsStr` slice.
87     pub fn push_os_str(&mut self, s: &OsStr) {
88         self.inner.push_slice(&s.inner)
89     }
90 }
91
92 impl ops::Index<ops::RangeFull> for OsString {
93     type Output = OsStr;
94
95     #[inline]
96     fn index(&self, _index: &ops::RangeFull) -> &OsStr {
97         unsafe { mem::transmute(self.inner.as_slice()) }
98     }
99 }
100
101 impl ops::Deref for OsString {
102     type Target = OsStr;
103
104     #[inline]
105     fn deref(&self) -> &OsStr {
106         &self[]
107     }
108 }
109
110 impl Debug for OsString {
111     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
112         fmt::Debug::fmt(&**self, formatter)
113     }
114 }
115
116 impl PartialEq for OsString {
117     fn eq(&self, other: &OsString) -> bool {
118         &**self == &**other
119     }
120 }
121
122 impl PartialEq<str> for OsString {
123     fn eq(&self, other: &str) -> bool {
124         &**self == other
125     }
126 }
127
128 impl PartialEq<OsString> for str {
129     fn eq(&self, other: &OsString) -> bool {
130         &**other == self
131     }
132 }
133
134 impl Eq for OsString {}
135
136 impl PartialOrd for OsString {
137     #[inline]
138     fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
139         (&**self).partial_cmp(&**other)
140     }
141     #[inline]
142     fn lt(&self, other: &OsString) -> bool { &**self < &**other }
143     #[inline]
144     fn le(&self, other: &OsString) -> bool { &**self <= &**other }
145     #[inline]
146     fn gt(&self, other: &OsString) -> bool { &**self > &**other }
147     #[inline]
148     fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
149 }
150
151 impl PartialOrd<str> for OsString {
152     #[inline]
153     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
154         (&**self).partial_cmp(other)
155     }
156 }
157
158 impl Ord for OsString {
159     #[inline]
160     fn cmp(&self, other: &OsString) -> cmp::Ordering {
161         (&**self).cmp(&**other)
162     }
163 }
164
165 impl<'a, S: Hasher + Writer> Hash<S> for OsString {
166     #[inline]
167     fn hash(&self, state: &mut S) {
168         (&**self).hash(state)
169     }
170 }
171
172 impl OsStr {
173     /// Coerce directly from a `&str` slice to a `&OsStr` slice.
174     pub fn from_str(s: &str) -> &OsStr {
175         unsafe { mem::transmute(Slice::from_str(s)) }
176     }
177
178     /// Yield a `&str` slice if the `OsStr` is valid unicode.
179     ///
180     /// This conversion may entail doing a check for UTF-8 validity.
181     pub fn to_str(&self) -> Option<&str> {
182         self.inner.to_str()
183     }
184
185     /// Convert an `OsStr` to a `CowString`.
186     ///
187     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
188     pub fn to_string_lossy(&self) -> CowString {
189         self.inner.to_string_lossy()
190     }
191
192     /// Copy the slice into an owned `OsString`.
193     pub fn to_os_string(&self) -> OsString {
194         OsString { inner: self.inner.to_owned() }
195     }
196
197     /// Get the underlying byte representation.
198     ///
199     /// Note: it is *crucial* that this API is private, to avoid
200     /// revealing the internal, platform-specific encodings.
201     fn bytes(&self) -> &[u8] {
202         unsafe { mem::transmute(&self.inner) }
203     }
204 }
205
206 impl PartialEq for OsStr {
207     fn eq(&self, other: &OsStr) -> bool {
208         self.bytes().eq(other.bytes())
209     }
210 }
211
212 impl PartialEq<str> for OsStr {
213     fn eq(&self, other: &str) -> bool {
214         *self == *OsStr::from_str(other)
215     }
216 }
217
218 impl PartialEq<OsStr> for str {
219     fn eq(&self, other: &OsStr) -> bool {
220         *other == *OsStr::from_str(self)
221     }
222 }
223
224 impl Eq for OsStr {}
225
226 impl PartialOrd for OsStr {
227     #[inline]
228     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
229         self.bytes().partial_cmp(other.bytes())
230     }
231     #[inline]
232     fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
233     #[inline]
234     fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
235     #[inline]
236     fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
237     #[inline]
238     fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
239 }
240
241 impl PartialOrd<str> for OsStr {
242     #[inline]
243     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
244         self.partial_cmp(OsStr::from_str(other))
245     }
246 }
247
248 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
249 // have more flexible coherence rules.
250
251 impl Ord for OsStr {
252     #[inline]
253     fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
254 }
255
256 impl<'a, S: Hasher + Writer> Hash<S> for OsStr {
257     #[inline]
258     fn hash(&self, state: &mut S) {
259         self.bytes().hash(state)
260     }
261 }
262
263 impl Debug for OsStr {
264     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
265         self.inner.fmt(formatter)
266     }
267 }
268
269 impl BorrowFrom<OsString> for OsStr {
270     fn borrow_from(owned: &OsString) -> &OsStr { &owned[] }
271 }
272
273 impl ToOwned<OsString> for OsStr {
274     fn to_owned(&self) -> OsString { self.to_os_string() }
275 }
276
277 impl<'a, T: AsOsStr + ?Sized> AsOsStr for &'a T {
278     fn as_os_str(&self) -> &OsStr {
279         (*self).as_os_str()
280     }
281 }
282
283 impl AsOsStr for OsStr {
284     fn as_os_str(&self) -> &OsStr {
285         self
286     }
287 }
288
289 impl AsOsStr for OsString {
290     fn as_os_str(&self) -> &OsStr {
291         &self[]
292     }
293 }
294
295 impl AsOsStr for str {
296     fn as_os_str(&self) -> &OsStr {
297         OsStr::from_str(self)
298     }
299 }
300
301 impl AsOsStr for String {
302     fn as_os_str(&self) -> &OsStr {
303         OsStr::from_str(&self[])
304     }
305 }
306
307 #[cfg(unix)]
308 impl AsOsStr for Path {
309     fn as_os_str(&self) -> &OsStr {
310         unsafe { mem::transmute(self.as_vec()) }
311     }
312 }
313
314 #[cfg(windows)]
315 impl AsOsStr for Path {
316     fn as_os_str(&self) -> &OsStr {
317         // currently .as_str() is actually infallible on windows
318         OsStr::from_str(self.as_str().unwrap())
319     }
320 }
321
322 impl FromInner<Buf> for OsString {
323     fn from_inner(buf: Buf) -> OsString {
324         OsString { inner: buf }
325     }
326 }
327
328 impl IntoInner<Buf> for OsString {
329     fn into_inner(self) -> Buf {
330         self.inner
331     }
332 }
333
334 impl AsInner<Slice> for OsStr {
335     fn as_inner(&self) -> &Slice {
336         &self.inner
337     }
338 }