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, ToOwned};
12 use fmt::{self, Debug};
17 use hash::{Hash, Hasher};
20 use sys::os_str::{Buf, Slice};
21 use sys_common::{AsInner, IntoInner, FromInner};
23 /// A type that can represent owned, mutable platform-native strings, but is
24 /// cheaply inter-convertible with Rust strings.
26 /// The need for this type arises from the fact that:
28 /// * On Unix systems, strings are often arbitrary sequences of non-zero
29 /// bytes, in many cases interpreted as UTF-8.
31 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
32 /// values, interpreted as UTF-16 when it is valid to do so.
34 /// * In Rust, strings are always valid UTF-8, but may contain zeros.
36 /// `OsString` and `OsStr` bridge this gap by simultaneously representing Rust
37 /// and platform-native string values, and in particular allowing a Rust string
38 /// to be converted into an "OS" string with no cost.
40 #[stable(feature = "rust1", since = "1.0.0")]
45 /// Slices into OS strings (see `OsString`).
46 #[stable(feature = "rust1", since = "1.0.0")]
52 /// Constructs a new empty `OsString`.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub fn new() -> OsString {
55 OsString { inner: Buf::from_string(String::new()) }
59 fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
60 use os::unix::ffi::OsStringExt;
61 Some(OsString::from_vec(vec))
65 fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
66 String::from_utf8(vec).ok().map(OsString::from)
69 /// Converts to an `OsStr` slice.
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub fn as_os_str(&self) -> &OsStr {
75 /// Converts the `OsString` into a `String` if it contains valid Unicode data.
77 /// On failure, ownership of the original `OsString` is returned.
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub fn into_string(self) -> Result<String, OsString> {
80 self.inner.into_string().map_err(|buf| OsString { inner: buf} )
83 /// Extends the string with the given `&OsStr` slice.
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
86 self.inner.push_slice(&s.as_ref().inner)
89 /// Creates a new `OsString` with the given capacity.
91 /// The string will be able to hold exactly `capacity` lenth units of other
92 /// OS strings without reallocating. If `capacity` is 0, the string will not
95 /// See main `OsString` documentation information about encoding.
96 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
97 pub fn with_capacity(capacity: usize) -> OsString {
99 inner: Buf::with_capacity(capacity)
103 /// Truncates the `OsString` to zero length.
104 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
105 pub fn clear(&mut self) {
109 /// Returns the capacity this `OsString` can hold without reallocating.
111 /// See `OsString` introduction for information about encoding.
112 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
113 pub fn capacity(&self) -> usize {
114 self.inner.capacity()
117 /// Reserves capacity for at least `additional` more capacity to be inserted
118 /// in the given `OsString`.
120 /// The collection may reserve more space to avoid frequent reallocations.
121 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
122 pub fn reserve(&mut self, additional: usize) {
123 self.inner.reserve(additional)
126 /// Reserves the minimum capacity for exactly `additional` more capacity to
127 /// be inserted in the given `OsString`. Does nothing if the capacity is
128 /// already sufficient.
130 /// Note that the allocator may give the collection more space than it
131 /// requests. Therefore capacity can not be relied upon to be precisely
132 /// minimal. Prefer reserve if future insertions are expected.
133 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
134 pub fn reserve_exact(&mut self, additional: usize) {
135 self.inner.reserve_exact(additional)
139 #[stable(feature = "rust1", since = "1.0.0")]
140 impl From<String> for OsString {
141 fn from(s: String) -> OsString {
142 OsString { inner: Buf::from_string(s) }
146 #[stable(feature = "rust1", since = "1.0.0")]
147 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for OsString {
148 fn from(s: &'a T) -> OsString {
149 s.as_ref().to_os_string()
153 #[stable(feature = "rust1", since = "1.0.0")]
154 impl ops::Index<ops::RangeFull> for OsString {
158 fn index(&self, _index: ops::RangeFull) -> &OsStr {
159 OsStr::from_inner(self.inner.as_slice())
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl ops::Deref for OsString {
168 fn deref(&self) -> &OsStr {
173 #[stable(feature = "osstring_default", since = "1.9.0")]
174 impl Default for OsString {
176 fn default() -> OsString {
181 #[stable(feature = "rust1", since = "1.0.0")]
182 impl Debug for OsString {
183 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
184 fmt::Debug::fmt(&**self, formatter)
188 #[stable(feature = "rust1", since = "1.0.0")]
189 impl PartialEq for OsString {
190 fn eq(&self, other: &OsString) -> bool {
195 #[stable(feature = "rust1", since = "1.0.0")]
196 impl PartialEq<str> for OsString {
197 fn eq(&self, other: &str) -> bool {
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl PartialEq<OsString> for str {
204 fn eq(&self, other: &OsString) -> bool {
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl Eq for OsString {}
212 #[stable(feature = "rust1", since = "1.0.0")]
213 impl PartialOrd for OsString {
215 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
216 (&**self).partial_cmp(&**other)
219 fn lt(&self, other: &OsString) -> bool { &**self < &**other }
221 fn le(&self, other: &OsString) -> bool { &**self <= &**other }
223 fn gt(&self, other: &OsString) -> bool { &**self > &**other }
225 fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
228 #[stable(feature = "rust1", since = "1.0.0")]
229 impl PartialOrd<str> for OsString {
231 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
232 (&**self).partial_cmp(other)
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl Ord for OsString {
239 fn cmp(&self, other: &OsString) -> cmp::Ordering {
240 (&**self).cmp(&**other)
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl Hash for OsString {
247 fn hash<H: Hasher>(&self, state: &mut H) {
248 (&**self).hash(state)
253 /// Coerces into an `OsStr` slice.
254 #[stable(feature = "rust1", since = "1.0.0")]
255 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
259 fn from_inner(inner: &Slice) -> &OsStr {
260 unsafe { mem::transmute(inner) }
263 /// Yields a `&str` slice if the `OsStr` is valid Unicode.
265 /// This conversion may entail doing a check for UTF-8 validity.
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn to_str(&self) -> Option<&str> {
271 /// Converts an `OsStr` to a `Cow<str>`.
273 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn to_string_lossy(&self) -> Cow<str> {
276 self.inner.to_string_lossy()
279 /// Copies the slice into an owned `OsString`.
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn to_os_string(&self) -> OsString {
282 OsString { inner: self.inner.to_owned() }
285 /// Checks whether the `OsStr` is empty.
286 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
287 pub fn is_empty(&self) -> bool {
288 self.inner.inner.is_empty()
291 /// Returns the length of this `OsStr`.
293 /// Note that this does **not** return the number of bytes in this string
294 /// as, for example, OS strings on Windows are encoded as a list of `u16`
295 /// rather than a list of bytes. This number is simply useful for passing to
296 /// other methods like `OsString::with_capacity` to avoid reallocations.
298 /// See `OsStr` introduction for more information about encoding.
299 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
300 pub fn len(&self) -> usize {
301 self.inner.inner.len()
304 /// Gets the underlying byte representation.
306 /// Note: it is *crucial* that this API is private, to avoid
307 /// revealing the internal, platform-specific encodings.
308 fn bytes(&self) -> &[u8] {
309 unsafe { mem::transmute(&self.inner) }
313 #[stable(feature = "osstring_default", since = "1.9.0")]
314 impl<'a> Default for &'a OsStr {
316 fn default() -> &'a OsStr {
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl PartialEq for OsStr {
323 fn eq(&self, other: &OsStr) -> bool {
324 self.bytes().eq(other.bytes())
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl PartialEq<str> for OsStr {
330 fn eq(&self, other: &str) -> bool {
331 *self == *OsStr::new(other)
335 #[stable(feature = "rust1", since = "1.0.0")]
336 impl PartialEq<OsStr> for str {
337 fn eq(&self, other: &OsStr) -> bool {
338 *other == *OsStr::new(self)
342 #[stable(feature = "rust1", since = "1.0.0")]
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl PartialOrd for OsStr {
348 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
349 self.bytes().partial_cmp(other.bytes())
352 fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
354 fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
356 fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
358 fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl PartialOrd<str> for OsStr {
364 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
365 self.partial_cmp(OsStr::new(other))
369 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
370 // have more flexible coherence rules.
372 #[stable(feature = "rust1", since = "1.0.0")]
375 fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
378 macro_rules! impl_cmp {
379 ($lhs:ty, $rhs: ty) => {
380 #[stable(feature = "cmp_os_str", since = "1.8.0")]
381 impl<'a, 'b> PartialEq<$rhs> for $lhs {
383 fn eq(&self, other: &$rhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
386 #[stable(feature = "cmp_os_str", since = "1.8.0")]
387 impl<'a, 'b> PartialEq<$lhs> for $rhs {
389 fn eq(&self, other: &$lhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
392 #[stable(feature = "cmp_os_str", since = "1.8.0")]
393 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
395 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
396 <OsStr as PartialOrd>::partial_cmp(self, other)
400 #[stable(feature = "cmp_os_str", since = "1.8.0")]
401 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
403 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
404 <OsStr as PartialOrd>::partial_cmp(self, other)
410 impl_cmp!(OsString, OsStr);
411 impl_cmp!(OsString, &'a OsStr);
412 impl_cmp!(Cow<'a, OsStr>, OsStr);
413 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
414 impl_cmp!(Cow<'a, OsStr>, OsString);
416 #[stable(feature = "rust1", since = "1.0.0")]
417 impl Hash for OsStr {
419 fn hash<H: Hasher>(&self, state: &mut H) {
420 self.bytes().hash(state)
424 #[stable(feature = "rust1", since = "1.0.0")]
425 impl Debug for OsStr {
426 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
427 self.inner.fmt(formatter)
431 #[stable(feature = "rust1", since = "1.0.0")]
432 impl Borrow<OsStr> for OsString {
433 fn borrow(&self) -> &OsStr { &self[..] }
436 #[stable(feature = "rust1", since = "1.0.0")]
437 impl ToOwned for OsStr {
438 type Owned = OsString;
439 fn to_owned(&self) -> OsString { self.to_os_string() }
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl AsRef<OsStr> for OsStr {
444 fn as_ref(&self) -> &OsStr {
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl AsRef<OsStr> for OsString {
451 fn as_ref(&self) -> &OsStr {
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl AsRef<OsStr> for str {
458 fn as_ref(&self) -> &OsStr {
459 OsStr::from_inner(Slice::from_str(self))
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl AsRef<OsStr> for String {
465 fn as_ref(&self) -> &OsStr {
470 impl FromInner<Buf> for OsString {
471 fn from_inner(buf: Buf) -> OsString {
472 OsString { inner: buf }
476 impl IntoInner<Buf> for OsString {
477 fn into_inner(self) -> Buf {
482 impl AsInner<Slice> for OsStr {
483 fn as_inner(&self) -> &Slice {
491 use sys_common::{AsInner, IntoInner};
494 fn test_os_string_with_capacity() {
495 let os_string = OsString::with_capacity(0);
496 assert_eq!(0, os_string.inner.into_inner().capacity());
498 let os_string = OsString::with_capacity(10);
499 assert_eq!(10, os_string.inner.into_inner().capacity());
501 let mut os_string = OsString::with_capacity(0);
502 os_string.push("abc");
503 assert!(os_string.inner.into_inner().capacity() >= 3);
507 fn test_os_string_clear() {
508 let mut os_string = OsString::from("abc");
509 assert_eq!(3, os_string.inner.as_inner().len());
512 assert_eq!(&os_string, "");
513 assert_eq!(0, os_string.inner.as_inner().len());
517 fn test_os_string_capacity() {
518 let os_string = OsString::with_capacity(0);
519 assert_eq!(0, os_string.capacity());
521 let os_string = OsString::with_capacity(10);
522 assert_eq!(10, os_string.capacity());
524 let mut os_string = OsString::with_capacity(0);
525 os_string.push("abc");
526 assert!(os_string.capacity() >= 3);
530 fn test_os_string_reserve() {
531 let mut os_string = OsString::new();
532 assert_eq!(os_string.capacity(), 0);
534 os_string.reserve(2);
535 assert!(os_string.capacity() >= 2);
541 assert!(os_string.capacity() >= 16);
542 os_string.reserve(16);
543 assert!(os_string.capacity() >= 32);
547 os_string.reserve(16);
548 assert!(os_string.capacity() >= 33)
552 fn test_os_string_reserve_exact() {
553 let mut os_string = OsString::new();
554 assert_eq!(os_string.capacity(), 0);
556 os_string.reserve_exact(2);
557 assert!(os_string.capacity() >= 2);
563 assert!(os_string.capacity() >= 16);
564 os_string.reserve_exact(16);
565 assert!(os_string.capacity() >= 32);
569 os_string.reserve_exact(16);
570 assert!(os_string.capacity() >= 33)
574 fn test_os_string_default() {
575 let os_string: OsString = Default::default();
576 assert_eq!("", &os_string);
580 fn test_os_str_is_empty() {
581 let mut os_string = OsString::new();
582 assert!(os_string.is_empty());
584 os_string.push("abc");
585 assert!(!os_string.is_empty());
588 assert!(os_string.is_empty());
592 fn test_os_str_len() {
593 let mut os_string = OsString::new();
594 assert_eq!(0, os_string.len());
596 os_string.push("abc");
597 assert_eq!(3, os_string.len());
600 assert_eq!(0, os_string.len());
604 fn test_os_str_default() {
605 let os_str: &OsStr = Default::default();
606 assert_eq!("", os_str);