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 //! A type that can represent all platform-native strings, but is cheaply
12 //! interconvertable with Rust strings.
14 //! The need for this type arises from the fact that:
16 //! * On Unix systems, strings are often arbitrary sequences of non-zero
17 //! bytes, in many cases interpreted as UTF-8.
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.
22 //! * In Rust, strings are always valid UTF-8, but may contain zeros.
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.
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.
32 #![unstable(feature = "os",
33 reason = "recently added as part of path/io reform")]
37 use core::borrow::{BorrowFrom, ToOwned};
38 use fmt::{self, Debug};
40 use string::{String, CowString};
43 use hash::{Hash, Hasher, Writer};
44 use old_path::{Path, GenericPath};
46 use sys::os_str::{Buf, Slice};
47 use sys_common::{AsInner, IntoInner, FromInner};
50 /// Owned, mutable OS strings.
56 /// Slices into OS strings.
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) }
67 /// Constructs an `OsString` by copying from a `&str` slice.
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) }
74 /// Constructs a new empty `OsString`.
75 pub fn new() -> OsString {
76 OsString { inner: Buf::from_string(String::new()) }
79 /// Convert the `OsString` into a `String` if it contains valid Unicode data.
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} )
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)
92 impl ops::Index<ops::RangeFull> for OsString {
96 fn index(&self, _index: &ops::RangeFull) -> &OsStr {
97 unsafe { mem::transmute(self.inner.as_slice()) }
101 impl ops::Deref for OsString {
105 fn deref(&self) -> &OsStr {
110 impl Debug for OsString {
111 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
112 fmt::Debug::fmt(&**self, formatter)
116 impl PartialEq for OsString {
117 fn eq(&self, other: &OsString) -> bool {
122 impl PartialEq<str> for OsString {
123 fn eq(&self, other: &str) -> bool {
128 impl PartialEq<OsString> for str {
129 fn eq(&self, other: &OsString) -> bool {
134 impl Eq for OsString {}
136 impl PartialOrd for OsString {
138 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
139 (&**self).partial_cmp(&**other)
142 fn lt(&self, other: &OsString) -> bool { &**self < &**other }
144 fn le(&self, other: &OsString) -> bool { &**self <= &**other }
146 fn gt(&self, other: &OsString) -> bool { &**self > &**other }
148 fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
151 impl PartialOrd<str> for OsString {
153 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
154 (&**self).partial_cmp(other)
158 impl Ord for OsString {
160 fn cmp(&self, other: &OsString) -> cmp::Ordering {
161 (&**self).cmp(&**other)
165 impl<'a, S: Hasher + Writer> Hash<S> for OsString {
167 fn hash(&self, state: &mut S) {
168 (&**self).hash(state)
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)) }
178 /// Yield a `&str` slice if the `OsStr` is valid unicode.
180 /// This conversion may entail doing a check for UTF-8 validity.
181 pub fn to_str(&self) -> Option<&str> {
185 /// Convert an `OsStr` to a `CowString`.
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()
192 /// Copy the slice into an owned `OsString`.
193 pub fn to_os_string(&self) -> OsString {
194 OsString { inner: self.inner.to_owned() }
197 /// Get the underlying byte representation.
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) }
206 impl PartialEq for OsStr {
207 fn eq(&self, other: &OsStr) -> bool {
208 self.bytes().eq(other.bytes())
212 impl PartialEq<str> for OsStr {
213 fn eq(&self, other: &str) -> bool {
214 *self == *OsStr::from_str(other)
218 impl PartialEq<OsStr> for str {
219 fn eq(&self, other: &OsStr) -> bool {
220 *other == *OsStr::from_str(self)
226 impl PartialOrd for OsStr {
228 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
229 self.bytes().partial_cmp(other.bytes())
232 fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
234 fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
236 fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
238 fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
241 impl PartialOrd<str> for OsStr {
243 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
244 self.partial_cmp(OsStr::from_str(other))
248 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
249 // have more flexible coherence rules.
253 fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
256 impl<'a, S: Hasher + Writer> Hash<S> for OsStr {
258 fn hash(&self, state: &mut S) {
259 self.bytes().hash(state)
263 impl Debug for OsStr {
264 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
265 self.inner.fmt(formatter)
269 impl BorrowFrom<OsString> for OsStr {
270 fn borrow_from(owned: &OsString) -> &OsStr { &owned[] }
273 impl ToOwned<OsString> for OsStr {
274 fn to_owned(&self) -> OsString { self.to_os_string() }
277 impl<'a, T: AsOsStr + ?Sized> AsOsStr for &'a T {
278 fn as_os_str(&self) -> &OsStr {
283 impl AsOsStr for OsStr {
284 fn as_os_str(&self) -> &OsStr {
289 impl AsOsStr for OsString {
290 fn as_os_str(&self) -> &OsStr {
295 impl AsOsStr for str {
296 fn as_os_str(&self) -> &OsStr {
297 OsStr::from_str(self)
301 impl AsOsStr for String {
302 fn as_os_str(&self) -> &OsStr {
303 OsStr::from_str(&self[])
308 impl AsOsStr for Path {
309 fn as_os_str(&self) -> &OsStr {
310 unsafe { mem::transmute(self.as_vec()) }
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())
322 impl FromInner<Buf> for OsString {
323 fn from_inner(buf: Buf) -> OsString {
324 OsString { inner: buf }
328 impl IntoInner<Buf> for OsString {
329 fn into_inner(self) -> Buf {
334 impl AsInner<Slice> for OsStr {
335 fn as_inner(&self) -> &Slice {