]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/os_str.rs
Various minor/cosmetic improvements to code
[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 use borrow::{Borrow, Cow};
12 use fmt;
13 use ops;
14 use cmp;
15 use hash::{Hash, Hasher};
16 use rc::Rc;
17 use sync::Arc;
18
19 use sys::os_str::{Buf, Slice};
20 use sys_common::{AsInner, IntoInner, FromInner};
21
22 /// A type that can represent owned, mutable platform-native strings, but is
23 /// cheaply inter-convertible with Rust strings.
24 ///
25 /// The need for this type arises from the fact that:
26 ///
27 /// * On Unix systems, strings are often arbitrary sequences of non-zero
28 ///   bytes, in many cases interpreted as UTF-8.
29 ///
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.
32 ///
33 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
34 ///
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`].
40 ///
41 /// `OsString` is to [`&OsStr`] as [`String`] is to [`&str`]: the former
42 /// in each pair are owned strings; the latter are borrowed
43 /// references.
44 ///
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.
51 ///
52 /// # Creating an `OsString`
53 ///
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.
57 ///
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
62 /// [`push`] method.
63 ///
64 /// # Extracting a borrowed reference to the whole OS string
65 ///
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
68 /// whole string.
69 ///
70 /// # Conversions
71 ///
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.
74 ///
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
88 #[derive(Clone)]
89 #[stable(feature = "rust1", since = "1.0.0")]
90 pub struct OsString {
91     inner: Buf
92 }
93
94 /// Borrowed reference to an OS string (see [`OsString`]).
95 ///
96 /// This type represents a borrowed reference to a string in the operating system's preferred
97 /// representation.
98 ///
99 /// `&OsStr` is to [`OsString`] as [`&str`] is to [`String`]: the former in each pair are borrowed
100 /// references; the latter are owned strings.
101 ///
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.
104 ///
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")]
110 pub struct OsStr {
111     inner: Slice
112 }
113
114 impl OsString {
115     /// Constructs a new empty `OsString`.
116     ///
117     /// # Examples
118     ///
119     /// ```
120     /// use std::ffi::OsString;
121     ///
122     /// let os_string = OsString::new();
123     /// ```
124     #[stable(feature = "rust1", since = "1.0.0")]
125     pub fn new() -> OsString {
126         OsString { inner: Buf::from_string(String::new()) }
127     }
128
129     /// Converts to an [`OsStr`] slice.
130     ///
131     /// [`OsStr`]: struct.OsStr.html
132     ///
133     /// # Examples
134     ///
135     /// ```
136     /// use std::ffi::{OsString, OsStr};
137     ///
138     /// let os_string = OsString::from("foo");
139     /// let os_str = OsStr::new("foo");
140     /// assert_eq!(os_string.as_os_str(), os_str);
141     /// ```
142     #[stable(feature = "rust1", since = "1.0.0")]
143     pub fn as_os_str(&self) -> &OsStr {
144         self
145     }
146
147     /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
148     ///
149     /// On failure, ownership of the original `OsString` is returned.
150     ///
151     /// [`String`]: ../../std/string/struct.String.html
152     ///
153     /// # Examples
154     ///
155     /// ```
156     /// use std::ffi::OsString;
157     ///
158     /// let os_string = OsString::from("foo");
159     /// let string = os_string.into_string();
160     /// assert_eq!(string, Ok(String::from("foo")));
161     /// ```
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} )
165     }
166
167     /// Extends the string with the given [`&OsStr`] slice.
168     ///
169     /// [`&OsStr`]: struct.OsStr.html
170     ///
171     /// # Examples
172     ///
173     /// ```
174     /// use std::ffi::OsString;
175     ///
176     /// let mut os_string = OsString::from("foo");
177     /// os_string.push("bar");
178     /// assert_eq!(&os_string, "foobar");
179     /// ```
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)
183     }
184
185     /// Creates a new `OsString` with the given capacity.
186     ///
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
189     /// allocate.
190     ///
191     /// See main `OsString` documentation information about encoding.
192     ///
193     /// # Examples
194     ///
195     /// ```
196     /// use std::ffi::OsString;
197     ///
198     /// let mut os_string = OsString::with_capacity(10);
199     /// let capacity = os_string.capacity();
200     ///
201     /// // This push is done without reallocating
202     /// os_string.push("foo");
203     ///
204     /// assert_eq!(capacity, os_string.capacity());
205     /// ```
206     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
207     pub fn with_capacity(capacity: usize) -> OsString {
208         OsString {
209             inner: Buf::with_capacity(capacity)
210         }
211     }
212
213     /// Truncates the `OsString` to zero length.
214     ///
215     /// # Examples
216     ///
217     /// ```
218     /// use std::ffi::OsString;
219     ///
220     /// let mut os_string = OsString::from("foo");
221     /// assert_eq!(&os_string, "foo");
222     ///
223     /// os_string.clear();
224     /// assert_eq!(&os_string, "");
225     /// ```
226     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
227     pub fn clear(&mut self) {
228         self.inner.clear()
229     }
230
231     /// Returns the capacity this `OsString` can hold without reallocating.
232     ///
233     /// See `OsString` introduction for information about encoding.
234     ///
235     /// # Examples
236     ///
237     /// ```
238     /// use std::ffi::OsString;
239     ///
240     /// let mut os_string = OsString::with_capacity(10);
241     /// assert!(os_string.capacity() >= 10);
242     /// ```
243     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
244     pub fn capacity(&self) -> usize {
245         self.inner.capacity()
246     }
247
248     /// Reserves capacity for at least `additional` more capacity to be inserted
249     /// in the given `OsString`.
250     ///
251     /// The collection may reserve more space to avoid frequent reallocations.
252     ///
253     /// # Examples
254     ///
255     /// ```
256     /// use std::ffi::OsString;
257     ///
258     /// let mut s = OsString::new();
259     /// s.reserve(10);
260     /// assert!(s.capacity() >= 10);
261     /// ```
262     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
263     pub fn reserve(&mut self, additional: usize) {
264         self.inner.reserve(additional)
265     }
266
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.
270     ///
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.
274     ///
275     /// # Examples
276     ///
277     /// ```
278     /// use std::ffi::OsString;
279     ///
280     /// let mut s = OsString::new();
281     /// s.reserve_exact(10);
282     /// assert!(s.capacity() >= 10);
283     /// ```
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)
287     }
288
289     /// Shrinks the capacity of the `OsString` to match its length.
290     ///
291     /// # Examples
292     ///
293     /// ```
294     /// use std::ffi::OsString;
295     ///
296     /// let mut s = OsString::from("foo");
297     ///
298     /// s.reserve(100);
299     /// assert!(s.capacity() >= 100);
300     ///
301     /// s.shrink_to_fit();
302     /// assert_eq!(3, s.capacity());
303     /// ```
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()
307     }
308
309     /// Shrinks the capacity of the `OsString` with a lower bound.
310     ///
311     /// The capacity will remain at least as large as both the length
312     /// and the supplied value.
313     ///
314     /// Panics if the current capacity is smaller than the supplied
315     /// minimum capacity.
316     ///
317     /// # Examples
318     ///
319     /// ```
320     /// #![feature(shrink_to)]
321     /// use std::ffi::OsString;
322     ///
323     /// let mut s = OsString::from("foo");
324     ///
325     /// s.reserve(100);
326     /// assert!(s.capacity() >= 100);
327     ///
328     /// s.shrink_to(10);
329     /// assert!(s.capacity() >= 10);
330     /// s.shrink_to(0);
331     /// assert!(s.capacity() >= 3);
332     /// ```
333     #[inline]
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)
337     }
338
339     /// Converts this `OsString` into a boxed [`OsStr`].
340     ///
341     /// [`OsStr`]: struct.OsStr.html
342     ///
343     /// # Examples
344     ///
345     /// ```
346     /// use std::ffi::{OsString, OsStr};
347     ///
348     /// let s = OsString::from("hello");
349     ///
350     /// let b: Box<OsStr> = s.into_boxed_os_str();
351     /// ```
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) }
356     }
357 }
358
359 #[stable(feature = "rust1", since = "1.0.0")]
360 impl From<String> for OsString {
361     /// Converts a [`String`] into a [`OsString`].
362     ///
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) }
366     }
367 }
368
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()
373     }
374 }
375
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl ops::Index<ops::RangeFull> for OsString {
378     type Output = OsStr;
379
380     #[inline]
381     fn index(&self, _index: ops::RangeFull) -> &OsStr {
382         OsStr::from_inner(self.inner.as_slice())
383     }
384 }
385
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl ops::Deref for OsString {
388     type Target = OsStr;
389
390     #[inline]
391     fn deref(&self) -> &OsStr {
392         &self[..]
393     }
394 }
395
396 #[stable(feature = "osstring_default", since = "1.9.0")]
397 impl Default for OsString {
398     /// Constructs an empty `OsString`.
399     #[inline]
400     fn default() -> OsString {
401         OsString::new()
402     }
403 }
404
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)
409     }
410 }
411
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl PartialEq for OsString {
414     fn eq(&self, other: &OsString) -> bool {
415         &**self == &**other
416     }
417 }
418
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl PartialEq<str> for OsString {
421     fn eq(&self, other: &str) -> bool {
422         &**self == other
423     }
424 }
425
426 #[stable(feature = "rust1", since = "1.0.0")]
427 impl PartialEq<OsString> for str {
428     fn eq(&self, other: &OsString) -> bool {
429         &**other == self
430     }
431 }
432
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 {
436         **self == **other
437     }
438 }
439
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 {
443         **other == **self
444     }
445 }
446
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl Eq for OsString {}
449
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl PartialOrd for OsString {
452     #[inline]
453     fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
454         (&**self).partial_cmp(&**other)
455     }
456     #[inline]
457     fn lt(&self, other: &OsString) -> bool { &**self < &**other }
458     #[inline]
459     fn le(&self, other: &OsString) -> bool { &**self <= &**other }
460     #[inline]
461     fn gt(&self, other: &OsString) -> bool { &**self > &**other }
462     #[inline]
463     fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
464 }
465
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl PartialOrd<str> for OsString {
468     #[inline]
469     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
470         (&**self).partial_cmp(other)
471     }
472 }
473
474 #[stable(feature = "rust1", since = "1.0.0")]
475 impl Ord for OsString {
476     #[inline]
477     fn cmp(&self, other: &OsString) -> cmp::Ordering {
478         (&**self).cmp(&**other)
479     }
480 }
481
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl Hash for OsString {
484     #[inline]
485     fn hash<H: Hasher>(&self, state: &mut H) {
486         (&**self).hash(state)
487     }
488 }
489
490 impl OsStr {
491     /// Coerces into an `OsStr` slice.
492     ///
493     /// # Examples
494     ///
495     /// ```
496     /// use std::ffi::OsStr;
497     ///
498     /// let os_str = OsStr::new("foo");
499     /// ```
500     #[stable(feature = "rust1", since = "1.0.0")]
501     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
502         s.as_ref()
503     }
504
505     fn from_inner(inner: &Slice) -> &OsStr {
506         unsafe { &*(inner as *const Slice as *const OsStr) }
507     }
508
509     /// Yields a [`&str`] slice if the `OsStr` is valid Unicode.
510     ///
511     /// This conversion may entail doing a check for UTF-8 validity.
512     ///
513     /// [`&str`]: ../../std/primitive.str.html
514     ///
515     /// # Examples
516     ///
517     /// ```
518     /// use std::ffi::OsStr;
519     ///
520     /// let os_str = OsStr::new("foo");
521     /// assert_eq!(os_str.to_str(), Some("foo"));
522     /// ```
523     #[stable(feature = "rust1", since = "1.0.0")]
524     pub fn to_str(&self) -> Option<&str> {
525         self.inner.to_str()
526     }
527
528     /// Converts an `OsStr` to a [`Cow`]`<`[`str`]`>`.
529     ///
530     /// Any non-Unicode sequences are replaced with
531     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
532     ///
533     /// [`Cow`]: ../../std/borrow/enum.Cow.html
534     /// [`str`]: ../../std/primitive.str.html
535     /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
536     ///
537     /// # Examples
538     ///
539     /// Calling `to_string_lossy` on an `OsStr` with valid unicode:
540     ///
541     /// ```
542     /// use std::ffi::OsStr;
543     ///
544     /// let os_str = OsStr::new("foo");
545     /// assert_eq!(os_str.to_string_lossy(), "foo");
546     /// ```
547     ///
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()
553     }
554
555     /// Copies the slice into an owned [`OsString`].
556     ///
557     /// [`OsString`]: struct.OsString.html
558     ///
559     /// # Examples
560     ///
561     /// ```
562     /// use std::ffi::{OsStr, OsString};
563     ///
564     /// let os_str = OsStr::new("foo");
565     /// let os_string = os_str.to_os_string();
566     /// assert_eq!(os_string, OsString::from("foo"));
567     /// ```
568     #[stable(feature = "rust1", since = "1.0.0")]
569     pub fn to_os_string(&self) -> OsString {
570         OsString { inner: self.inner.to_owned() }
571     }
572
573     /// Checks whether the `OsStr` is empty.
574     ///
575     /// # Examples
576     ///
577     /// ```
578     /// use std::ffi::OsStr;
579     ///
580     /// let os_str = OsStr::new("");
581     /// assert!(os_str.is_empty());
582     ///
583     /// let os_str = OsStr::new("foo");
584     /// assert!(!os_str.is_empty());
585     /// ```
586     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
587     pub fn is_empty(&self) -> bool {
588         self.inner.inner.is_empty()
589     }
590
591     /// Returns the length of this `OsStr`.
592     ///
593     /// Note that this does **not** return the number of bytes in the string in
594     /// OS string form.
595     ///
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.
601     ///
602     /// This number is simply useful for passing to other methods, like
603     /// [`OsString::with_capacity`] to avoid reallocations.
604     ///
605     /// [`OsString`]: struct.OsString.html
606     /// [`OsString::with_capacity`]: struct.OsString.html#method.with_capacity
607     ///
608     /// # Examples
609     ///
610     /// ```
611     /// use std::ffi::OsStr;
612     ///
613     /// let os_str = OsStr::new("");
614     /// assert_eq!(os_str.len(), 0);
615     ///
616     /// let os_str = OsStr::new("foo");
617     /// assert_eq!(os_str.len(), 3);
618     /// ```
619     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
620     pub fn len(&self) -> usize {
621         self.inner.inner.len()
622     }
623
624     /// Converts a [`Box`]`<OsStr>` into an [`OsString`] without copying or allocating.
625     ///
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) }
632     }
633
634     /// Gets the underlying byte representation.
635     ///
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]) }
640     }
641 }
642
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) }
648     }
649 }
650
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.
654     ///
655     /// [`Box`]: ../boxed/struct.Box.html
656     /// [`OsString`]: ../ffi/struct.OsString.html
657     fn from(boxed: Box<OsStr>) -> OsString {
658         boxed.into_os_string()
659     }
660 }
661
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.
665     ///
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()
670     }
671 }
672
673 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
674 impl Clone for Box<OsStr> {
675     #[inline]
676     fn clone(&self) -> Self {
677         self.to_os_string().into_boxed_os_str()
678     }
679 }
680
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.
684     ///
685     /// [`Arc`]: ../sync/struct.Arc.html
686     /// [`OsString`]: ../ffi/struct.OsString.html
687     #[inline]
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) }
691     }
692 }
693
694 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
695 impl<'a> From<&'a OsStr> for Arc<OsStr> {
696     #[inline]
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) }
700     }
701 }
702
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.
706     ///
707     /// [`Rc`]: ../rc/struct.Rc.html
708     /// [`OsString`]: ../ffi/struct.OsString.html
709     #[inline]
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) }
713     }
714 }
715
716 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
717 impl<'a> From<&'a OsStr> for Rc<OsStr> {
718     #[inline]
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) }
722     }
723 }
724
725 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
726 impl<'a> From<OsString> for Cow<'a, OsStr> {
727     #[inline]
728     fn from(s: OsString) -> Cow<'a, OsStr> {
729         Cow::Owned(s)
730     }
731 }
732
733 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
734 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
735     #[inline]
736     fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
737         Cow::Borrowed(s)
738     }
739 }
740
741 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
742 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
743     #[inline]
744     fn from(s: &'a OsString) -> Cow<'a, OsStr> {
745         Cow::Borrowed(s.as_os_str())
746     }
747 }
748
749 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
750 impl<'a> From<Cow<'a, OsStr>> for OsString {
751     #[inline]
752     fn from(s: Cow<'a, OsStr>) -> Self {
753         s.into_owned()
754     }
755 }
756
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) }
762     }
763 }
764
765 #[stable(feature = "osstring_default", since = "1.9.0")]
766 impl<'a> Default for &'a OsStr {
767     /// Creates an empty `OsStr`.
768     #[inline]
769     fn default() -> &'a OsStr {
770         OsStr::new("")
771     }
772 }
773
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())
778     }
779 }
780
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)
785     }
786 }
787
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)
792     }
793 }
794
795 #[stable(feature = "rust1", since = "1.0.0")]
796 impl Eq for OsStr {}
797
798 #[stable(feature = "rust1", since = "1.0.0")]
799 impl PartialOrd for OsStr {
800     #[inline]
801     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
802         self.bytes().partial_cmp(other.bytes())
803     }
804     #[inline]
805     fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
806     #[inline]
807     fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
808     #[inline]
809     fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
810     #[inline]
811     fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
812 }
813
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl PartialOrd<str> for OsStr {
816     #[inline]
817     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
818         self.partial_cmp(OsStr::new(other))
819     }
820 }
821
822 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
823 // have more flexible coherence rules.
824
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl Ord for OsStr {
827     #[inline]
828     fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
829 }
830
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 {
835             #[inline]
836             fn eq(&self, other: &$rhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
837         }
838
839         #[stable(feature = "cmp_os_str", since = "1.8.0")]
840         impl<'a, 'b> PartialEq<$lhs> for $rhs {
841             #[inline]
842             fn eq(&self, other: &$lhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
843         }
844
845         #[stable(feature = "cmp_os_str", since = "1.8.0")]
846         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
847             #[inline]
848             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
849                 <OsStr as PartialOrd>::partial_cmp(self, other)
850             }
851         }
852
853         #[stable(feature = "cmp_os_str", since = "1.8.0")]
854         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
855             #[inline]
856             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
857                 <OsStr as PartialOrd>::partial_cmp(self, other)
858             }
859         }
860     }
861 }
862
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);
868
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl Hash for OsStr {
871     #[inline]
872     fn hash<H: Hasher>(&self, state: &mut H) {
873         self.bytes().hash(state)
874     }
875 }
876
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)
881     }
882 }
883
884 impl OsStr {
885     pub(crate) fn display(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
886         fmt::Display::fmt(&self.inner, formatter)
887     }
888 }
889
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl Borrow<OsStr> for OsString {
892     fn borrow(&self) -> &OsStr { &self[..] }
893 }
894
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl ToOwned for OsStr {
897     type Owned = OsString;
898     fn to_owned(&self) -> OsString {
899         self.to_os_string()
900     }
901     fn clone_into(&self, target: &mut OsString) {
902         target.clear();
903         target.push(self);
904     }
905 }
906
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl AsRef<OsStr> for OsStr {
909     fn as_ref(&self) -> &OsStr {
910         self
911     }
912 }
913
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl AsRef<OsStr> for OsString {
916     fn as_ref(&self) -> &OsStr {
917         self
918     }
919 }
920
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))
925     }
926 }
927
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl AsRef<OsStr> for String {
930     fn as_ref(&self) -> &OsStr {
931         (&**self).as_ref()
932     }
933 }
934
935 impl FromInner<Buf> for OsString {
936     fn from_inner(buf: Buf) -> OsString {
937         OsString { inner: buf }
938     }
939 }
940
941 impl IntoInner<Buf> for OsString {
942     fn into_inner(self) -> Buf {
943         self.inner
944     }
945 }
946
947 impl AsInner<Slice> for OsStr {
948     fn as_inner(&self) -> &Slice {
949         &self.inner
950     }
951 }
952
953 #[cfg(test)]
954 mod tests {
955     use super::*;
956     use sys_common::{AsInner, IntoInner};
957
958     use rc::Rc;
959     use sync::Arc;
960
961     #[test]
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());
965
966         let os_string = OsString::with_capacity(10);
967         assert_eq!(10, os_string.inner.into_inner().capacity());
968
969         let mut os_string = OsString::with_capacity(0);
970         os_string.push("abc");
971         assert!(os_string.inner.into_inner().capacity() >= 3);
972     }
973
974     #[test]
975     fn test_os_string_clear() {
976         let mut os_string = OsString::from("abc");
977         assert_eq!(3, os_string.inner.as_inner().len());
978
979         os_string.clear();
980         assert_eq!(&os_string, "");
981         assert_eq!(0, os_string.inner.as_inner().len());
982     }
983
984     #[test]
985     fn test_os_string_capacity() {
986         let os_string = OsString::with_capacity(0);
987         assert_eq!(0, os_string.capacity());
988
989         let os_string = OsString::with_capacity(10);
990         assert_eq!(10, os_string.capacity());
991
992         let mut os_string = OsString::with_capacity(0);
993         os_string.push("abc");
994         assert!(os_string.capacity() >= 3);
995     }
996
997     #[test]
998     fn test_os_string_reserve() {
999         let mut os_string = OsString::new();
1000         assert_eq!(os_string.capacity(), 0);
1001
1002         os_string.reserve(2);
1003         assert!(os_string.capacity() >= 2);
1004
1005         for _ in 0..16 {
1006             os_string.push("a");
1007         }
1008
1009         assert!(os_string.capacity() >= 16);
1010         os_string.reserve(16);
1011         assert!(os_string.capacity() >= 32);
1012
1013         os_string.push("a");
1014
1015         os_string.reserve(16);
1016         assert!(os_string.capacity() >= 33)
1017     }
1018
1019     #[test]
1020     fn test_os_string_reserve_exact() {
1021         let mut os_string = OsString::new();
1022         assert_eq!(os_string.capacity(), 0);
1023
1024         os_string.reserve_exact(2);
1025         assert!(os_string.capacity() >= 2);
1026
1027         for _ in 0..16 {
1028             os_string.push("a");
1029         }
1030
1031         assert!(os_string.capacity() >= 16);
1032         os_string.reserve_exact(16);
1033         assert!(os_string.capacity() >= 32);
1034
1035         os_string.push("a");
1036
1037         os_string.reserve_exact(16);
1038         assert!(os_string.capacity() >= 33)
1039     }
1040
1041     #[test]
1042     fn test_os_string_default() {
1043         let os_string: OsString = Default::default();
1044         assert_eq!("", &os_string);
1045     }
1046
1047     #[test]
1048     fn test_os_str_is_empty() {
1049         let mut os_string = OsString::new();
1050         assert!(os_string.is_empty());
1051
1052         os_string.push("abc");
1053         assert!(!os_string.is_empty());
1054
1055         os_string.clear();
1056         assert!(os_string.is_empty());
1057     }
1058
1059     #[test]
1060     fn test_os_str_len() {
1061         let mut os_string = OsString::new();
1062         assert_eq!(0, os_string.len());
1063
1064         os_string.push("abc");
1065         assert_eq!(3, os_string.len());
1066
1067         os_string.clear();
1068         assert_eq!(0, os_string.len());
1069     }
1070
1071     #[test]
1072     fn test_os_str_default() {
1073         let os_str: &OsStr = Default::default();
1074         assert_eq!("", os_str);
1075     }
1076
1077     #[test]
1078     fn into_boxed() {
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);
1086     }
1087
1088     #[test]
1089     fn boxed_default() {
1090         let boxed = <Box<OsStr>>::default();
1091         assert!(boxed.is_empty());
1092     }
1093
1094     #[test]
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);
1102     }
1103
1104     #[test]
1105     fn into_rc() {
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);
1110
1111         assert_eq!(&*rc, os_str);
1112         assert_eq!(&*arc, os_str);
1113
1114         let rc2: Rc<OsStr> = Rc::from(os_str.to_owned());
1115         let arc2: Arc<OsStr> = Arc::from(os_str.to_owned());
1116
1117         assert_eq!(&*rc2, os_str);
1118         assert_eq!(&*arc2, os_str);
1119     }
1120 }