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 use borrow::{Borrow, Cow};
12 use fmt::{self, Debug};
16 use hash::{Hash, Hasher};
18 use sys::os_str::{Buf, Slice};
19 use sys_common::{AsInner, IntoInner, FromInner};
21 /// A type that can represent owned, mutable platform-native strings, but is
22 /// cheaply inter-convertible with Rust strings.
24 /// The need for this type arises from the fact that:
26 /// * On Unix systems, strings are often arbitrary sequences of non-zero
27 /// bytes, in many cases interpreted as UTF-8.
29 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
30 /// values, interpreted as UTF-16 when it is valid to do so.
32 /// * In Rust, strings are always valid UTF-8, but may contain zeros.
34 /// `OsString` and `OsStr` bridge this gap by simultaneously representing Rust
35 /// and platform-native string values, and in particular allowing a Rust string
36 /// to be converted into an "OS" string with no cost.
38 #[stable(feature = "rust1", since = "1.0.0")]
43 /// Slices into OS strings (see `OsString`).
44 #[stable(feature = "rust1", since = "1.0.0")]
50 /// Constructs a new empty `OsString`.
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub fn new() -> OsString {
53 OsString { inner: Buf::from_string(String::new()) }
57 fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
58 use os::unix::ffi::OsStringExt;
59 Some(OsString::from_vec(vec))
63 fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
64 String::from_utf8(vec).ok().map(OsString::from)
67 /// Converts to an `OsStr` slice.
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub fn as_os_str(&self) -> &OsStr {
73 /// Converts the `OsString` into a `String` if it contains valid Unicode data.
75 /// On failure, ownership of the original `OsString` is returned.
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub fn into_string(self) -> Result<String, OsString> {
78 self.inner.into_string().map_err(|buf| OsString { inner: buf} )
81 /// Extends the string with the given `&OsStr` slice.
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
84 self.inner.push_slice(&s.as_ref().inner)
87 /// Creates a new `OsString` with the given capacity.
89 /// The string will be able to hold exactly `capacity` lenth units of other
90 /// OS strings without reallocating. If `capacity` is 0, the string will not
93 /// See main `OsString` documentation information about encoding.
94 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
95 pub fn with_capacity(capacity: usize) -> OsString {
97 inner: Buf::with_capacity(capacity)
101 /// Truncates the `OsString` to zero length.
102 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
103 pub fn clear(&mut self) {
107 /// Returns the capacity this `OsString` can hold without reallocating.
109 /// See `OsString` introduction for information about encoding.
110 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
111 pub fn capacity(&self) -> usize {
112 self.inner.capacity()
115 /// Reserves capacity for at least `additional` more capacity to be inserted
116 /// in the given `OsString`.
118 /// The collection may reserve more space to avoid frequent reallocations.
119 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
120 pub fn reserve(&mut self, additional: usize) {
121 self.inner.reserve(additional)
124 /// Reserves the minimum capacity for exactly `additional` more capacity to
125 /// be inserted in the given `OsString`. Does nothing if the capacity is
126 /// already sufficient.
128 /// Note that the allocator may give the collection more space than it
129 /// requests. Therefore capacity can not be relied upon to be precisely
130 /// minimal. Prefer reserve if future insertions are expected.
131 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
132 pub fn reserve_exact(&mut self, additional: usize) {
133 self.inner.reserve_exact(additional)
137 #[stable(feature = "rust1", since = "1.0.0")]
138 impl From<String> for OsString {
139 fn from(s: String) -> OsString {
140 OsString { inner: Buf::from_string(s) }
144 #[stable(feature = "rust1", since = "1.0.0")]
145 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for OsString {
146 fn from(s: &'a T) -> OsString {
147 s.as_ref().to_os_string()
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl ops::Index<ops::RangeFull> for OsString {
156 fn index(&self, _index: ops::RangeFull) -> &OsStr {
157 OsStr::from_inner(self.inner.as_slice())
161 #[stable(feature = "rust1", since = "1.0.0")]
162 impl ops::Deref for OsString {
166 fn deref(&self) -> &OsStr {
171 #[stable(feature = "osstring_default", since = "1.9.0")]
172 impl Default for OsString {
174 fn default() -> OsString {
179 #[stable(feature = "rust1", since = "1.0.0")]
180 impl Debug for OsString {
181 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
182 fmt::Debug::fmt(&**self, formatter)
186 #[stable(feature = "rust1", since = "1.0.0")]
187 impl PartialEq for OsString {
188 fn eq(&self, other: &OsString) -> bool {
193 #[stable(feature = "rust1", since = "1.0.0")]
194 impl PartialEq<str> for OsString {
195 fn eq(&self, other: &str) -> bool {
200 #[stable(feature = "rust1", since = "1.0.0")]
201 impl PartialEq<OsString> for str {
202 fn eq(&self, other: &OsString) -> bool {
207 #[stable(feature = "rust1", since = "1.0.0")]
208 impl Eq for OsString {}
210 #[stable(feature = "rust1", since = "1.0.0")]
211 impl PartialOrd for OsString {
213 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
214 (&**self).partial_cmp(&**other)
217 fn lt(&self, other: &OsString) -> bool { &**self < &**other }
219 fn le(&self, other: &OsString) -> bool { &**self <= &**other }
221 fn gt(&self, other: &OsString) -> bool { &**self > &**other }
223 fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl PartialOrd<str> for OsString {
229 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
230 (&**self).partial_cmp(other)
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl Ord for OsString {
237 fn cmp(&self, other: &OsString) -> cmp::Ordering {
238 (&**self).cmp(&**other)
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl Hash for OsString {
245 fn hash<H: Hasher>(&self, state: &mut H) {
246 (&**self).hash(state)
251 /// Coerces into an `OsStr` slice.
256 /// use std::ffi::OsStr;
258 /// let os_str = OsStr::new("foo");
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
265 fn from_inner(inner: &Slice) -> &OsStr {
266 unsafe { mem::transmute(inner) }
269 /// Yields a `&str` slice if the `OsStr` is valid Unicode.
271 /// This conversion may entail doing a check for UTF-8 validity.
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub fn to_str(&self) -> Option<&str> {
277 /// Converts an `OsStr` to a `Cow<str>`.
279 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn to_string_lossy(&self) -> Cow<str> {
282 self.inner.to_string_lossy()
285 /// Copies the slice into an owned `OsString`.
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn to_os_string(&self) -> OsString {
288 OsString { inner: self.inner.to_owned() }
291 /// Checks whether the `OsStr` is empty.
296 /// use std::ffi::OsStr;
298 /// let os_str = OsStr::new("");
299 /// assert!(os_str.is_empty());
301 /// let os_str = OsStr::new("foo");
302 /// assert!(!os_str.is_empty());
304 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
305 pub fn is_empty(&self) -> bool {
306 self.inner.inner.is_empty()
309 /// Returns the length of this `OsStr`.
311 /// Note that this does **not** return the number of bytes in this string
312 /// as, for example, OS strings on Windows are encoded as a list of `u16`
313 /// rather than a list of bytes. This number is simply useful for passing to
314 /// other methods like `OsString::with_capacity` to avoid reallocations.
316 /// See `OsStr` introduction for more information about encoding.
321 /// use std::ffi::OsStr;
323 /// let os_str = OsStr::new("");
324 /// assert_eq!(os_str.len(), 0);
326 /// let os_str = OsStr::new("foo");
327 /// assert_eq!(os_str.len(), 3);
329 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
330 pub fn len(&self) -> usize {
331 self.inner.inner.len()
334 /// Gets the underlying byte representation.
336 /// Note: it is *crucial* that this API is private, to avoid
337 /// revealing the internal, platform-specific encodings.
338 fn bytes(&self) -> &[u8] {
339 unsafe { mem::transmute(&self.inner) }
343 #[stable(feature = "osstring_default", since = "1.9.0")]
344 impl<'a> Default for &'a OsStr {
346 fn default() -> &'a OsStr {
351 #[stable(feature = "rust1", since = "1.0.0")]
352 impl PartialEq for OsStr {
353 fn eq(&self, other: &OsStr) -> bool {
354 self.bytes().eq(other.bytes())
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl PartialEq<str> for OsStr {
360 fn eq(&self, other: &str) -> bool {
361 *self == *OsStr::new(other)
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl PartialEq<OsStr> for str {
367 fn eq(&self, other: &OsStr) -> bool {
368 *other == *OsStr::new(self)
372 #[stable(feature = "rust1", since = "1.0.0")]
375 #[stable(feature = "rust1", since = "1.0.0")]
376 impl PartialOrd for OsStr {
378 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
379 self.bytes().partial_cmp(other.bytes())
382 fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
384 fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
386 fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
388 fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
391 #[stable(feature = "rust1", since = "1.0.0")]
392 impl PartialOrd<str> for OsStr {
394 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
395 self.partial_cmp(OsStr::new(other))
399 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
400 // have more flexible coherence rules.
402 #[stable(feature = "rust1", since = "1.0.0")]
405 fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
408 macro_rules! impl_cmp {
409 ($lhs:ty, $rhs: ty) => {
410 #[stable(feature = "cmp_os_str", since = "1.8.0")]
411 impl<'a, 'b> PartialEq<$rhs> for $lhs {
413 fn eq(&self, other: &$rhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
416 #[stable(feature = "cmp_os_str", since = "1.8.0")]
417 impl<'a, 'b> PartialEq<$lhs> for $rhs {
419 fn eq(&self, other: &$lhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
422 #[stable(feature = "cmp_os_str", since = "1.8.0")]
423 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
425 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
426 <OsStr as PartialOrd>::partial_cmp(self, other)
430 #[stable(feature = "cmp_os_str", since = "1.8.0")]
431 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
433 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
434 <OsStr as PartialOrd>::partial_cmp(self, other)
440 impl_cmp!(OsString, OsStr);
441 impl_cmp!(OsString, &'a OsStr);
442 impl_cmp!(Cow<'a, OsStr>, OsStr);
443 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
444 impl_cmp!(Cow<'a, OsStr>, OsString);
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl Hash for OsStr {
449 fn hash<H: Hasher>(&self, state: &mut H) {
450 self.bytes().hash(state)
454 #[stable(feature = "rust1", since = "1.0.0")]
455 impl Debug for OsStr {
456 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
457 self.inner.fmt(formatter)
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl Borrow<OsStr> for OsString {
463 fn borrow(&self) -> &OsStr { &self[..] }
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl ToOwned for OsStr {
468 type Owned = OsString;
469 fn to_owned(&self) -> OsString { self.to_os_string() }
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl AsRef<OsStr> for OsStr {
474 fn as_ref(&self) -> &OsStr {
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl AsRef<OsStr> for OsString {
481 fn as_ref(&self) -> &OsStr {
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl AsRef<OsStr> for str {
488 fn as_ref(&self) -> &OsStr {
489 OsStr::from_inner(Slice::from_str(self))
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl AsRef<OsStr> for String {
495 fn as_ref(&self) -> &OsStr {
500 impl FromInner<Buf> for OsString {
501 fn from_inner(buf: Buf) -> OsString {
502 OsString { inner: buf }
506 impl IntoInner<Buf> for OsString {
507 fn into_inner(self) -> Buf {
512 impl AsInner<Slice> for OsStr {
513 fn as_inner(&self) -> &Slice {
521 use sys_common::{AsInner, IntoInner};
524 fn test_os_string_with_capacity() {
525 let os_string = OsString::with_capacity(0);
526 assert_eq!(0, os_string.inner.into_inner().capacity());
528 let os_string = OsString::with_capacity(10);
529 assert_eq!(10, os_string.inner.into_inner().capacity());
531 let mut os_string = OsString::with_capacity(0);
532 os_string.push("abc");
533 assert!(os_string.inner.into_inner().capacity() >= 3);
537 fn test_os_string_clear() {
538 let mut os_string = OsString::from("abc");
539 assert_eq!(3, os_string.inner.as_inner().len());
542 assert_eq!(&os_string, "");
543 assert_eq!(0, os_string.inner.as_inner().len());
547 fn test_os_string_capacity() {
548 let os_string = OsString::with_capacity(0);
549 assert_eq!(0, os_string.capacity());
551 let os_string = OsString::with_capacity(10);
552 assert_eq!(10, os_string.capacity());
554 let mut os_string = OsString::with_capacity(0);
555 os_string.push("abc");
556 assert!(os_string.capacity() >= 3);
560 fn test_os_string_reserve() {
561 let mut os_string = OsString::new();
562 assert_eq!(os_string.capacity(), 0);
564 os_string.reserve(2);
565 assert!(os_string.capacity() >= 2);
571 assert!(os_string.capacity() >= 16);
572 os_string.reserve(16);
573 assert!(os_string.capacity() >= 32);
577 os_string.reserve(16);
578 assert!(os_string.capacity() >= 33)
582 fn test_os_string_reserve_exact() {
583 let mut os_string = OsString::new();
584 assert_eq!(os_string.capacity(), 0);
586 os_string.reserve_exact(2);
587 assert!(os_string.capacity() >= 2);
593 assert!(os_string.capacity() >= 16);
594 os_string.reserve_exact(16);
595 assert!(os_string.capacity() >= 32);
599 os_string.reserve_exact(16);
600 assert!(os_string.capacity() >= 33)
604 fn test_os_string_default() {
605 let os_string: OsString = Default::default();
606 assert_eq!("", &os_string);
610 fn test_os_str_is_empty() {
611 let mut os_string = OsString::new();
612 assert!(os_string.is_empty());
614 os_string.push("abc");
615 assert!(!os_string.is_empty());
618 assert!(os_string.is_empty());
622 fn test_os_str_len() {
623 let mut os_string = OsString::new();
624 assert_eq!(0, os_string.len());
626 os_string.push("abc");
627 assert_eq!(3, os_string.len());
630 assert_eq!(0, os_string.len());
634 fn test_os_str_default() {
635 let os_str: &OsStr = Default::default();
636 assert_eq!("", os_str);