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};
15 use hash::{Hash, Hasher};
19 use sys::os_str::{Buf, Slice};
20 use sys_common::{AsInner, IntoInner, FromInner};
22 /// A type that can represent owned, mutable platform-native strings, but is
23 /// cheaply inter-convertible with Rust strings.
25 /// The need for this type arises from the fact that:
27 /// * On Unix systems, strings are often arbitrary sequences of non-zero
28 /// bytes, in many cases interpreted as UTF-8.
30 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
31 /// values, interpreted as UTF-16 when it is valid to do so.
33 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
35 /// `OsString` and [`OsStr`] bridge this gap by simultaneously representing Rust
36 /// and platform-native string values, and in particular allowing a Rust string
37 /// to be converted into an "OS" string with no cost if possible. A consequence
38 /// of this is that `OsString` instances are *not* `NUL` terminated; in order
39 /// to pass to e.g. Unix system call, you should create a [`CStr`].
41 /// `OsString` is to [`&OsStr`] as [`String`] is to [`&str`]: the former
42 /// in each pair are owned strings; the latter are borrowed
45 /// Note, `OsString` and `OsStr` internally do not necessarily hold strings in
46 /// the form native to the platform; While on Unix, strings are stored as a
47 /// sequence of 8-bit values, on Windows, where strings are 16-bit value based
48 /// as just discussed, strings are also actually stored as a sequence of 8-bit
49 /// values, encoded in a less-strict variant of UTF-8. This is useful to
50 /// understand when handling capacity and length values.
52 /// # Creating an `OsString`
54 /// **From a Rust string**: `OsString` implements
55 /// [`From`]`<`[`String`]`>`, so you can use `my_string.from` to
56 /// create an `OsString` from a normal Rust string.
58 /// **From slices:** Just like you can start with an empty Rust
59 /// [`String`] and then [`push_str`][String.push_str] `&str`
60 /// sub-string slices into it, you can create an empty `OsString` with
61 /// the [`new`] method and then push string slices into it with the
64 /// # Extracting a borrowed reference to the whole OS string
66 /// You can use the [`as_os_str`] method to get an `&`[`OsStr`] from
67 /// an `OsString`; this is effectively a borrowed reference to the
72 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
73 /// the traits which `OsString` implements for [conversions] from/to native representations.
75 /// [`OsStr`]: struct.OsStr.html
76 /// [`&OsStr`]: struct.OsStr.html
77 /// [`CStr`]: struct.CStr.html
78 /// [`From`]: ../convert/trait.From.html
79 /// [`String`]: ../string/struct.String.html
80 /// [`&str`]: ../primitive.str.html
81 /// [`u8`]: ../primitive.u8.html
82 /// [`u16`]: ../primitive.u16.html
83 /// [String.push_str]: ../string/struct.String.html#method.push_str
84 /// [`new`]: #method.new
85 /// [`push`]: #method.push
86 /// [`as_os_str`]: #method.as_os_str
87 /// [conversions]: index.html#conversions
89 #[stable(feature = "rust1", since = "1.0.0")]
94 /// Borrowed reference to an OS string (see [`OsString`]).
96 /// This type represents a borrowed reference to a string in the operating system's preferred
99 /// `&OsStr` is to [`OsString`] as [`&str`] is to [`String`]: the former in each pair are borrowed
100 /// references; the latter are owned strings.
102 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
103 /// the traits which `OsStr` implements for [conversions] from/to native representations.
105 /// [`OsString`]: struct.OsString.html
106 /// [`&str`]: ../primitive.str.html
107 /// [`String`]: ../string/struct.String.html
108 /// [conversions]: index.html#conversions
109 #[stable(feature = "rust1", since = "1.0.0")]
115 /// Constructs a new empty `OsString`.
120 /// use std::ffi::OsString;
122 /// let os_string = OsString::new();
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub fn new() -> OsString {
126 OsString { inner: Buf::from_string(String::new()) }
129 /// Converts to an [`OsStr`] slice.
131 /// [`OsStr`]: struct.OsStr.html
136 /// use std::ffi::{OsString, OsStr};
138 /// let os_string = OsString::from("foo");
139 /// let os_str = OsStr::new("foo");
140 /// assert_eq!(os_string.as_os_str(), os_str);
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub fn as_os_str(&self) -> &OsStr {
147 /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
149 /// On failure, ownership of the original `OsString` is returned.
151 /// [`String`]: ../../std/string/struct.String.html
156 /// use std::ffi::OsString;
158 /// let os_string = OsString::from("foo");
159 /// let string = os_string.into_string();
160 /// assert_eq!(string, Ok(String::from("foo")));
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn into_string(self) -> Result<String, OsString> {
164 self.inner.into_string().map_err(|buf| OsString { inner: buf} )
167 /// Extends the string with the given [`&OsStr`] slice.
169 /// [`&OsStr`]: struct.OsStr.html
174 /// use std::ffi::OsString;
176 /// let mut os_string = OsString::from("foo");
177 /// os_string.push("bar");
178 /// assert_eq!(&os_string, "foobar");
180 #[stable(feature = "rust1", since = "1.0.0")]
181 pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
182 self.inner.push_slice(&s.as_ref().inner)
185 /// Creates a new `OsString` with the given capacity.
187 /// The string will be able to hold exactly `capacity` length units of other
188 /// OS strings without reallocating. If `capacity` is 0, the string will not
191 /// See main `OsString` documentation information about encoding.
196 /// use std::ffi::OsString;
198 /// let mut os_string = OsString::with_capacity(10);
199 /// let capacity = os_string.capacity();
201 /// // This push is done without reallocating
202 /// os_string.push("foo");
204 /// assert_eq!(capacity, os_string.capacity());
206 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
207 pub fn with_capacity(capacity: usize) -> OsString {
209 inner: Buf::with_capacity(capacity)
213 /// Truncates the `OsString` to zero length.
218 /// use std::ffi::OsString;
220 /// let mut os_string = OsString::from("foo");
221 /// assert_eq!(&os_string, "foo");
223 /// os_string.clear();
224 /// assert_eq!(&os_string, "");
226 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
227 pub fn clear(&mut self) {
231 /// Returns the capacity this `OsString` can hold without reallocating.
233 /// See `OsString` introduction for information about encoding.
238 /// use std::ffi::OsString;
240 /// let mut os_string = OsString::with_capacity(10);
241 /// assert!(os_string.capacity() >= 10);
243 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
244 pub fn capacity(&self) -> usize {
245 self.inner.capacity()
248 /// Reserves capacity for at least `additional` more capacity to be inserted
249 /// in the given `OsString`.
251 /// The collection may reserve more space to avoid frequent reallocations.
256 /// use std::ffi::OsString;
258 /// let mut s = OsString::new();
260 /// assert!(s.capacity() >= 10);
262 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
263 pub fn reserve(&mut self, additional: usize) {
264 self.inner.reserve(additional)
267 /// Reserves the minimum capacity for exactly `additional` more capacity to
268 /// be inserted in the given `OsString`. Does nothing if the capacity is
269 /// already sufficient.
271 /// Note that the allocator may give the collection more space than it
272 /// requests. Therefore capacity can not be relied upon to be precisely
273 /// minimal. Prefer reserve if future insertions are expected.
278 /// use std::ffi::OsString;
280 /// let mut s = OsString::new();
281 /// s.reserve_exact(10);
282 /// assert!(s.capacity() >= 10);
284 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
285 pub fn reserve_exact(&mut self, additional: usize) {
286 self.inner.reserve_exact(additional)
289 /// Shrinks the capacity of the `OsString` to match its length.
294 /// use std::ffi::OsString;
296 /// let mut s = OsString::from("foo");
299 /// assert!(s.capacity() >= 100);
301 /// s.shrink_to_fit();
302 /// assert_eq!(3, s.capacity());
304 #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
305 pub fn shrink_to_fit(&mut self) {
306 self.inner.shrink_to_fit()
309 /// Shrinks the capacity of the `OsString` with a lower bound.
311 /// The capacity will remain at least as large as both the length
312 /// and the supplied value.
314 /// Panics if the current capacity is smaller than the supplied
315 /// minimum capacity.
320 /// #![feature(shrink_to)]
321 /// use std::ffi::OsString;
323 /// let mut s = OsString::from("foo");
326 /// assert!(s.capacity() >= 100);
329 /// assert!(s.capacity() >= 10);
331 /// assert!(s.capacity() >= 3);
334 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
335 pub fn shrink_to(&mut self, min_capacity: usize) {
336 self.inner.shrink_to(min_capacity)
339 /// Converts this `OsString` into a boxed [`OsStr`].
341 /// [`OsStr`]: struct.OsStr.html
346 /// use std::ffi::{OsString, OsStr};
348 /// let s = OsString::from("hello");
350 /// let b: Box<OsStr> = s.into_boxed_os_str();
352 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
353 pub fn into_boxed_os_str(self) -> Box<OsStr> {
354 let rw = Box::into_raw(self.inner.into_box()) as *mut OsStr;
355 unsafe { Box::from_raw(rw) }
359 #[stable(feature = "rust1", since = "1.0.0")]
360 impl From<String> for OsString {
361 /// Converts a [`String`] into a [`OsString`].
363 /// The conversion copies the data, and includes an allocation on the heap.
364 fn from(s: String) -> OsString {
365 OsString { inner: Buf::from_string(s) }
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for OsString {
371 fn from(s: &'a T) -> OsString {
372 s.as_ref().to_os_string()
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl ops::Index<ops::RangeFull> for OsString {
381 fn index(&self, _index: ops::RangeFull) -> &OsStr {
382 OsStr::from_inner(self.inner.as_slice())
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl ops::Deref for OsString {
391 fn deref(&self) -> &OsStr {
396 #[stable(feature = "osstring_default", since = "1.9.0")]
397 impl Default for OsString {
398 /// Constructs an empty `OsString`.
400 fn default() -> OsString {
405 #[stable(feature = "rust1", since = "1.0.0")]
406 impl fmt::Debug for OsString {
407 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
408 fmt::Debug::fmt(&**self, formatter)
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl PartialEq for OsString {
414 fn eq(&self, other: &OsString) -> bool {
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl PartialEq<str> for OsString {
421 fn eq(&self, other: &str) -> bool {
426 #[stable(feature = "rust1", since = "1.0.0")]
427 impl PartialEq<OsString> for str {
428 fn eq(&self, other: &OsString) -> bool {
433 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
434 impl<'a> PartialEq<&'a str> for OsString {
435 fn eq(&self, other: &&'a str) -> bool {
440 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
441 impl<'a> PartialEq<OsString> for &'a str {
442 fn eq(&self, other: &OsString) -> bool {
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl Eq for OsString {}
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl PartialOrd for OsString {
453 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
454 (&**self).partial_cmp(&**other)
457 fn lt(&self, other: &OsString) -> bool { &**self < &**other }
459 fn le(&self, other: &OsString) -> bool { &**self <= &**other }
461 fn gt(&self, other: &OsString) -> bool { &**self > &**other }
463 fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl PartialOrd<str> for OsString {
469 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
470 (&**self).partial_cmp(other)
474 #[stable(feature = "rust1", since = "1.0.0")]
475 impl Ord for OsString {
477 fn cmp(&self, other: &OsString) -> cmp::Ordering {
478 (&**self).cmp(&**other)
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl Hash for OsString {
485 fn hash<H: Hasher>(&self, state: &mut H) {
486 (&**self).hash(state)
491 /// Coerces into an `OsStr` slice.
496 /// use std::ffi::OsStr;
498 /// let os_str = OsStr::new("foo");
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
505 fn from_inner(inner: &Slice) -> &OsStr {
506 unsafe { &*(inner as *const Slice as *const OsStr) }
509 /// Yields a [`&str`] slice if the `OsStr` is valid Unicode.
511 /// This conversion may entail doing a check for UTF-8 validity.
513 /// [`&str`]: ../../std/primitive.str.html
518 /// use std::ffi::OsStr;
520 /// let os_str = OsStr::new("foo");
521 /// assert_eq!(os_str.to_str(), Some("foo"));
523 #[stable(feature = "rust1", since = "1.0.0")]
524 pub fn to_str(&self) -> Option<&str> {
528 /// Converts an `OsStr` to a [`Cow`]`<`[`str`]`>`.
530 /// Any non-Unicode sequences are replaced with
531 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
533 /// [`Cow`]: ../../std/borrow/enum.Cow.html
534 /// [`str`]: ../../std/primitive.str.html
535 /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
539 /// Calling `to_string_lossy` on an `OsStr` with valid unicode:
542 /// use std::ffi::OsStr;
544 /// let os_str = OsStr::new("foo");
545 /// assert_eq!(os_str.to_string_lossy(), "foo");
548 /// Had `os_str` contained invalid unicode, the `to_string_lossy` call might
549 /// have returned `"fo�"`.
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn to_string_lossy(&self) -> Cow<str> {
552 self.inner.to_string_lossy()
555 /// Copies the slice into an owned [`OsString`].
557 /// [`OsString`]: struct.OsString.html
562 /// use std::ffi::{OsStr, OsString};
564 /// let os_str = OsStr::new("foo");
565 /// let os_string = os_str.to_os_string();
566 /// assert_eq!(os_string, OsString::from("foo"));
568 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn to_os_string(&self) -> OsString {
570 OsString { inner: self.inner.to_owned() }
573 /// Checks whether the `OsStr` is empty.
578 /// use std::ffi::OsStr;
580 /// let os_str = OsStr::new("");
581 /// assert!(os_str.is_empty());
583 /// let os_str = OsStr::new("foo");
584 /// assert!(!os_str.is_empty());
586 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
587 pub fn is_empty(&self) -> bool {
588 self.inner.inner.is_empty()
591 /// Returns the length of this `OsStr`.
593 /// Note that this does **not** return the number of bytes in the string in
596 /// The length returned is that of the underlying storage used by `OsStr`;
597 /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
598 /// store strings in a form best suited for cheap inter-conversion between
599 /// native-platform and Rust string forms, which may differ significantly
600 /// from both of them, including in storage size and encoding.
602 /// This number is simply useful for passing to other methods, like
603 /// [`OsString::with_capacity`] to avoid reallocations.
605 /// [`OsString`]: struct.OsString.html
606 /// [`OsString::with_capacity`]: struct.OsString.html#method.with_capacity
611 /// use std::ffi::OsStr;
613 /// let os_str = OsStr::new("");
614 /// assert_eq!(os_str.len(), 0);
616 /// let os_str = OsStr::new("foo");
617 /// assert_eq!(os_str.len(), 3);
619 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
620 pub fn len(&self) -> usize {
621 self.inner.inner.len()
624 /// Converts a [`Box`]`<OsStr>` into an [`OsString`] without copying or allocating.
626 /// [`Box`]: ../boxed/struct.Box.html
627 /// [`OsString`]: struct.OsString.html
628 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
629 pub fn into_os_string(self: Box<OsStr>) -> OsString {
630 let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
631 OsString { inner: Buf::from_box(boxed) }
634 /// Gets the underlying byte representation.
636 /// Note: it is *crucial* that this API is private, to avoid
637 /// revealing the internal, platform-specific encodings.
638 fn bytes(&self) -> &[u8] {
639 unsafe { &*(&self.inner as *const _ as *const [u8]) }
643 #[stable(feature = "box_from_os_str", since = "1.17.0")]
644 impl<'a> From<&'a OsStr> for Box<OsStr> {
645 fn from(s: &'a OsStr) -> Box<OsStr> {
646 let rw = Box::into_raw(s.inner.into_box()) as *mut OsStr;
647 unsafe { Box::from_raw(rw) }
651 #[stable(feature = "os_string_from_box", since = "1.18.0")]
652 impl From<Box<OsStr>> for OsString {
653 /// Converts a `Box<OsStr>` into a `OsString` without copying or allocating.
655 /// [`Box`]: ../boxed/struct.Box.html
656 /// [`OsString`]: ../ffi/struct.OsString.html
657 fn from(boxed: Box<OsStr>) -> OsString {
658 boxed.into_os_string()
662 #[stable(feature = "box_from_os_string", since = "1.20.0")]
663 impl From<OsString> for Box<OsStr> {
664 /// Converts a [`OsString`] into a [`Box`]`<OsStr>` without copying or allocating.
666 /// [`Box`]: ../boxed/struct.Box.html
667 /// [`OsString`]: ../ffi/struct.OsString.html
668 fn from(s: OsString) -> Box<OsStr> {
669 s.into_boxed_os_str()
673 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
674 impl Clone for Box<OsStr> {
676 fn clone(&self) -> Self {
677 self.to_os_string().into_boxed_os_str()
681 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
682 impl From<OsString> for Arc<OsStr> {
683 /// Converts a [`OsString`] into a [`Arc`]`<OsStr>` without copying or allocating.
685 /// [`Arc`]: ../sync/struct.Arc.html
686 /// [`OsString`]: ../ffi/struct.OsString.html
688 fn from(s: OsString) -> Arc<OsStr> {
689 let arc = s.inner.into_arc();
690 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
694 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
695 impl<'a> From<&'a OsStr> for Arc<OsStr> {
697 fn from(s: &OsStr) -> Arc<OsStr> {
698 let arc = s.inner.into_arc();
699 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
703 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
704 impl From<OsString> for Rc<OsStr> {
705 /// Converts a [`OsString`] into a [`Rc`]`<OsStr>` without copying or allocating.
707 /// [`Rc`]: ../rc/struct.Rc.html
708 /// [`OsString`]: ../ffi/struct.OsString.html
710 fn from(s: OsString) -> Rc<OsStr> {
711 let rc = s.inner.into_rc();
712 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
716 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
717 impl<'a> From<&'a OsStr> for Rc<OsStr> {
719 fn from(s: &OsStr) -> Rc<OsStr> {
720 let rc = s.inner.into_rc();
721 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
725 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
726 impl<'a> From<OsString> for Cow<'a, OsStr> {
728 fn from(s: OsString) -> Cow<'a, OsStr> {
733 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
734 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
736 fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
741 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
742 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
744 fn from(s: &'a OsString) -> Cow<'a, OsStr> {
745 Cow::Borrowed(s.as_os_str())
749 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
750 impl<'a> From<Cow<'a, OsStr>> for OsString {
752 fn from(s: Cow<'a, OsStr>) -> Self {
757 #[stable(feature = "box_default_extra", since = "1.17.0")]
758 impl Default for Box<OsStr> {
759 fn default() -> Box<OsStr> {
760 let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
761 unsafe { Box::from_raw(rw) }
765 #[stable(feature = "osstring_default", since = "1.9.0")]
766 impl<'a> Default for &'a OsStr {
767 /// Creates an empty `OsStr`.
769 fn default() -> &'a OsStr {
774 #[stable(feature = "rust1", since = "1.0.0")]
775 impl PartialEq for OsStr {
776 fn eq(&self, other: &OsStr) -> bool {
777 self.bytes().eq(other.bytes())
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl PartialEq<str> for OsStr {
783 fn eq(&self, other: &str) -> bool {
784 *self == *OsStr::new(other)
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl PartialEq<OsStr> for str {
790 fn eq(&self, other: &OsStr) -> bool {
791 *other == *OsStr::new(self)
795 #[stable(feature = "rust1", since = "1.0.0")]
798 #[stable(feature = "rust1", since = "1.0.0")]
799 impl PartialOrd for OsStr {
801 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
802 self.bytes().partial_cmp(other.bytes())
805 fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
807 fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
809 fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
811 fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl PartialOrd<str> for OsStr {
817 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
818 self.partial_cmp(OsStr::new(other))
822 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
823 // have more flexible coherence rules.
825 #[stable(feature = "rust1", since = "1.0.0")]
828 fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
831 macro_rules! impl_cmp {
832 ($lhs:ty, $rhs: ty) => {
833 #[stable(feature = "cmp_os_str", since = "1.8.0")]
834 impl<'a, 'b> PartialEq<$rhs> for $lhs {
836 fn eq(&self, other: &$rhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
839 #[stable(feature = "cmp_os_str", since = "1.8.0")]
840 impl<'a, 'b> PartialEq<$lhs> for $rhs {
842 fn eq(&self, other: &$lhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
845 #[stable(feature = "cmp_os_str", since = "1.8.0")]
846 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
848 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
849 <OsStr as PartialOrd>::partial_cmp(self, other)
853 #[stable(feature = "cmp_os_str", since = "1.8.0")]
854 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
856 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
857 <OsStr as PartialOrd>::partial_cmp(self, other)
863 impl_cmp!(OsString, OsStr);
864 impl_cmp!(OsString, &'a OsStr);
865 impl_cmp!(Cow<'a, OsStr>, OsStr);
866 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
867 impl_cmp!(Cow<'a, OsStr>, OsString);
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl Hash for OsStr {
872 fn hash<H: Hasher>(&self, state: &mut H) {
873 self.bytes().hash(state)
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl fmt::Debug for OsStr {
879 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
880 fmt::Debug::fmt(&self.inner, formatter)
885 pub(crate) fn display(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
886 fmt::Display::fmt(&self.inner, formatter)
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl Borrow<OsStr> for OsString {
892 fn borrow(&self) -> &OsStr { &self[..] }
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl ToOwned for OsStr {
897 type Owned = OsString;
898 fn to_owned(&self) -> OsString {
901 fn clone_into(&self, target: &mut OsString) {
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl AsRef<OsStr> for OsStr {
909 fn as_ref(&self) -> &OsStr {
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl AsRef<OsStr> for OsString {
916 fn as_ref(&self) -> &OsStr {
921 #[stable(feature = "rust1", since = "1.0.0")]
922 impl AsRef<OsStr> for str {
923 fn as_ref(&self) -> &OsStr {
924 OsStr::from_inner(Slice::from_str(self))
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl AsRef<OsStr> for String {
930 fn as_ref(&self) -> &OsStr {
935 impl FromInner<Buf> for OsString {
936 fn from_inner(buf: Buf) -> OsString {
937 OsString { inner: buf }
941 impl IntoInner<Buf> for OsString {
942 fn into_inner(self) -> Buf {
947 impl AsInner<Slice> for OsStr {
948 fn as_inner(&self) -> &Slice {
956 use sys_common::{AsInner, IntoInner};
962 fn test_os_string_with_capacity() {
963 let os_string = OsString::with_capacity(0);
964 assert_eq!(0, os_string.inner.into_inner().capacity());
966 let os_string = OsString::with_capacity(10);
967 assert_eq!(10, os_string.inner.into_inner().capacity());
969 let mut os_string = OsString::with_capacity(0);
970 os_string.push("abc");
971 assert!(os_string.inner.into_inner().capacity() >= 3);
975 fn test_os_string_clear() {
976 let mut os_string = OsString::from("abc");
977 assert_eq!(3, os_string.inner.as_inner().len());
980 assert_eq!(&os_string, "");
981 assert_eq!(0, os_string.inner.as_inner().len());
985 fn test_os_string_capacity() {
986 let os_string = OsString::with_capacity(0);
987 assert_eq!(0, os_string.capacity());
989 let os_string = OsString::with_capacity(10);
990 assert_eq!(10, os_string.capacity());
992 let mut os_string = OsString::with_capacity(0);
993 os_string.push("abc");
994 assert!(os_string.capacity() >= 3);
998 fn test_os_string_reserve() {
999 let mut os_string = OsString::new();
1000 assert_eq!(os_string.capacity(), 0);
1002 os_string.reserve(2);
1003 assert!(os_string.capacity() >= 2);
1006 os_string.push("a");
1009 assert!(os_string.capacity() >= 16);
1010 os_string.reserve(16);
1011 assert!(os_string.capacity() >= 32);
1013 os_string.push("a");
1015 os_string.reserve(16);
1016 assert!(os_string.capacity() >= 33)
1020 fn test_os_string_reserve_exact() {
1021 let mut os_string = OsString::new();
1022 assert_eq!(os_string.capacity(), 0);
1024 os_string.reserve_exact(2);
1025 assert!(os_string.capacity() >= 2);
1028 os_string.push("a");
1031 assert!(os_string.capacity() >= 16);
1032 os_string.reserve_exact(16);
1033 assert!(os_string.capacity() >= 32);
1035 os_string.push("a");
1037 os_string.reserve_exact(16);
1038 assert!(os_string.capacity() >= 33)
1042 fn test_os_string_default() {
1043 let os_string: OsString = Default::default();
1044 assert_eq!("", &os_string);
1048 fn test_os_str_is_empty() {
1049 let mut os_string = OsString::new();
1050 assert!(os_string.is_empty());
1052 os_string.push("abc");
1053 assert!(!os_string.is_empty());
1056 assert!(os_string.is_empty());
1060 fn test_os_str_len() {
1061 let mut os_string = OsString::new();
1062 assert_eq!(0, os_string.len());
1064 os_string.push("abc");
1065 assert_eq!(3, os_string.len());
1068 assert_eq!(0, os_string.len());
1072 fn test_os_str_default() {
1073 let os_str: &OsStr = Default::default();
1074 assert_eq!("", os_str);
1079 let orig = "Hello, world!";
1080 let os_str = OsStr::new(orig);
1081 let boxed: Box<OsStr> = Box::from(os_str);
1082 let os_string = os_str.to_owned().into_boxed_os_str().into_os_string();
1083 assert_eq!(os_str, &*boxed);
1084 assert_eq!(&*boxed, &*os_string);
1085 assert_eq!(&*os_string, os_str);
1089 fn boxed_default() {
1090 let boxed = <Box<OsStr>>::default();
1091 assert!(boxed.is_empty());
1095 fn test_os_str_clone_into() {
1096 let mut os_string = OsString::with_capacity(123);
1097 os_string.push("hello");
1098 let os_str = OsStr::new("bonjour");
1099 os_str.clone_into(&mut os_string);
1100 assert_eq!(os_str, os_string);
1101 assert!(os_string.capacity() >= 123);
1106 let orig = "Hello, world!";
1107 let os_str = OsStr::new(orig);
1108 let rc: Rc<OsStr> = Rc::from(os_str);
1109 let arc: Arc<OsStr> = Arc::from(os_str);
1111 assert_eq!(&*rc, os_str);
1112 assert_eq!(&*arc, os_str);
1114 let rc2: Rc<OsStr> = Rc::from(os_str.to_owned());
1115 let arc2: Arc<OsStr> = Arc::from(os_str.to_owned());
1117 assert_eq!(&*rc2, os_str);
1118 assert_eq!(&*arc2, os_str);