]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/os_str.rs
Rollup merge of #67594 - oxalica:update-libc, r=Dylan-DPC
[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     pub fn is_empty(&self) -> bool {
619         self.inner.inner.is_empty()
620     }
621
622     /// Returns the length of this `OsStr`.
623     ///
624     /// Note that this does **not** return the number of bytes in the string in
625     /// OS string form.
626     ///
627     /// The length returned is that of the underlying storage used by `OsStr`.
628     /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
629     /// store strings in a form best suited for cheap inter-conversion between
630     /// native-platform and Rust string forms, which may differ significantly
631     /// from both of them, including in storage size and encoding.
632     ///
633     /// This number is simply useful for passing to other methods, like
634     /// [`OsString::with_capacity`] to avoid reallocations.
635     ///
636     /// [`OsString`]: struct.OsString.html
637     /// [`OsString::with_capacity`]: struct.OsString.html#method.with_capacity
638     ///
639     /// # Examples
640     ///
641     /// ```
642     /// use std::ffi::OsStr;
643     ///
644     /// let os_str = OsStr::new("");
645     /// assert_eq!(os_str.len(), 0);
646     ///
647     /// let os_str = OsStr::new("foo");
648     /// assert_eq!(os_str.len(), 3);
649     /// ```
650     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
651     pub fn len(&self) -> usize {
652         self.inner.inner.len()
653     }
654
655     /// Converts a [`Box`]`<OsStr>` into an [`OsString`] without copying or allocating.
656     ///
657     /// [`Box`]: ../boxed/struct.Box.html
658     /// [`OsString`]: struct.OsString.html
659     #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
660     pub fn into_os_string(self: Box<OsStr>) -> OsString {
661         let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
662         OsString { inner: Buf::from_box(boxed) }
663     }
664
665     /// Gets the underlying byte representation.
666     ///
667     /// Note: it is *crucial* that this API is private, to avoid
668     /// revealing the internal, platform-specific encodings.
669     #[inline]
670     fn bytes(&self) -> &[u8] {
671         unsafe { &*(&self.inner as *const _ as *const [u8]) }
672     }
673 }
674
675 #[stable(feature = "box_from_os_str", since = "1.17.0")]
676 impl From<&OsStr> for Box<OsStr> {
677     fn from(s: &OsStr) -> Box<OsStr> {
678         let rw = Box::into_raw(s.inner.into_box()) as *mut OsStr;
679         unsafe { Box::from_raw(rw) }
680     }
681 }
682
683 #[stable(feature = "os_string_from_box", since = "1.18.0")]
684 impl From<Box<OsStr>> for OsString {
685     /// Converts a [`Box`]`<`[`OsStr`]`>` into a `OsString` without copying or
686     /// allocating.
687     ///
688     /// [`Box`]: ../boxed/struct.Box.html
689     /// [`OsStr`]: ../ffi/struct.OsStr.html
690     fn from(boxed: Box<OsStr>) -> OsString {
691         boxed.into_os_string()
692     }
693 }
694
695 #[stable(feature = "box_from_os_string", since = "1.20.0")]
696 impl From<OsString> for Box<OsStr> {
697     /// Converts a [`OsString`] into a [`Box`]`<OsStr>` without copying or allocating.
698     ///
699     /// [`Box`]: ../boxed/struct.Box.html
700     /// [`OsString`]: ../ffi/struct.OsString.html
701     fn from(s: OsString) -> Box<OsStr> {
702         s.into_boxed_os_str()
703     }
704 }
705
706 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
707 impl Clone for Box<OsStr> {
708     #[inline]
709     fn clone(&self) -> Self {
710         self.to_os_string().into_boxed_os_str()
711     }
712 }
713
714 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
715 impl From<OsString> for Arc<OsStr> {
716     /// Converts a [`OsString`] into a [`Arc`]`<OsStr>` without copying or allocating.
717     ///
718     /// [`Arc`]: ../sync/struct.Arc.html
719     /// [`OsString`]: ../ffi/struct.OsString.html
720     #[inline]
721     fn from(s: OsString) -> Arc<OsStr> {
722         let arc = s.inner.into_arc();
723         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
724     }
725 }
726
727 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
728 impl From<&OsStr> for Arc<OsStr> {
729     #[inline]
730     fn from(s: &OsStr) -> Arc<OsStr> {
731         let arc = s.inner.into_arc();
732         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
733     }
734 }
735
736 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
737 impl From<OsString> for Rc<OsStr> {
738     /// Converts a [`OsString`] into a [`Rc`]`<OsStr>` without copying or allocating.
739     ///
740     /// [`Rc`]: ../rc/struct.Rc.html
741     /// [`OsString`]: ../ffi/struct.OsString.html
742     #[inline]
743     fn from(s: OsString) -> Rc<OsStr> {
744         let rc = s.inner.into_rc();
745         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
746     }
747 }
748
749 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
750 impl From<&OsStr> for Rc<OsStr> {
751     #[inline]
752     fn from(s: &OsStr) -> Rc<OsStr> {
753         let rc = s.inner.into_rc();
754         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
755     }
756 }
757
758 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
759 impl<'a> From<OsString> for Cow<'a, OsStr> {
760     #[inline]
761     fn from(s: OsString) -> Cow<'a, OsStr> {
762         Cow::Owned(s)
763     }
764 }
765
766 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
767 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
768     #[inline]
769     fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
770         Cow::Borrowed(s)
771     }
772 }
773
774 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
775 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
776     #[inline]
777     fn from(s: &'a OsString) -> Cow<'a, OsStr> {
778         Cow::Borrowed(s.as_os_str())
779     }
780 }
781
782 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
783 impl<'a> From<Cow<'a, OsStr>> for OsString {
784     #[inline]
785     fn from(s: Cow<'a, OsStr>) -> Self {
786         s.into_owned()
787     }
788 }
789
790 #[stable(feature = "box_default_extra", since = "1.17.0")]
791 impl Default for Box<OsStr> {
792     fn default() -> Box<OsStr> {
793         let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
794         unsafe { Box::from_raw(rw) }
795     }
796 }
797
798 #[stable(feature = "osstring_default", since = "1.9.0")]
799 impl Default for &OsStr {
800     /// Creates an empty `OsStr`.
801     #[inline]
802     fn default() -> Self {
803         OsStr::new("")
804     }
805 }
806
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl PartialEq for OsStr {
809     #[inline]
810     fn eq(&self, other: &OsStr) -> bool {
811         self.bytes().eq(other.bytes())
812     }
813 }
814
815 #[stable(feature = "rust1", since = "1.0.0")]
816 impl PartialEq<str> for OsStr {
817     #[inline]
818     fn eq(&self, other: &str) -> bool {
819         *self == *OsStr::new(other)
820     }
821 }
822
823 #[stable(feature = "rust1", since = "1.0.0")]
824 impl PartialEq<OsStr> for str {
825     #[inline]
826     fn eq(&self, other: &OsStr) -> bool {
827         *other == *OsStr::new(self)
828     }
829 }
830
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl Eq for OsStr {}
833
834 #[stable(feature = "rust1", since = "1.0.0")]
835 impl PartialOrd for OsStr {
836     #[inline]
837     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
838         self.bytes().partial_cmp(other.bytes())
839     }
840     #[inline]
841     fn lt(&self, other: &OsStr) -> bool {
842         self.bytes().lt(other.bytes())
843     }
844     #[inline]
845     fn le(&self, other: &OsStr) -> bool {
846         self.bytes().le(other.bytes())
847     }
848     #[inline]
849     fn gt(&self, other: &OsStr) -> bool {
850         self.bytes().gt(other.bytes())
851     }
852     #[inline]
853     fn ge(&self, other: &OsStr) -> bool {
854         self.bytes().ge(other.bytes())
855     }
856 }
857
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl PartialOrd<str> for OsStr {
860     #[inline]
861     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
862         self.partial_cmp(OsStr::new(other))
863     }
864 }
865
866 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
867 // have more flexible coherence rules.
868
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl Ord for OsStr {
871     #[inline]
872     fn cmp(&self, other: &OsStr) -> cmp::Ordering {
873         self.bytes().cmp(other.bytes())
874     }
875 }
876
877 macro_rules! impl_cmp {
878     ($lhs:ty, $rhs: ty) => {
879         #[stable(feature = "cmp_os_str", since = "1.8.0")]
880         impl<'a, 'b> PartialEq<$rhs> for $lhs {
881             #[inline]
882             fn eq(&self, other: &$rhs) -> bool {
883                 <OsStr as PartialEq>::eq(self, other)
884             }
885         }
886
887         #[stable(feature = "cmp_os_str", since = "1.8.0")]
888         impl<'a, 'b> PartialEq<$lhs> for $rhs {
889             #[inline]
890             fn eq(&self, other: &$lhs) -> bool {
891                 <OsStr as PartialEq>::eq(self, other)
892             }
893         }
894
895         #[stable(feature = "cmp_os_str", since = "1.8.0")]
896         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
897             #[inline]
898             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
899                 <OsStr as PartialOrd>::partial_cmp(self, other)
900             }
901         }
902
903         #[stable(feature = "cmp_os_str", since = "1.8.0")]
904         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
905             #[inline]
906             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
907                 <OsStr as PartialOrd>::partial_cmp(self, other)
908             }
909         }
910     };
911 }
912
913 impl_cmp!(OsString, OsStr);
914 impl_cmp!(OsString, &'a OsStr);
915 impl_cmp!(Cow<'a, OsStr>, OsStr);
916 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
917 impl_cmp!(Cow<'a, OsStr>, OsString);
918
919 #[stable(feature = "rust1", since = "1.0.0")]
920 impl Hash for OsStr {
921     #[inline]
922     fn hash<H: Hasher>(&self, state: &mut H) {
923         self.bytes().hash(state)
924     }
925 }
926
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl fmt::Debug for OsStr {
929     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
930         fmt::Debug::fmt(&self.inner, formatter)
931     }
932 }
933
934 impl OsStr {
935     pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
936         fmt::Display::fmt(&self.inner, formatter)
937     }
938 }
939
940 #[stable(feature = "rust1", since = "1.0.0")]
941 impl Borrow<OsStr> for OsString {
942     fn borrow(&self) -> &OsStr {
943         &self[..]
944     }
945 }
946
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl ToOwned for OsStr {
949     type Owned = OsString;
950     fn to_owned(&self) -> OsString {
951         self.to_os_string()
952     }
953     fn clone_into(&self, target: &mut OsString) {
954         target.clear();
955         target.push(self);
956     }
957 }
958
959 #[stable(feature = "rust1", since = "1.0.0")]
960 impl AsRef<OsStr> for OsStr {
961     fn as_ref(&self) -> &OsStr {
962         self
963     }
964 }
965
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl AsRef<OsStr> for OsString {
968     fn as_ref(&self) -> &OsStr {
969         self
970     }
971 }
972
973 #[stable(feature = "rust1", since = "1.0.0")]
974 impl AsRef<OsStr> for str {
975     #[inline]
976     fn as_ref(&self) -> &OsStr {
977         OsStr::from_inner(Slice::from_str(self))
978     }
979 }
980
981 #[stable(feature = "rust1", since = "1.0.0")]
982 impl AsRef<OsStr> for String {
983     #[inline]
984     fn as_ref(&self) -> &OsStr {
985         (&**self).as_ref()
986     }
987 }
988
989 impl FromInner<Buf> for OsString {
990     fn from_inner(buf: Buf) -> OsString {
991         OsString { inner: buf }
992     }
993 }
994
995 impl IntoInner<Buf> for OsString {
996     fn into_inner(self) -> Buf {
997         self.inner
998     }
999 }
1000
1001 impl AsInner<Slice> for OsStr {
1002     #[inline]
1003     fn as_inner(&self) -> &Slice {
1004         &self.inner
1005     }
1006 }
1007
1008 #[cfg(test)]
1009 mod tests {
1010     use super::*;
1011     use crate::sys_common::{AsInner, IntoInner};
1012
1013     use crate::rc::Rc;
1014     use crate::sync::Arc;
1015
1016     #[test]
1017     fn test_os_string_with_capacity() {
1018         let os_string = OsString::with_capacity(0);
1019         assert_eq!(0, os_string.inner.into_inner().capacity());
1020
1021         let os_string = OsString::with_capacity(10);
1022         assert_eq!(10, os_string.inner.into_inner().capacity());
1023
1024         let mut os_string = OsString::with_capacity(0);
1025         os_string.push("abc");
1026         assert!(os_string.inner.into_inner().capacity() >= 3);
1027     }
1028
1029     #[test]
1030     fn test_os_string_clear() {
1031         let mut os_string = OsString::from("abc");
1032         assert_eq!(3, os_string.inner.as_inner().len());
1033
1034         os_string.clear();
1035         assert_eq!(&os_string, "");
1036         assert_eq!(0, os_string.inner.as_inner().len());
1037     }
1038
1039     #[test]
1040     fn test_os_string_capacity() {
1041         let os_string = OsString::with_capacity(0);
1042         assert_eq!(0, os_string.capacity());
1043
1044         let os_string = OsString::with_capacity(10);
1045         assert_eq!(10, os_string.capacity());
1046
1047         let mut os_string = OsString::with_capacity(0);
1048         os_string.push("abc");
1049         assert!(os_string.capacity() >= 3);
1050     }
1051
1052     #[test]
1053     fn test_os_string_reserve() {
1054         let mut os_string = OsString::new();
1055         assert_eq!(os_string.capacity(), 0);
1056
1057         os_string.reserve(2);
1058         assert!(os_string.capacity() >= 2);
1059
1060         for _ in 0..16 {
1061             os_string.push("a");
1062         }
1063
1064         assert!(os_string.capacity() >= 16);
1065         os_string.reserve(16);
1066         assert!(os_string.capacity() >= 32);
1067
1068         os_string.push("a");
1069
1070         os_string.reserve(16);
1071         assert!(os_string.capacity() >= 33)
1072     }
1073
1074     #[test]
1075     fn test_os_string_reserve_exact() {
1076         let mut os_string = OsString::new();
1077         assert_eq!(os_string.capacity(), 0);
1078
1079         os_string.reserve_exact(2);
1080         assert!(os_string.capacity() >= 2);
1081
1082         for _ in 0..16 {
1083             os_string.push("a");
1084         }
1085
1086         assert!(os_string.capacity() >= 16);
1087         os_string.reserve_exact(16);
1088         assert!(os_string.capacity() >= 32);
1089
1090         os_string.push("a");
1091
1092         os_string.reserve_exact(16);
1093         assert!(os_string.capacity() >= 33)
1094     }
1095
1096     #[test]
1097     fn test_os_string_default() {
1098         let os_string: OsString = Default::default();
1099         assert_eq!("", &os_string);
1100     }
1101
1102     #[test]
1103     fn test_os_str_is_empty() {
1104         let mut os_string = OsString::new();
1105         assert!(os_string.is_empty());
1106
1107         os_string.push("abc");
1108         assert!(!os_string.is_empty());
1109
1110         os_string.clear();
1111         assert!(os_string.is_empty());
1112     }
1113
1114     #[test]
1115     fn test_os_str_len() {
1116         let mut os_string = OsString::new();
1117         assert_eq!(0, os_string.len());
1118
1119         os_string.push("abc");
1120         assert_eq!(3, os_string.len());
1121
1122         os_string.clear();
1123         assert_eq!(0, os_string.len());
1124     }
1125
1126     #[test]
1127     fn test_os_str_default() {
1128         let os_str: &OsStr = Default::default();
1129         assert_eq!("", os_str);
1130     }
1131
1132     #[test]
1133     fn into_boxed() {
1134         let orig = "Hello, world!";
1135         let os_str = OsStr::new(orig);
1136         let boxed: Box<OsStr> = Box::from(os_str);
1137         let os_string = os_str.to_owned().into_boxed_os_str().into_os_string();
1138         assert_eq!(os_str, &*boxed);
1139         assert_eq!(&*boxed, &*os_string);
1140         assert_eq!(&*os_string, os_str);
1141     }
1142
1143     #[test]
1144     fn boxed_default() {
1145         let boxed = <Box<OsStr>>::default();
1146         assert!(boxed.is_empty());
1147     }
1148
1149     #[test]
1150     fn test_os_str_clone_into() {
1151         let mut os_string = OsString::with_capacity(123);
1152         os_string.push("hello");
1153         let os_str = OsStr::new("bonjour");
1154         os_str.clone_into(&mut os_string);
1155         assert_eq!(os_str, os_string);
1156         assert!(os_string.capacity() >= 123);
1157     }
1158
1159     #[test]
1160     fn into_rc() {
1161         let orig = "Hello, world!";
1162         let os_str = OsStr::new(orig);
1163         let rc: Rc<OsStr> = Rc::from(os_str);
1164         let arc: Arc<OsStr> = Arc::from(os_str);
1165
1166         assert_eq!(&*rc, os_str);
1167         assert_eq!(&*arc, os_str);
1168
1169         let rc2: Rc<OsStr> = Rc::from(os_str.to_owned());
1170         let arc2: Arc<OsStr> = Arc::from(os_str.to_owned());
1171
1172         assert_eq!(&*rc2, os_str);
1173         assert_eq!(&*arc2, os_str);
1174     }
1175 }