]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/os_str.rs
ec2d07f34ca5fc4a7801ce6d93d35a5153ad2e67
[rust.git] / src / libstd / ffi / os_str.rs
1 use crate::borrow::{Borrow, Cow};
2 use crate::cmp;
3 use crate::fmt;
4 use crate::hash::{Hash, Hasher};
5 use crate::ops;
6 use crate::rc::Rc;
7 use crate::sync::Arc;
8
9 use crate::sys::os_str::{Buf, Slice};
10 use crate::sys_common::{AsInner, FromInner, IntoInner};
11
12 /// A type that can represent owned, mutable platform-native strings, but is
13 /// cheaply inter-convertible with Rust strings.
14 ///
15 /// The need for this type arises from the fact that:
16 ///
17 /// * On Unix systems, strings are often arbitrary sequences of non-zero
18 ///   bytes, in many cases interpreted as UTF-8.
19 ///
20 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
21 ///   values, interpreted as UTF-16 when it is valid to do so.
22 ///
23 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
24 ///
25 /// `OsString` and [`OsStr`] bridge this gap by simultaneously representing Rust
26 /// and platform-native string values, and in particular allowing a Rust string
27 /// to be converted into an "OS" string with no cost if possible. A consequence
28 /// of this is that `OsString` instances are *not* `NUL` terminated; in order
29 /// to pass to e.g., Unix system call, you should create a [`CStr`].
30 ///
31 /// `OsString` is to [`&OsStr`] as [`String`] is to [`&str`]: the former
32 /// in each pair are owned strings; the latter are borrowed
33 /// references.
34 ///
35 /// Note, `OsString` and [`OsStr`] internally do not necessarily hold strings in
36 /// the form native to the platform; While on Unix, strings are stored as a
37 /// sequence of 8-bit values, on Windows, where strings are 16-bit value based
38 /// as just discussed, strings are also actually stored as a sequence of 8-bit
39 /// values, encoded in a less-strict variant of UTF-8. This is useful to
40 /// understand when handling capacity and length values.
41 ///
42 /// # Creating an `OsString`
43 ///
44 /// **From a Rust string**: `OsString` implements
45 /// [`From`]`<`[`String`]`>`, so you can use `my_string.from` to
46 /// create an `OsString` from a normal Rust string.
47 ///
48 /// **From slices:** Just like you can start with an empty Rust
49 /// [`String`] and then [`push_str`][String.push_str] `&str`
50 /// sub-string slices into it, you can create an empty `OsString` with
51 /// the [`new`] method and then push string slices into it with the
52 /// [`push`] method.
53 ///
54 /// # Extracting a borrowed reference to the whole OS string
55 ///
56 /// You can use the [`as_os_str`] method to get an `&`[`OsStr`] from
57 /// an `OsString`; this is effectively a borrowed reference to the
58 /// whole string.
59 ///
60 /// # Conversions
61 ///
62 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
63 /// the traits which `OsString` implements for [conversions] from/to native representations.
64 ///
65 /// [`OsStr`]: struct.OsStr.html
66 /// [`&OsStr`]: struct.OsStr.html
67 /// [`CStr`]: struct.CStr.html
68 /// [`From`]: ../convert/trait.From.html
69 /// [`String`]: ../string/struct.String.html
70 /// [`&str`]: ../primitive.str.html
71 /// [`u8`]: ../primitive.u8.html
72 /// [`u16`]: ../primitive.u16.html
73 /// [String.push_str]: ../string/struct.String.html#method.push_str
74 /// [`new`]: #method.new
75 /// [`push`]: #method.push
76 /// [`as_os_str`]: #method.as_os_str
77 /// [conversions]: index.html#conversions
78 #[derive(Clone)]
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub struct OsString {
81     inner: Buf,
82 }
83
84 /// Borrowed reference to an OS string (see [`OsString`]).
85 ///
86 /// This type represents a borrowed reference to a string in the operating system's preferred
87 /// representation.
88 ///
89 /// `&OsStr` is to [`OsString`] as [`&str`] is to [`String`]: the former in each pair are borrowed
90 /// references; the latter are owned strings.
91 ///
92 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
93 /// the traits which `OsStr` implements for [conversions] from/to native representations.
94 ///
95 /// [`OsString`]: struct.OsString.html
96 /// [`&str`]: ../primitive.str.html
97 /// [`String`]: ../string/struct.String.html
98 /// [conversions]: index.html#conversions
99 #[stable(feature = "rust1", since = "1.0.0")]
100 // FIXME:
101 // `OsStr::from_inner` current implementation relies
102 // on `OsStr` being layout-compatible with `Slice`.
103 // When attribute privacy is implemented, `OsStr` should be annotated as `#[repr(transparent)]`.
104 // Anyway, `OsStr` representation and layout are considered implementation detail, are
105 // not documented and must not be relied upon.
106 pub struct OsStr {
107     inner: Slice,
108 }
109
110 impl OsString {
111     /// Constructs a new empty `OsString`.
112     ///
113     /// # Examples
114     ///
115     /// ```
116     /// use std::ffi::OsString;
117     ///
118     /// let os_string = OsString::new();
119     /// ```
120     #[stable(feature = "rust1", since = "1.0.0")]
121     pub fn new() -> OsString {
122         OsString { inner: Buf::from_string(String::new()) }
123     }
124
125     /// Converts to an [`OsStr`] slice.
126     ///
127     /// [`OsStr`]: struct.OsStr.html
128     ///
129     /// # Examples
130     ///
131     /// ```
132     /// use std::ffi::{OsString, OsStr};
133     ///
134     /// let os_string = OsString::from("foo");
135     /// let os_str = OsStr::new("foo");
136     /// assert_eq!(os_string.as_os_str(), os_str);
137     /// ```
138     #[stable(feature = "rust1", since = "1.0.0")]
139     pub fn as_os_str(&self) -> &OsStr {
140         self
141     }
142
143     /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
144     ///
145     /// On failure, ownership of the original `OsString` is returned.
146     ///
147     /// [`String`]: ../../std/string/struct.String.html
148     ///
149     /// # Examples
150     ///
151     /// ```
152     /// use std::ffi::OsString;
153     ///
154     /// let os_string = OsString::from("foo");
155     /// let string = os_string.into_string();
156     /// assert_eq!(string, Ok(String::from("foo")));
157     /// ```
158     #[stable(feature = "rust1", since = "1.0.0")]
159     pub fn into_string(self) -> Result<String, OsString> {
160         self.inner.into_string().map_err(|buf| OsString { inner: buf })
161     }
162
163     /// Extends the string with the given [`&OsStr`] slice.
164     ///
165     /// [`&OsStr`]: struct.OsStr.html
166     ///
167     /// # Examples
168     ///
169     /// ```
170     /// use std::ffi::OsString;
171     ///
172     /// let mut os_string = OsString::from("foo");
173     /// os_string.push("bar");
174     /// assert_eq!(&os_string, "foobar");
175     /// ```
176     #[stable(feature = "rust1", since = "1.0.0")]
177     pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
178         self.inner.push_slice(&s.as_ref().inner)
179     }
180
181     /// Creates a new `OsString` with the given capacity.
182     ///
183     /// The string will be able to hold exactly `capacity` length units of other
184     /// OS strings without reallocating. If `capacity` is 0, the string will not
185     /// allocate.
186     ///
187     /// See main `OsString` documentation information about encoding.
188     ///
189     /// # Examples
190     ///
191     /// ```
192     /// use std::ffi::OsString;
193     ///
194     /// let mut os_string = OsString::with_capacity(10);
195     /// let capacity = os_string.capacity();
196     ///
197     /// // This push is done without reallocating
198     /// os_string.push("foo");
199     ///
200     /// assert_eq!(capacity, os_string.capacity());
201     /// ```
202     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
203     pub fn with_capacity(capacity: usize) -> OsString {
204         OsString { inner: Buf::with_capacity(capacity) }
205     }
206
207     /// Truncates the `OsString` to zero length.
208     ///
209     /// # Examples
210     ///
211     /// ```
212     /// use std::ffi::OsString;
213     ///
214     /// let mut os_string = OsString::from("foo");
215     /// assert_eq!(&os_string, "foo");
216     ///
217     /// os_string.clear();
218     /// assert_eq!(&os_string, "");
219     /// ```
220     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
221     pub fn clear(&mut self) {
222         self.inner.clear()
223     }
224
225     /// Returns the capacity this `OsString` can hold without reallocating.
226     ///
227     /// See `OsString` introduction for information about encoding.
228     ///
229     /// # Examples
230     ///
231     /// ```
232     /// use std::ffi::OsString;
233     ///
234     /// let os_string = OsString::with_capacity(10);
235     /// assert!(os_string.capacity() >= 10);
236     /// ```
237     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
238     pub fn capacity(&self) -> usize {
239         self.inner.capacity()
240     }
241
242     /// Reserves capacity for at least `additional` more capacity to be inserted
243     /// in the given `OsString`.
244     ///
245     /// The collection may reserve more space to avoid frequent reallocations.
246     ///
247     /// # Examples
248     ///
249     /// ```
250     /// use std::ffi::OsString;
251     ///
252     /// let mut s = OsString::new();
253     /// s.reserve(10);
254     /// assert!(s.capacity() >= 10);
255     /// ```
256     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
257     pub fn reserve(&mut self, additional: usize) {
258         self.inner.reserve(additional)
259     }
260
261     /// Reserves the minimum capacity for exactly `additional` more capacity to
262     /// be inserted in the given `OsString`. Does nothing if the capacity is
263     /// already sufficient.
264     ///
265     /// Note that the allocator may give the collection more space than it
266     /// requests. Therefore, capacity can not be relied upon to be precisely
267     /// minimal. Prefer reserve if future insertions are expected.
268     ///
269     /// # Examples
270     ///
271     /// ```
272     /// use std::ffi::OsString;
273     ///
274     /// let mut s = OsString::new();
275     /// s.reserve_exact(10);
276     /// assert!(s.capacity() >= 10);
277     /// ```
278     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
279     pub fn reserve_exact(&mut self, additional: usize) {
280         self.inner.reserve_exact(additional)
281     }
282
283     /// Shrinks the capacity of the `OsString` to match its length.
284     ///
285     /// # Examples
286     ///
287     /// ```
288     /// use std::ffi::OsString;
289     ///
290     /// let mut s = OsString::from("foo");
291     ///
292     /// s.reserve(100);
293     /// assert!(s.capacity() >= 100);
294     ///
295     /// s.shrink_to_fit();
296     /// assert_eq!(3, s.capacity());
297     /// ```
298     #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
299     pub fn shrink_to_fit(&mut self) {
300         self.inner.shrink_to_fit()
301     }
302
303     /// Shrinks the capacity of the `OsString` with a lower bound.
304     ///
305     /// The capacity will remain at least as large as both the length
306     /// and the supplied value.
307     ///
308     /// Panics if the current capacity is smaller than the supplied
309     /// minimum capacity.
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// #![feature(shrink_to)]
315     /// use std::ffi::OsString;
316     ///
317     /// let mut s = OsString::from("foo");
318     ///
319     /// s.reserve(100);
320     /// assert!(s.capacity() >= 100);
321     ///
322     /// s.shrink_to(10);
323     /// assert!(s.capacity() >= 10);
324     /// s.shrink_to(0);
325     /// assert!(s.capacity() >= 3);
326     /// ```
327     #[inline]
328     #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
329     pub fn shrink_to(&mut self, min_capacity: usize) {
330         self.inner.shrink_to(min_capacity)
331     }
332
333     /// Converts this `OsString` into a boxed [`OsStr`].
334     ///
335     /// [`OsStr`]: struct.OsStr.html
336     ///
337     /// # Examples
338     ///
339     /// ```
340     /// use std::ffi::{OsString, OsStr};
341     ///
342     /// let s = OsString::from("hello");
343     ///
344     /// let b: Box<OsStr> = s.into_boxed_os_str();
345     /// ```
346     #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
347     pub fn into_boxed_os_str(self) -> Box<OsStr> {
348         let rw = Box::into_raw(self.inner.into_box()) as *mut OsStr;
349         unsafe { Box::from_raw(rw) }
350     }
351 }
352
353 #[stable(feature = "rust1", since = "1.0.0")]
354 impl From<String> for OsString {
355     /// Converts a [`String`] into a [`OsString`].
356     ///
357     /// The conversion copies the data, and includes an allocation on the heap.
358     ///
359     /// [`OsString`]: ../../std/ffi/struct.OsString.html
360     fn from(s: String) -> OsString {
361         OsString { inner: Buf::from_string(s) }
362     }
363 }
364
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl<T: ?Sized + AsRef<OsStr>> From<&T> for OsString {
367     fn from(s: &T) -> OsString {
368         s.as_ref().to_os_string()
369     }
370 }
371
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl ops::Index<ops::RangeFull> for OsString {
374     type Output = OsStr;
375
376     #[inline]
377     fn index(&self, _index: ops::RangeFull) -> &OsStr {
378         OsStr::from_inner(self.inner.as_slice())
379     }
380 }
381
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl ops::Deref for OsString {
384     type Target = OsStr;
385
386     #[inline]
387     fn deref(&self) -> &OsStr {
388         &self[..]
389     }
390 }
391
392 #[stable(feature = "osstring_default", since = "1.9.0")]
393 impl Default for OsString {
394     /// Constructs an empty `OsString`.
395     #[inline]
396     fn default() -> OsString {
397         OsString::new()
398     }
399 }
400
401 #[stable(feature = "rust1", since = "1.0.0")]
402 impl fmt::Debug for OsString {
403     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
404         fmt::Debug::fmt(&**self, formatter)
405     }
406 }
407
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl PartialEq for OsString {
410     fn eq(&self, other: &OsString) -> bool {
411         &**self == &**other
412     }
413 }
414
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl PartialEq<str> for OsString {
417     fn eq(&self, other: &str) -> bool {
418         &**self == other
419     }
420 }
421
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl PartialEq<OsString> for str {
424     fn eq(&self, other: &OsString) -> bool {
425         &**other == self
426     }
427 }
428
429 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
430 impl PartialEq<&str> for OsString {
431     fn eq(&self, other: &&str) -> bool {
432         **self == **other
433     }
434 }
435
436 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
437 impl<'a> PartialEq<OsString> for &'a str {
438     fn eq(&self, other: &OsString) -> bool {
439         **other == **self
440     }
441 }
442
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl Eq for OsString {}
445
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl PartialOrd for OsString {
448     #[inline]
449     fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
450         (&**self).partial_cmp(&**other)
451     }
452     #[inline]
453     fn lt(&self, other: &OsString) -> bool {
454         &**self < &**other
455     }
456     #[inline]
457     fn le(&self, other: &OsString) -> bool {
458         &**self <= &**other
459     }
460     #[inline]
461     fn gt(&self, other: &OsString) -> bool {
462         &**self > &**other
463     }
464     #[inline]
465     fn ge(&self, other: &OsString) -> bool {
466         &**self >= &**other
467     }
468 }
469
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl PartialOrd<str> for OsString {
472     #[inline]
473     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
474         (&**self).partial_cmp(other)
475     }
476 }
477
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl Ord for OsString {
480     #[inline]
481     fn cmp(&self, other: &OsString) -> cmp::Ordering {
482         (&**self).cmp(&**other)
483     }
484 }
485
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl Hash for OsString {
488     #[inline]
489     fn hash<H: Hasher>(&self, state: &mut H) {
490         (&**self).hash(state)
491     }
492 }
493
494 impl OsStr {
495     /// Coerces into an `OsStr` slice.
496     ///
497     /// # Examples
498     ///
499     /// ```
500     /// use std::ffi::OsStr;
501     ///
502     /// let os_str = OsStr::new("foo");
503     /// ```
504     #[inline]
505     #[stable(feature = "rust1", since = "1.0.0")]
506     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
507         s.as_ref()
508     }
509
510     #[inline]
511     fn from_inner(inner: &Slice) -> &OsStr {
512         unsafe { &*(inner as *const Slice as *const OsStr) }
513     }
514
515     /// Yields a [`&str`] slice if the `OsStr` is valid Unicode.
516     ///
517     /// This conversion may entail doing a check for UTF-8 validity.
518     ///
519     /// [`&str`]: ../../std/primitive.str.html
520     ///
521     /// # Examples
522     ///
523     /// ```
524     /// use std::ffi::OsStr;
525     ///
526     /// let os_str = OsStr::new("foo");
527     /// assert_eq!(os_str.to_str(), Some("foo"));
528     /// ```
529     #[stable(feature = "rust1", since = "1.0.0")]
530     pub fn to_str(&self) -> Option<&str> {
531         self.inner.to_str()
532     }
533
534     /// Converts an `OsStr` to a [`Cow`]`<`[`str`]`>`.
535     ///
536     /// Any non-Unicode sequences are replaced with
537     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
538     ///
539     /// [`Cow`]: ../../std/borrow/enum.Cow.html
540     /// [`str`]: ../../std/primitive.str.html
541     /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
542     ///
543     /// # Examples
544     ///
545     /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
546     ///
547     /// ```
548     /// // Note, due to differences in how Unix and Windows represent strings,
549     /// // we are forced to complicate this example, setting up example `OsStr`s
550     /// // with different source data and via different platform extensions.
551     /// // Understand that in reality you could end up with such example invalid
552     /// // sequences simply through collecting user command line arguments, for
553     /// // example.
554     ///
555     /// #[cfg(any(unix, target_os = "redox"))] {
556     ///     use std::ffi::OsStr;
557     ///     use std::os::unix::ffi::OsStrExt;
558     ///
559     ///     // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
560     ///     // respectively. The value 0x80 is a lone continuation byte, invalid
561     ///     // in a UTF-8 sequence.
562     ///     let source = [0x66, 0x6f, 0x80, 0x6f];
563     ///     let os_str = OsStr::from_bytes(&source[..]);
564     ///
565     ///     assert_eq!(os_str.to_string_lossy(), "fo�o");
566     /// }
567     /// #[cfg(windows)] {
568     ///     use std::ffi::OsString;
569     ///     use std::os::windows::prelude::*;
570     ///
571     ///     // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
572     ///     // respectively. The value 0xD800 is a lone surrogate half, invalid
573     ///     // in a UTF-16 sequence.
574     ///     let source = [0x0066, 0x006f, 0xD800, 0x006f];
575     ///     let os_string = OsString::from_wide(&source[..]);
576     ///     let os_str = os_string.as_os_str();
577     ///
578     ///     assert_eq!(os_str.to_string_lossy(), "fo�o");
579     /// }
580     /// ```
581     #[stable(feature = "rust1", since = "1.0.0")]
582     pub fn to_string_lossy(&self) -> Cow<'_, str> {
583         self.inner.to_string_lossy()
584     }
585
586     /// Copies the slice into an owned [`OsString`].
587     ///
588     /// [`OsString`]: struct.OsString.html
589     ///
590     /// # Examples
591     ///
592     /// ```
593     /// use std::ffi::{OsStr, OsString};
594     ///
595     /// let os_str = OsStr::new("foo");
596     /// let os_string = os_str.to_os_string();
597     /// assert_eq!(os_string, OsString::from("foo"));
598     /// ```
599     #[stable(feature = "rust1", since = "1.0.0")]
600     pub fn to_os_string(&self) -> OsString {
601         OsString { inner: self.inner.to_owned() }
602     }
603
604     /// Checks whether the `OsStr` is empty.
605     ///
606     /// # Examples
607     ///
608     /// ```
609     /// use std::ffi::OsStr;
610     ///
611     /// let os_str = OsStr::new("");
612     /// assert!(os_str.is_empty());
613     ///
614     /// let os_str = OsStr::new("foo");
615     /// assert!(!os_str.is_empty());
616     /// ```
617     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
618     #[inline]
619     pub fn is_empty(&self) -> bool {
620         self.inner.inner.is_empty()
621     }
622
623     /// Returns the length of this `OsStr`.
624     ///
625     /// Note that this does **not** return the number of bytes in the string in
626     /// OS string form.
627     ///
628     /// The length returned is that of the underlying storage used by `OsStr`.
629     /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
630     /// store strings in a form best suited for cheap inter-conversion between
631     /// native-platform and Rust string forms, which may differ significantly
632     /// from both of them, including in storage size and encoding.
633     ///
634     /// This number is simply useful for passing to other methods, like
635     /// [`OsString::with_capacity`] to avoid reallocations.
636     ///
637     /// [`OsString`]: struct.OsString.html
638     /// [`OsString::with_capacity`]: struct.OsString.html#method.with_capacity
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// use std::ffi::OsStr;
644     ///
645     /// let os_str = OsStr::new("");
646     /// assert_eq!(os_str.len(), 0);
647     ///
648     /// let os_str = OsStr::new("foo");
649     /// assert_eq!(os_str.len(), 3);
650     /// ```
651     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
652     pub fn len(&self) -> usize {
653         self.inner.inner.len()
654     }
655
656     /// Converts a [`Box`]`<OsStr>` into an [`OsString`] without copying or allocating.
657     ///
658     /// [`Box`]: ../boxed/struct.Box.html
659     /// [`OsString`]: struct.OsString.html
660     #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
661     pub fn into_os_string(self: Box<OsStr>) -> OsString {
662         let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
663         OsString { inner: Buf::from_box(boxed) }
664     }
665
666     /// Gets the underlying byte representation.
667     ///
668     /// Note: it is *crucial* that this API is private, to avoid
669     /// revealing the internal, platform-specific encodings.
670     #[inline]
671     fn bytes(&self) -> &[u8] {
672         unsafe { &*(&self.inner as *const _ as *const [u8]) }
673     }
674 }
675
676 #[stable(feature = "box_from_os_str", since = "1.17.0")]
677 impl From<&OsStr> for Box<OsStr> {
678     fn from(s: &OsStr) -> Box<OsStr> {
679         let rw = Box::into_raw(s.inner.into_box()) as *mut OsStr;
680         unsafe { Box::from_raw(rw) }
681     }
682 }
683
684 #[stable(feature = "os_string_from_box", since = "1.18.0")]
685 impl From<Box<OsStr>> for OsString {
686     /// Converts a [`Box`]`<`[`OsStr`]`>` into a `OsString` without copying or
687     /// allocating.
688     ///
689     /// [`Box`]: ../boxed/struct.Box.html
690     /// [`OsStr`]: ../ffi/struct.OsStr.html
691     fn from(boxed: Box<OsStr>) -> OsString {
692         boxed.into_os_string()
693     }
694 }
695
696 #[stable(feature = "box_from_os_string", since = "1.20.0")]
697 impl From<OsString> for Box<OsStr> {
698     /// Converts a [`OsString`] into a [`Box`]`<OsStr>` without copying or allocating.
699     ///
700     /// [`Box`]: ../boxed/struct.Box.html
701     /// [`OsString`]: ../ffi/struct.OsString.html
702     fn from(s: OsString) -> Box<OsStr> {
703         s.into_boxed_os_str()
704     }
705 }
706
707 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
708 impl Clone for Box<OsStr> {
709     #[inline]
710     fn clone(&self) -> Self {
711         self.to_os_string().into_boxed_os_str()
712     }
713 }
714
715 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
716 impl From<OsString> for Arc<OsStr> {
717     /// Converts a [`OsString`] into a [`Arc`]`<OsStr>` without copying or allocating.
718     ///
719     /// [`Arc`]: ../sync/struct.Arc.html
720     /// [`OsString`]: ../ffi/struct.OsString.html
721     #[inline]
722     fn from(s: OsString) -> Arc<OsStr> {
723         let arc = s.inner.into_arc();
724         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
725     }
726 }
727
728 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
729 impl From<&OsStr> for Arc<OsStr> {
730     #[inline]
731     fn from(s: &OsStr) -> Arc<OsStr> {
732         let arc = s.inner.into_arc();
733         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
734     }
735 }
736
737 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
738 impl From<OsString> for Rc<OsStr> {
739     /// Converts a [`OsString`] into a [`Rc`]`<OsStr>` without copying or allocating.
740     ///
741     /// [`Rc`]: ../rc/struct.Rc.html
742     /// [`OsString`]: ../ffi/struct.OsString.html
743     #[inline]
744     fn from(s: OsString) -> Rc<OsStr> {
745         let rc = s.inner.into_rc();
746         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
747     }
748 }
749
750 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
751 impl From<&OsStr> for Rc<OsStr> {
752     #[inline]
753     fn from(s: &OsStr) -> Rc<OsStr> {
754         let rc = s.inner.into_rc();
755         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
756     }
757 }
758
759 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
760 impl<'a> From<OsString> for Cow<'a, OsStr> {
761     #[inline]
762     fn from(s: OsString) -> Cow<'a, OsStr> {
763         Cow::Owned(s)
764     }
765 }
766
767 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
768 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
769     #[inline]
770     fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
771         Cow::Borrowed(s)
772     }
773 }
774
775 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
776 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
777     #[inline]
778     fn from(s: &'a OsString) -> Cow<'a, OsStr> {
779         Cow::Borrowed(s.as_os_str())
780     }
781 }
782
783 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
784 impl<'a> From<Cow<'a, OsStr>> for OsString {
785     #[inline]
786     fn from(s: Cow<'a, OsStr>) -> Self {
787         s.into_owned()
788     }
789 }
790
791 #[stable(feature = "box_default_extra", since = "1.17.0")]
792 impl Default for Box<OsStr> {
793     fn default() -> Box<OsStr> {
794         let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
795         unsafe { Box::from_raw(rw) }
796     }
797 }
798
799 #[stable(feature = "osstring_default", since = "1.9.0")]
800 impl Default for &OsStr {
801     /// Creates an empty `OsStr`.
802     #[inline]
803     fn default() -> Self {
804         OsStr::new("")
805     }
806 }
807
808 #[stable(feature = "rust1", since = "1.0.0")]
809 impl PartialEq for OsStr {
810     #[inline]
811     fn eq(&self, other: &OsStr) -> bool {
812         self.bytes().eq(other.bytes())
813     }
814 }
815
816 #[stable(feature = "rust1", since = "1.0.0")]
817 impl PartialEq<str> for OsStr {
818     #[inline]
819     fn eq(&self, other: &str) -> bool {
820         *self == *OsStr::new(other)
821     }
822 }
823
824 #[stable(feature = "rust1", since = "1.0.0")]
825 impl PartialEq<OsStr> for str {
826     #[inline]
827     fn eq(&self, other: &OsStr) -> bool {
828         *other == *OsStr::new(self)
829     }
830 }
831
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl Eq for OsStr {}
834
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl PartialOrd for OsStr {
837     #[inline]
838     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
839         self.bytes().partial_cmp(other.bytes())
840     }
841     #[inline]
842     fn lt(&self, other: &OsStr) -> bool {
843         self.bytes().lt(other.bytes())
844     }
845     #[inline]
846     fn le(&self, other: &OsStr) -> bool {
847         self.bytes().le(other.bytes())
848     }
849     #[inline]
850     fn gt(&self, other: &OsStr) -> bool {
851         self.bytes().gt(other.bytes())
852     }
853     #[inline]
854     fn ge(&self, other: &OsStr) -> bool {
855         self.bytes().ge(other.bytes())
856     }
857 }
858
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl PartialOrd<str> for OsStr {
861     #[inline]
862     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
863         self.partial_cmp(OsStr::new(other))
864     }
865 }
866
867 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
868 // have more flexible coherence rules.
869
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl Ord for OsStr {
872     #[inline]
873     fn cmp(&self, other: &OsStr) -> cmp::Ordering {
874         self.bytes().cmp(other.bytes())
875     }
876 }
877
878 macro_rules! impl_cmp {
879     ($lhs:ty, $rhs: ty) => {
880         #[stable(feature = "cmp_os_str", since = "1.8.0")]
881         impl<'a, 'b> PartialEq<$rhs> for $lhs {
882             #[inline]
883             fn eq(&self, other: &$rhs) -> bool {
884                 <OsStr as PartialEq>::eq(self, other)
885             }
886         }
887
888         #[stable(feature = "cmp_os_str", since = "1.8.0")]
889         impl<'a, 'b> PartialEq<$lhs> for $rhs {
890             #[inline]
891             fn eq(&self, other: &$lhs) -> bool {
892                 <OsStr as PartialEq>::eq(self, other)
893             }
894         }
895
896         #[stable(feature = "cmp_os_str", since = "1.8.0")]
897         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
898             #[inline]
899             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
900                 <OsStr as PartialOrd>::partial_cmp(self, other)
901             }
902         }
903
904         #[stable(feature = "cmp_os_str", since = "1.8.0")]
905         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
906             #[inline]
907             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
908                 <OsStr as PartialOrd>::partial_cmp(self, other)
909             }
910         }
911     };
912 }
913
914 impl_cmp!(OsString, OsStr);
915 impl_cmp!(OsString, &'a OsStr);
916 impl_cmp!(Cow<'a, OsStr>, OsStr);
917 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
918 impl_cmp!(Cow<'a, OsStr>, OsString);
919
920 #[stable(feature = "rust1", since = "1.0.0")]
921 impl Hash for OsStr {
922     #[inline]
923     fn hash<H: Hasher>(&self, state: &mut H) {
924         self.bytes().hash(state)
925     }
926 }
927
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl fmt::Debug for OsStr {
930     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
931         fmt::Debug::fmt(&self.inner, formatter)
932     }
933 }
934
935 impl OsStr {
936     pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
937         fmt::Display::fmt(&self.inner, formatter)
938     }
939 }
940
941 #[stable(feature = "rust1", since = "1.0.0")]
942 impl Borrow<OsStr> for OsString {
943     fn borrow(&self) -> &OsStr {
944         &self[..]
945     }
946 }
947
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl ToOwned for OsStr {
950     type Owned = OsString;
951     fn to_owned(&self) -> OsString {
952         self.to_os_string()
953     }
954     fn clone_into(&self, target: &mut OsString) {
955         target.clear();
956         target.push(self);
957     }
958 }
959
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl AsRef<OsStr> for OsStr {
962     fn as_ref(&self) -> &OsStr {
963         self
964     }
965 }
966
967 #[stable(feature = "rust1", since = "1.0.0")]
968 impl AsRef<OsStr> for OsString {
969     fn as_ref(&self) -> &OsStr {
970         self
971     }
972 }
973
974 #[stable(feature = "rust1", since = "1.0.0")]
975 impl AsRef<OsStr> for str {
976     #[inline]
977     fn as_ref(&self) -> &OsStr {
978         OsStr::from_inner(Slice::from_str(self))
979     }
980 }
981
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl AsRef<OsStr> for String {
984     #[inline]
985     fn as_ref(&self) -> &OsStr {
986         (&**self).as_ref()
987     }
988 }
989
990 impl FromInner<Buf> for OsString {
991     fn from_inner(buf: Buf) -> OsString {
992         OsString { inner: buf }
993     }
994 }
995
996 impl IntoInner<Buf> for OsString {
997     fn into_inner(self) -> Buf {
998         self.inner
999     }
1000 }
1001
1002 impl AsInner<Slice> for OsStr {
1003     #[inline]
1004     fn as_inner(&self) -> &Slice {
1005         &self.inner
1006     }
1007 }
1008
1009 #[cfg(test)]
1010 mod tests {
1011     use super::*;
1012     use crate::sys_common::{AsInner, IntoInner};
1013
1014     use crate::rc::Rc;
1015     use crate::sync::Arc;
1016
1017     #[test]
1018     fn test_os_string_with_capacity() {
1019         let os_string = OsString::with_capacity(0);
1020         assert_eq!(0, os_string.inner.into_inner().capacity());
1021
1022         let os_string = OsString::with_capacity(10);
1023         assert_eq!(10, os_string.inner.into_inner().capacity());
1024
1025         let mut os_string = OsString::with_capacity(0);
1026         os_string.push("abc");
1027         assert!(os_string.inner.into_inner().capacity() >= 3);
1028     }
1029
1030     #[test]
1031     fn test_os_string_clear() {
1032         let mut os_string = OsString::from("abc");
1033         assert_eq!(3, os_string.inner.as_inner().len());
1034
1035         os_string.clear();
1036         assert_eq!(&os_string, "");
1037         assert_eq!(0, os_string.inner.as_inner().len());
1038     }
1039
1040     #[test]
1041     fn test_os_string_capacity() {
1042         let os_string = OsString::with_capacity(0);
1043         assert_eq!(0, os_string.capacity());
1044
1045         let os_string = OsString::with_capacity(10);
1046         assert_eq!(10, os_string.capacity());
1047
1048         let mut os_string = OsString::with_capacity(0);
1049         os_string.push("abc");
1050         assert!(os_string.capacity() >= 3);
1051     }
1052
1053     #[test]
1054     fn test_os_string_reserve() {
1055         let mut os_string = OsString::new();
1056         assert_eq!(os_string.capacity(), 0);
1057
1058         os_string.reserve(2);
1059         assert!(os_string.capacity() >= 2);
1060
1061         for _ in 0..16 {
1062             os_string.push("a");
1063         }
1064
1065         assert!(os_string.capacity() >= 16);
1066         os_string.reserve(16);
1067         assert!(os_string.capacity() >= 32);
1068
1069         os_string.push("a");
1070
1071         os_string.reserve(16);
1072         assert!(os_string.capacity() >= 33)
1073     }
1074
1075     #[test]
1076     fn test_os_string_reserve_exact() {
1077         let mut os_string = OsString::new();
1078         assert_eq!(os_string.capacity(), 0);
1079
1080         os_string.reserve_exact(2);
1081         assert!(os_string.capacity() >= 2);
1082
1083         for _ in 0..16 {
1084             os_string.push("a");
1085         }
1086
1087         assert!(os_string.capacity() >= 16);
1088         os_string.reserve_exact(16);
1089         assert!(os_string.capacity() >= 32);
1090
1091         os_string.push("a");
1092
1093         os_string.reserve_exact(16);
1094         assert!(os_string.capacity() >= 33)
1095     }
1096
1097     #[test]
1098     fn test_os_string_default() {
1099         let os_string: OsString = Default::default();
1100         assert_eq!("", &os_string);
1101     }
1102
1103     #[test]
1104     fn test_os_str_is_empty() {
1105         let mut os_string = OsString::new();
1106         assert!(os_string.is_empty());
1107
1108         os_string.push("abc");
1109         assert!(!os_string.is_empty());
1110
1111         os_string.clear();
1112         assert!(os_string.is_empty());
1113     }
1114
1115     #[test]
1116     fn test_os_str_len() {
1117         let mut os_string = OsString::new();
1118         assert_eq!(0, os_string.len());
1119
1120         os_string.push("abc");
1121         assert_eq!(3, os_string.len());
1122
1123         os_string.clear();
1124         assert_eq!(0, os_string.len());
1125     }
1126
1127     #[test]
1128     fn test_os_str_default() {
1129         let os_str: &OsStr = Default::default();
1130         assert_eq!("", os_str);
1131     }
1132
1133     #[test]
1134     fn into_boxed() {
1135         let orig = "Hello, world!";
1136         let os_str = OsStr::new(orig);
1137         let boxed: Box<OsStr> = Box::from(os_str);
1138         let os_string = os_str.to_owned().into_boxed_os_str().into_os_string();
1139         assert_eq!(os_str, &*boxed);
1140         assert_eq!(&*boxed, &*os_string);
1141         assert_eq!(&*os_string, os_str);
1142     }
1143
1144     #[test]
1145     fn boxed_default() {
1146         let boxed = <Box<OsStr>>::default();
1147         assert!(boxed.is_empty());
1148     }
1149
1150     #[test]
1151     fn test_os_str_clone_into() {
1152         let mut os_string = OsString::with_capacity(123);
1153         os_string.push("hello");
1154         let os_str = OsStr::new("bonjour");
1155         os_str.clone_into(&mut os_string);
1156         assert_eq!(os_str, os_string);
1157         assert!(os_string.capacity() >= 123);
1158     }
1159
1160     #[test]
1161     fn into_rc() {
1162         let orig = "Hello, world!";
1163         let os_str = OsStr::new(orig);
1164         let rc: Rc<OsStr> = Rc::from(os_str);
1165         let arc: Arc<OsStr> = Arc::from(os_str);
1166
1167         assert_eq!(&*rc, os_str);
1168         assert_eq!(&*arc, os_str);
1169
1170         let rc2: Rc<OsStr> = Rc::from(os_str.to_owned());
1171         let arc2: Arc<OsStr> = Arc::from(os_str.to_owned());
1172
1173         assert_eq!(&*rc2, os_str);
1174         assert_eq!(&*arc2, os_str);
1175     }
1176 }