]> git.lizzy.rs Git - rust.git/blob - library/std/src/ffi/os_str.rs
Fix documentation for with_capacity and reserve families of methods
[rust.git] / library / std / src / ffi / os_str.rs
1 #[cfg(test)]
2 mod tests;
3
4 use crate::borrow::{Borrow, Cow};
5 use crate::cmp;
6 use crate::collections::TryReserveError;
7 use crate::fmt;
8 use crate::hash::{Hash, Hasher};
9 use crate::iter::Extend;
10 use crate::ops;
11 use crate::rc::Rc;
12 use crate::str::FromStr;
13 use crate::sync::Arc;
14
15 use crate::sys::os_str::{Buf, Slice};
16 use crate::sys_common::{AsInner, FromInner, IntoInner};
17
18 /// A type that can represent owned, mutable platform-native strings, but is
19 /// cheaply inter-convertible with Rust strings.
20 ///
21 /// The need for this type arises from the fact that:
22 ///
23 /// * On Unix systems, strings are often arbitrary sequences of non-zero
24 ///   bytes, in many cases interpreted as UTF-8.
25 ///
26 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
27 ///   values, interpreted as UTF-16 when it is valid to do so.
28 ///
29 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
30 ///
31 /// `OsString` and [`OsStr`] bridge this gap by simultaneously representing Rust
32 /// and platform-native string values, and in particular allowing a Rust string
33 /// to be converted into an "OS" string with no cost if possible. A consequence
34 /// of this is that `OsString` instances are *not* `NUL` terminated; in order
35 /// to pass to e.g., Unix system call, you should create a [`CStr`].
36 ///
37 /// `OsString` is to <code>&[OsStr]</code> as [`String`] is to <code>&[str]</code>: the former
38 /// in each pair are owned strings; the latter are borrowed
39 /// references.
40 ///
41 /// Note, `OsString` and [`OsStr`] internally do not necessarily hold strings in
42 /// the form native to the platform; While on Unix, strings are stored as a
43 /// sequence of 8-bit values, on Windows, where strings are 16-bit value based
44 /// as just discussed, strings are also actually stored as a sequence of 8-bit
45 /// values, encoded in a less-strict variant of UTF-8. This is useful to
46 /// understand when handling capacity and length values.
47 ///
48 /// # Capacity of `OsString`
49 ///
50 /// Capacity uses units of UTF-8 bytes for OS strings which were created from valid unicode, and
51 /// uses units of bytes in an unspecified encoding for other contents. On a given target, all
52 /// `OsString` and `OsStr` values use the same units for capacity, so the following will work:
53 /// ```
54 /// use std::ffi::{OsStr, OsString};
55 ///
56 /// fn concat_os_strings(a: &OsStr, b: &OsStr) -> OsString {
57 ///     let mut ret = OsString::with_capacity(a.len() + b.len()); // This will allocate
58 ///     ret.push(a); // This will not allocate further
59 ///     ret.push(b); // This will not allocate further
60 ///     ret
61 /// }
62 /// ```
63 ///
64 /// # Creating an `OsString`
65 ///
66 /// **From a Rust string**: `OsString` implements
67 /// <code>[From]<[String]></code>, so you can use <code>my_string.[into]\()</code> to
68 /// create an `OsString` from a normal Rust string.
69 ///
70 /// **From slices:** Just like you can start with an empty Rust
71 /// [`String`] and then [`String::push_str`] some <code>&[str]</code>
72 /// sub-string slices into it, you can create an empty `OsString` with
73 /// the [`OsString::new`] method and then push string slices into it with the
74 /// [`OsString::push`] method.
75 ///
76 /// # Extracting a borrowed reference to the whole OS string
77 ///
78 /// You can use the [`OsString::as_os_str`] method to get an <code>&[OsStr]</code> from
79 /// an `OsString`; this is effectively a borrowed reference to the
80 /// whole string.
81 ///
82 /// # Conversions
83 ///
84 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
85 /// the traits which `OsString` implements for [conversions] from/to native representations.
86 ///
87 /// [`CStr`]: crate::ffi::CStr
88 /// [conversions]: super#conversions
89 /// [into]: Into::into
90 #[cfg_attr(not(test), rustc_diagnostic_item = "OsString")]
91 #[stable(feature = "rust1", since = "1.0.0")]
92 pub struct OsString {
93     inner: Buf,
94 }
95
96 /// Allows extension traits within `std`.
97 #[unstable(feature = "sealed", issue = "none")]
98 impl crate::sealed::Sealed for OsString {}
99
100 /// Borrowed reference to an OS string (see [`OsString`]).
101 ///
102 /// This type represents a borrowed reference to a string in the operating system's preferred
103 /// representation.
104 ///
105 /// `&OsStr` is to [`OsString`] as <code>&[str]</code> is to [`String`]: the
106 /// former in each pair are borrowed references; the latter are owned strings.
107 ///
108 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
109 /// the traits which `OsStr` implements for [conversions] from/to native representations.
110 ///
111 /// [conversions]: super#conversions
112 #[cfg_attr(not(test), rustc_diagnostic_item = "OsStr")]
113 #[stable(feature = "rust1", since = "1.0.0")]
114 // FIXME:
115 // `OsStr::from_inner` current implementation relies
116 // on `OsStr` being layout-compatible with `Slice`.
117 // When attribute privacy is implemented, `OsStr` should be annotated as `#[repr(transparent)]`.
118 // Anyway, `OsStr` representation and layout are considered implementation details, are
119 // not documented and must not be relied upon.
120 pub struct OsStr {
121     inner: Slice,
122 }
123
124 /// Allows extension traits within `std`.
125 #[unstable(feature = "sealed", issue = "none")]
126 impl crate::sealed::Sealed for OsStr {}
127
128 impl OsString {
129     /// Constructs a new empty `OsString`.
130     ///
131     /// # Examples
132     ///
133     /// ```
134     /// use std::ffi::OsString;
135     ///
136     /// let os_string = OsString::new();
137     /// ```
138     #[stable(feature = "rust1", since = "1.0.0")]
139     #[must_use]
140     #[inline]
141     pub fn new() -> OsString {
142         OsString { inner: Buf::from_string(String::new()) }
143     }
144
145     /// Converts to an [`OsStr`] slice.
146     ///
147     /// # Examples
148     ///
149     /// ```
150     /// use std::ffi::{OsString, OsStr};
151     ///
152     /// let os_string = OsString::from("foo");
153     /// let os_str = OsStr::new("foo");
154     /// assert_eq!(os_string.as_os_str(), os_str);
155     /// ```
156     #[stable(feature = "rust1", since = "1.0.0")]
157     #[must_use]
158     #[inline]
159     pub fn as_os_str(&self) -> &OsStr {
160         self
161     }
162
163     /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
164     ///
165     /// On failure, ownership of the original `OsString` is returned.
166     ///
167     /// # Examples
168     ///
169     /// ```
170     /// use std::ffi::OsString;
171     ///
172     /// let os_string = OsString::from("foo");
173     /// let string = os_string.into_string();
174     /// assert_eq!(string, Ok(String::from("foo")));
175     /// ```
176     #[stable(feature = "rust1", since = "1.0.0")]
177     #[inline]
178     pub fn into_string(self) -> Result<String, OsString> {
179         self.inner.into_string().map_err(|buf| OsString { inner: buf })
180     }
181
182     /// Extends the string with the given <code>&[OsStr]</code> slice.
183     ///
184     /// # Examples
185     ///
186     /// ```
187     /// use std::ffi::OsString;
188     ///
189     /// let mut os_string = OsString::from("foo");
190     /// os_string.push("bar");
191     /// assert_eq!(&os_string, "foobar");
192     /// ```
193     #[stable(feature = "rust1", since = "1.0.0")]
194     #[inline]
195     pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
196         self.inner.push_slice(&s.as_ref().inner)
197     }
198
199     /// Creates a new `OsString` with at least the given capacity.
200     ///
201     /// The string will be able to hold at least `capacity` length units of other
202     /// OS strings without reallocating. This method is allowed to allocate for
203     /// more units than `capacity`. If `capacity` is 0, the string will not
204     /// allocate.
205     ///
206     /// See the main `OsString` documentation information about encoding and capacity units.
207     ///
208     /// # Examples
209     ///
210     /// ```
211     /// use std::ffi::OsString;
212     ///
213     /// let mut os_string = OsString::with_capacity(10);
214     /// let capacity = os_string.capacity();
215     ///
216     /// // This push is done without reallocating
217     /// os_string.push("foo");
218     ///
219     /// assert_eq!(capacity, os_string.capacity());
220     /// ```
221     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
222     #[must_use]
223     #[inline]
224     pub fn with_capacity(capacity: usize) -> OsString {
225         OsString { inner: Buf::with_capacity(capacity) }
226     }
227
228     /// Truncates the `OsString` to zero length.
229     ///
230     /// # Examples
231     ///
232     /// ```
233     /// use std::ffi::OsString;
234     ///
235     /// let mut os_string = OsString::from("foo");
236     /// assert_eq!(&os_string, "foo");
237     ///
238     /// os_string.clear();
239     /// assert_eq!(&os_string, "");
240     /// ```
241     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
242     #[inline]
243     pub fn clear(&mut self) {
244         self.inner.clear()
245     }
246
247     /// Returns the capacity this `OsString` can hold without reallocating.
248     ///
249     /// See the main `OsString` documentation information about encoding and capacity units.
250     ///
251     /// # Examples
252     ///
253     /// ```
254     /// use std::ffi::OsString;
255     ///
256     /// let os_string = OsString::with_capacity(10);
257     /// assert!(os_string.capacity() >= 10);
258     /// ```
259     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
260     #[must_use]
261     #[inline]
262     pub fn capacity(&self) -> usize {
263         self.inner.capacity()
264     }
265
266     /// Reserves capacity for at least `additional` more capacity to be inserted
267     /// in the given `OsString`. Does nothing if the capacity is
268     /// already sufficient.
269     ///
270     /// The collection may reserve more space to speculatively avoid frequent reallocations.
271     ///
272     /// See the main `OsString` documentation information about encoding and capacity units.
273     ///
274     /// # Examples
275     ///
276     /// ```
277     /// use std::ffi::OsString;
278     ///
279     /// let mut s = OsString::new();
280     /// s.reserve(10);
281     /// assert!(s.capacity() >= 10);
282     /// ```
283     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
284     #[inline]
285     pub fn reserve(&mut self, additional: usize) {
286         self.inner.reserve(additional)
287     }
288
289     /// Tries to reserve capacity for at least `additional` more length units
290     /// in the given `OsString`. The string may reserve more space to speculatively avoid
291     /// frequent reallocations. After calling `try_reserve`, capacity will be
292     /// greater than or equal to `self.len() + additional` if it returns `Ok(())`.
293     /// Does nothing if capacity is already sufficient.
294     ///
295     /// See the main `OsString` documentation information about encoding and capacity units.
296     ///
297     /// # Errors
298     ///
299     /// If the capacity overflows, or the allocator reports a failure, then an error
300     /// is returned.
301     ///
302     /// # Examples
303     ///
304     /// ```
305     /// use std::ffi::{OsStr, OsString};
306     /// use std::collections::TryReserveError;
307     ///
308     /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
309     ///     let mut s = OsString::new();
310     ///
311     ///     // Pre-reserve the memory, exiting if we can't
312     ///     s.try_reserve(OsStr::new(data).len())?;
313     ///
314     ///     // Now we know this can't OOM in the middle of our complex work
315     ///     s.push(data);
316     ///
317     ///     Ok(s)
318     /// }
319     /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
320     /// ```
321     #[stable(feature = "try_reserve_2", since = "1.63.0")]
322     #[inline]
323     pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
324         self.inner.try_reserve(additional)
325     }
326
327     /// Reserves the minimum capacity for at least `additional` more capacity to
328     /// be inserted in the given `OsString`. Does nothing if the capacity is
329     /// already sufficient.
330     ///
331     /// Note that the allocator may give the collection more space than it
332     /// requests. Therefore, capacity can not be relied upon to be precisely
333     /// minimal. Prefer [`reserve`] if future insertions are expected.
334     ///
335     /// [`reserve`]: OsString::reserve
336     ///
337     /// See the main `OsString` documentation information about encoding and capacity units.
338     ///
339     /// # Examples
340     ///
341     /// ```
342     /// use std::ffi::OsString;
343     ///
344     /// let mut s = OsString::new();
345     /// s.reserve_exact(10);
346     /// assert!(s.capacity() >= 10);
347     /// ```
348     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
349     #[inline]
350     pub fn reserve_exact(&mut self, additional: usize) {
351         self.inner.reserve_exact(additional)
352     }
353
354     /// Tries to reserve the minimum capacity for at least `additional`
355     /// more length units in the given `OsString`. After calling
356     /// `try_reserve_exact`, capacity will be greater than or equal to
357     /// `self.len() + additional` if it returns `Ok(())`.
358     /// Does nothing if the capacity is already sufficient.
359     ///
360     /// Note that the allocator may give the `OsString` more space than it
361     /// requests. Therefore, capacity can not be relied upon to be precisely
362     /// minimal. Prefer [`try_reserve`] if future insertions are expected.
363     ///
364     /// [`try_reserve`]: OsString::try_reserve
365     ///
366     /// See the main `OsString` documentation information about encoding and capacity units.
367     ///
368     /// # Errors
369     ///
370     /// If the capacity overflows, or the allocator reports a failure, then an error
371     /// is returned.
372     ///
373     /// # Examples
374     ///
375     /// ```
376     /// use std::ffi::{OsStr, OsString};
377     /// use std::collections::TryReserveError;
378     ///
379     /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
380     ///     let mut s = OsString::new();
381     ///
382     ///     // Pre-reserve the memory, exiting if we can't
383     ///     s.try_reserve_exact(OsStr::new(data).len())?;
384     ///
385     ///     // Now we know this can't OOM in the middle of our complex work
386     ///     s.push(data);
387     ///
388     ///     Ok(s)
389     /// }
390     /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
391     /// ```
392     #[stable(feature = "try_reserve_2", since = "1.63.0")]
393     #[inline]
394     pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
395         self.inner.try_reserve_exact(additional)
396     }
397
398     /// Shrinks the capacity of the `OsString` to match its length.
399     ///
400     /// See the main `OsString` documentation information about encoding and capacity units.
401     ///
402     /// # Examples
403     ///
404     /// ```
405     /// use std::ffi::OsString;
406     ///
407     /// let mut s = OsString::from("foo");
408     ///
409     /// s.reserve(100);
410     /// assert!(s.capacity() >= 100);
411     ///
412     /// s.shrink_to_fit();
413     /// assert_eq!(3, s.capacity());
414     /// ```
415     #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
416     #[inline]
417     pub fn shrink_to_fit(&mut self) {
418         self.inner.shrink_to_fit()
419     }
420
421     /// Shrinks the capacity of the `OsString` with a lower bound.
422     ///
423     /// The capacity will remain at least as large as both the length
424     /// and the supplied value.
425     ///
426     /// If the current capacity is less than the lower limit, this is a no-op.
427     ///
428     /// See the main `OsString` documentation information about encoding and capacity units.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// use std::ffi::OsString;
434     ///
435     /// let mut s = OsString::from("foo");
436     ///
437     /// s.reserve(100);
438     /// assert!(s.capacity() >= 100);
439     ///
440     /// s.shrink_to(10);
441     /// assert!(s.capacity() >= 10);
442     /// s.shrink_to(0);
443     /// assert!(s.capacity() >= 3);
444     /// ```
445     #[inline]
446     #[stable(feature = "shrink_to", since = "1.56.0")]
447     pub fn shrink_to(&mut self, min_capacity: usize) {
448         self.inner.shrink_to(min_capacity)
449     }
450
451     /// Converts this `OsString` into a boxed [`OsStr`].
452     ///
453     /// # Examples
454     ///
455     /// ```
456     /// use std::ffi::{OsString, OsStr};
457     ///
458     /// let s = OsString::from("hello");
459     ///
460     /// let b: Box<OsStr> = s.into_boxed_os_str();
461     /// ```
462     #[must_use = "`self` will be dropped if the result is not used"]
463     #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
464     pub fn into_boxed_os_str(self) -> Box<OsStr> {
465         let rw = Box::into_raw(self.inner.into_box()) as *mut OsStr;
466         unsafe { Box::from_raw(rw) }
467     }
468 }
469
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl From<String> for OsString {
472     /// Converts a [`String`] into an [`OsString`].
473     ///
474     /// This conversion does not allocate or copy memory.
475     #[inline]
476     fn from(s: String) -> OsString {
477         OsString { inner: Buf::from_string(s) }
478     }
479 }
480
481 #[stable(feature = "rust1", since = "1.0.0")]
482 impl<T: ?Sized + AsRef<OsStr>> From<&T> for OsString {
483     /// Copies any value implementing <code>[AsRef]&lt;[OsStr]&gt;</code>
484     /// into a newly allocated [`OsString`].
485     fn from(s: &T) -> OsString {
486         s.as_ref().to_os_string()
487     }
488 }
489
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl ops::Index<ops::RangeFull> for OsString {
492     type Output = OsStr;
493
494     #[inline]
495     fn index(&self, _index: ops::RangeFull) -> &OsStr {
496         OsStr::from_inner(self.inner.as_slice())
497     }
498 }
499
500 #[stable(feature = "mut_osstr", since = "1.44.0")]
501 impl ops::IndexMut<ops::RangeFull> for OsString {
502     #[inline]
503     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut OsStr {
504         OsStr::from_inner_mut(self.inner.as_mut_slice())
505     }
506 }
507
508 #[stable(feature = "rust1", since = "1.0.0")]
509 impl ops::Deref for OsString {
510     type Target = OsStr;
511
512     #[inline]
513     fn deref(&self) -> &OsStr {
514         &self[..]
515     }
516 }
517
518 #[stable(feature = "mut_osstr", since = "1.44.0")]
519 impl ops::DerefMut for OsString {
520     #[inline]
521     fn deref_mut(&mut self) -> &mut OsStr {
522         &mut self[..]
523     }
524 }
525
526 #[stable(feature = "osstring_default", since = "1.9.0")]
527 impl Default for OsString {
528     /// Constructs an empty `OsString`.
529     #[inline]
530     fn default() -> OsString {
531         OsString::new()
532     }
533 }
534
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl Clone for OsString {
537     #[inline]
538     fn clone(&self) -> Self {
539         OsString { inner: self.inner.clone() }
540     }
541
542     #[inline]
543     fn clone_from(&mut self, source: &Self) {
544         self.inner.clone_from(&source.inner)
545     }
546 }
547
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl fmt::Debug for OsString {
550     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
551         fmt::Debug::fmt(&**self, formatter)
552     }
553 }
554
555 #[stable(feature = "rust1", since = "1.0.0")]
556 impl PartialEq for OsString {
557     #[inline]
558     fn eq(&self, other: &OsString) -> bool {
559         &**self == &**other
560     }
561 }
562
563 #[stable(feature = "rust1", since = "1.0.0")]
564 impl PartialEq<str> for OsString {
565     #[inline]
566     fn eq(&self, other: &str) -> bool {
567         &**self == other
568     }
569 }
570
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl PartialEq<OsString> for str {
573     #[inline]
574     fn eq(&self, other: &OsString) -> bool {
575         &**other == self
576     }
577 }
578
579 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
580 impl PartialEq<&str> for OsString {
581     #[inline]
582     fn eq(&self, other: &&str) -> bool {
583         **self == **other
584     }
585 }
586
587 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
588 impl<'a> PartialEq<OsString> for &'a str {
589     #[inline]
590     fn eq(&self, other: &OsString) -> bool {
591         **other == **self
592     }
593 }
594
595 #[stable(feature = "rust1", since = "1.0.0")]
596 impl Eq for OsString {}
597
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl PartialOrd for OsString {
600     #[inline]
601     fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
602         (&**self).partial_cmp(&**other)
603     }
604     #[inline]
605     fn lt(&self, other: &OsString) -> bool {
606         &**self < &**other
607     }
608     #[inline]
609     fn le(&self, other: &OsString) -> bool {
610         &**self <= &**other
611     }
612     #[inline]
613     fn gt(&self, other: &OsString) -> bool {
614         &**self > &**other
615     }
616     #[inline]
617     fn ge(&self, other: &OsString) -> bool {
618         &**self >= &**other
619     }
620 }
621
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl PartialOrd<str> for OsString {
624     #[inline]
625     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
626         (&**self).partial_cmp(other)
627     }
628 }
629
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl Ord for OsString {
632     #[inline]
633     fn cmp(&self, other: &OsString) -> cmp::Ordering {
634         (&**self).cmp(&**other)
635     }
636 }
637
638 #[stable(feature = "rust1", since = "1.0.0")]
639 impl Hash for OsString {
640     #[inline]
641     fn hash<H: Hasher>(&self, state: &mut H) {
642         (&**self).hash(state)
643     }
644 }
645
646 impl OsStr {
647     /// Coerces into an `OsStr` slice.
648     ///
649     /// # Examples
650     ///
651     /// ```
652     /// use std::ffi::OsStr;
653     ///
654     /// let os_str = OsStr::new("foo");
655     /// ```
656     #[inline]
657     #[stable(feature = "rust1", since = "1.0.0")]
658     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
659         s.as_ref()
660     }
661
662     #[inline]
663     fn from_inner(inner: &Slice) -> &OsStr {
664         // SAFETY: OsStr is just a wrapper of Slice,
665         // therefore converting &Slice to &OsStr is safe.
666         unsafe { &*(inner as *const Slice as *const OsStr) }
667     }
668
669     #[inline]
670     fn from_inner_mut(inner: &mut Slice) -> &mut OsStr {
671         // SAFETY: OsStr is just a wrapper of Slice,
672         // therefore converting &mut Slice to &mut OsStr is safe.
673         // Any method that mutates OsStr must be careful not to
674         // break platform-specific encoding, in particular Wtf8 on Windows.
675         unsafe { &mut *(inner as *mut Slice as *mut OsStr) }
676     }
677
678     /// Yields a <code>&[str]</code> slice if the `OsStr` is valid Unicode.
679     ///
680     /// This conversion may entail doing a check for UTF-8 validity.
681     ///
682     /// # Examples
683     ///
684     /// ```
685     /// use std::ffi::OsStr;
686     ///
687     /// let os_str = OsStr::new("foo");
688     /// assert_eq!(os_str.to_str(), Some("foo"));
689     /// ```
690     #[stable(feature = "rust1", since = "1.0.0")]
691     #[must_use = "this returns the result of the operation, \
692                   without modifying the original"]
693     #[inline]
694     pub fn to_str(&self) -> Option<&str> {
695         self.inner.to_str()
696     }
697
698     /// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
699     ///
700     /// Any non-Unicode sequences are replaced with
701     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
702     ///
703     /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
704     ///
705     /// # Examples
706     ///
707     /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
708     ///
709     /// ```
710     /// // Note, due to differences in how Unix and Windows represent strings,
711     /// // we are forced to complicate this example, setting up example `OsStr`s
712     /// // with different source data and via different platform extensions.
713     /// // Understand that in reality you could end up with such example invalid
714     /// // sequences simply through collecting user command line arguments, for
715     /// // example.
716     ///
717     /// #[cfg(unix)] {
718     ///     use std::ffi::OsStr;
719     ///     use std::os::unix::ffi::OsStrExt;
720     ///
721     ///     // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
722     ///     // respectively. The value 0x80 is a lone continuation byte, invalid
723     ///     // in a UTF-8 sequence.
724     ///     let source = [0x66, 0x6f, 0x80, 0x6f];
725     ///     let os_str = OsStr::from_bytes(&source[..]);
726     ///
727     ///     assert_eq!(os_str.to_string_lossy(), "fo�o");
728     /// }
729     /// #[cfg(windows)] {
730     ///     use std::ffi::OsString;
731     ///     use std::os::windows::prelude::*;
732     ///
733     ///     // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
734     ///     // respectively. The value 0xD800 is a lone surrogate half, invalid
735     ///     // in a UTF-16 sequence.
736     ///     let source = [0x0066, 0x006f, 0xD800, 0x006f];
737     ///     let os_string = OsString::from_wide(&source[..]);
738     ///     let os_str = os_string.as_os_str();
739     ///
740     ///     assert_eq!(os_str.to_string_lossy(), "fo�o");
741     /// }
742     /// ```
743     #[stable(feature = "rust1", since = "1.0.0")]
744     #[must_use = "this returns the result of the operation, \
745                   without modifying the original"]
746     #[inline]
747     pub fn to_string_lossy(&self) -> Cow<'_, str> {
748         self.inner.to_string_lossy()
749     }
750
751     /// Copies the slice into an owned [`OsString`].
752     ///
753     /// # Examples
754     ///
755     /// ```
756     /// use std::ffi::{OsStr, OsString};
757     ///
758     /// let os_str = OsStr::new("foo");
759     /// let os_string = os_str.to_os_string();
760     /// assert_eq!(os_string, OsString::from("foo"));
761     /// ```
762     #[stable(feature = "rust1", since = "1.0.0")]
763     #[must_use = "this returns the result of the operation, \
764                   without modifying the original"]
765     #[inline]
766     pub fn to_os_string(&self) -> OsString {
767         OsString { inner: self.inner.to_owned() }
768     }
769
770     /// Checks whether the `OsStr` is empty.
771     ///
772     /// # Examples
773     ///
774     /// ```
775     /// use std::ffi::OsStr;
776     ///
777     /// let os_str = OsStr::new("");
778     /// assert!(os_str.is_empty());
779     ///
780     /// let os_str = OsStr::new("foo");
781     /// assert!(!os_str.is_empty());
782     /// ```
783     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
784     #[must_use]
785     #[inline]
786     pub fn is_empty(&self) -> bool {
787         self.inner.inner.is_empty()
788     }
789
790     /// Returns the length of this `OsStr`.
791     ///
792     /// Note that this does **not** return the number of bytes in the string in
793     /// OS string form.
794     ///
795     /// The length returned is that of the underlying storage used by `OsStr`.
796     /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
797     /// store strings in a form best suited for cheap inter-conversion between
798     /// native-platform and Rust string forms, which may differ significantly
799     /// from both of them, including in storage size and encoding.
800     ///
801     /// This number is simply useful for passing to other methods, like
802     /// [`OsString::with_capacity`] to avoid reallocations.
803     ///
804     /// See the main `OsString` documentation information about encoding and capacity units.
805     ///
806     /// # Examples
807     ///
808     /// ```
809     /// use std::ffi::OsStr;
810     ///
811     /// let os_str = OsStr::new("");
812     /// assert_eq!(os_str.len(), 0);
813     ///
814     /// let os_str = OsStr::new("foo");
815     /// assert_eq!(os_str.len(), 3);
816     /// ```
817     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
818     #[must_use]
819     #[inline]
820     pub fn len(&self) -> usize {
821         self.inner.inner.len()
822     }
823
824     /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or allocating.
825     #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
826     #[must_use = "`self` will be dropped if the result is not used"]
827     pub fn into_os_string(self: Box<OsStr>) -> OsString {
828         let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
829         OsString { inner: Buf::from_box(boxed) }
830     }
831
832     /// Gets the underlying byte representation.
833     ///
834     /// Note: it is *crucial* that this API is not externally public, to avoid
835     /// revealing the internal, platform-specific encodings.
836     #[inline]
837     pub(crate) fn bytes(&self) -> &[u8] {
838         unsafe { &*(&self.inner as *const _ as *const [u8]) }
839     }
840
841     /// Converts this string to its ASCII lower case equivalent in-place.
842     ///
843     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
844     /// but non-ASCII letters are unchanged.
845     ///
846     /// To return a new lowercased value without modifying the existing one, use
847     /// [`OsStr::to_ascii_lowercase`].
848     ///
849     /// # Examples
850     ///
851     /// ```
852     /// use std::ffi::OsString;
853     ///
854     /// let mut s = OsString::from("GRÜßE, JÜRGEN ❤");
855     ///
856     /// s.make_ascii_lowercase();
857     ///
858     /// assert_eq!("grÜße, jÜrgen ❤", s);
859     /// ```
860     #[stable(feature = "osstring_ascii", since = "1.53.0")]
861     #[inline]
862     pub fn make_ascii_lowercase(&mut self) {
863         self.inner.make_ascii_lowercase()
864     }
865
866     /// Converts this string to its ASCII upper case equivalent in-place.
867     ///
868     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
869     /// but non-ASCII letters are unchanged.
870     ///
871     /// To return a new uppercased value without modifying the existing one, use
872     /// [`OsStr::to_ascii_uppercase`].
873     ///
874     /// # Examples
875     ///
876     /// ```
877     /// use std::ffi::OsString;
878     ///
879     /// let mut s = OsString::from("Grüße, Jürgen ❤");
880     ///
881     /// s.make_ascii_uppercase();
882     ///
883     /// assert_eq!("GRüßE, JüRGEN ❤", s);
884     /// ```
885     #[stable(feature = "osstring_ascii", since = "1.53.0")]
886     #[inline]
887     pub fn make_ascii_uppercase(&mut self) {
888         self.inner.make_ascii_uppercase()
889     }
890
891     /// Returns a copy of this string where each character is mapped to its
892     /// ASCII lower case equivalent.
893     ///
894     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
895     /// but non-ASCII letters are unchanged.
896     ///
897     /// To lowercase the value in-place, use [`OsStr::make_ascii_lowercase`].
898     ///
899     /// # Examples
900     ///
901     /// ```
902     /// use std::ffi::OsString;
903     /// let s = OsString::from("Grüße, Jürgen ❤");
904     ///
905     /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
906     /// ```
907     #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase`"]
908     #[stable(feature = "osstring_ascii", since = "1.53.0")]
909     pub fn to_ascii_lowercase(&self) -> OsString {
910         OsString::from_inner(self.inner.to_ascii_lowercase())
911     }
912
913     /// Returns a copy of this string where each character is mapped to its
914     /// ASCII upper case equivalent.
915     ///
916     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
917     /// but non-ASCII letters are unchanged.
918     ///
919     /// To uppercase the value in-place, use [`OsStr::make_ascii_uppercase`].
920     ///
921     /// # Examples
922     ///
923     /// ```
924     /// use std::ffi::OsString;
925     /// let s = OsString::from("Grüße, Jürgen ❤");
926     ///
927     /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
928     /// ```
929     #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase`"]
930     #[stable(feature = "osstring_ascii", since = "1.53.0")]
931     pub fn to_ascii_uppercase(&self) -> OsString {
932         OsString::from_inner(self.inner.to_ascii_uppercase())
933     }
934
935     /// Checks if all characters in this string are within the ASCII range.
936     ///
937     /// # Examples
938     ///
939     /// ```
940     /// use std::ffi::OsString;
941     ///
942     /// let ascii = OsString::from("hello!\n");
943     /// let non_ascii = OsString::from("Grüße, Jürgen ❤");
944     ///
945     /// assert!(ascii.is_ascii());
946     /// assert!(!non_ascii.is_ascii());
947     /// ```
948     #[stable(feature = "osstring_ascii", since = "1.53.0")]
949     #[must_use]
950     #[inline]
951     pub fn is_ascii(&self) -> bool {
952         self.inner.is_ascii()
953     }
954
955     /// Checks that two strings are an ASCII case-insensitive match.
956     ///
957     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
958     /// but without allocating and copying temporaries.
959     ///
960     /// # Examples
961     ///
962     /// ```
963     /// use std::ffi::OsString;
964     ///
965     /// assert!(OsString::from("Ferris").eq_ignore_ascii_case("FERRIS"));
966     /// assert!(OsString::from("Ferrös").eq_ignore_ascii_case("FERRöS"));
967     /// assert!(!OsString::from("Ferrös").eq_ignore_ascii_case("FERRÖS"));
968     /// ```
969     #[stable(feature = "osstring_ascii", since = "1.53.0")]
970     pub fn eq_ignore_ascii_case<S: AsRef<OsStr>>(&self, other: S) -> bool {
971         self.inner.eq_ignore_ascii_case(&other.as_ref().inner)
972     }
973 }
974
975 #[stable(feature = "box_from_os_str", since = "1.17.0")]
976 impl From<&OsStr> for Box<OsStr> {
977     /// Copies the string into a newly allocated <code>[Box]&lt;[OsStr]&gt;</code>.
978     #[inline]
979     fn from(s: &OsStr) -> Box<OsStr> {
980         let rw = Box::into_raw(s.inner.into_box()) as *mut OsStr;
981         unsafe { Box::from_raw(rw) }
982     }
983 }
984
985 #[stable(feature = "box_from_cow", since = "1.45.0")]
986 impl From<Cow<'_, OsStr>> for Box<OsStr> {
987     /// Converts a `Cow<'a, OsStr>` into a <code>[Box]&lt;[OsStr]&gt;</code>,
988     /// by copying the contents if they are borrowed.
989     #[inline]
990     fn from(cow: Cow<'_, OsStr>) -> Box<OsStr> {
991         match cow {
992             Cow::Borrowed(s) => Box::from(s),
993             Cow::Owned(s) => Box::from(s),
994         }
995     }
996 }
997
998 #[stable(feature = "os_string_from_box", since = "1.18.0")]
999 impl From<Box<OsStr>> for OsString {
1000     /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or
1001     /// allocating.
1002     #[inline]
1003     fn from(boxed: Box<OsStr>) -> OsString {
1004         boxed.into_os_string()
1005     }
1006 }
1007
1008 #[stable(feature = "box_from_os_string", since = "1.20.0")]
1009 impl From<OsString> for Box<OsStr> {
1010     /// Converts an [`OsString`] into a <code>[Box]<[OsStr]></code> without copying or allocating.
1011     #[inline]
1012     fn from(s: OsString) -> Box<OsStr> {
1013         s.into_boxed_os_str()
1014     }
1015 }
1016
1017 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1018 impl Clone for Box<OsStr> {
1019     #[inline]
1020     fn clone(&self) -> Self {
1021         self.to_os_string().into_boxed_os_str()
1022     }
1023 }
1024
1025 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1026 impl From<OsString> for Arc<OsStr> {
1027     /// Converts an [`OsString`] into an <code>[Arc]<[OsStr]></code> by moving the [`OsString`]
1028     /// data into a new [`Arc`] buffer.
1029     #[inline]
1030     fn from(s: OsString) -> Arc<OsStr> {
1031         let arc = s.inner.into_arc();
1032         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1033     }
1034 }
1035
1036 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1037 impl From<&OsStr> for Arc<OsStr> {
1038     /// Copies the string into a newly allocated <code>[Arc]&lt;[OsStr]&gt;</code>.
1039     #[inline]
1040     fn from(s: &OsStr) -> Arc<OsStr> {
1041         let arc = s.inner.into_arc();
1042         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1043     }
1044 }
1045
1046 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1047 impl From<OsString> for Rc<OsStr> {
1048     /// Converts an [`OsString`] into an <code>[Rc]<[OsStr]></code> by moving the [`OsString`]
1049     /// data into a new [`Rc`] buffer.
1050     #[inline]
1051     fn from(s: OsString) -> Rc<OsStr> {
1052         let rc = s.inner.into_rc();
1053         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1054     }
1055 }
1056
1057 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1058 impl From<&OsStr> for Rc<OsStr> {
1059     /// Copies the string into a newly allocated <code>[Rc]&lt;[OsStr]&gt;</code>.
1060     #[inline]
1061     fn from(s: &OsStr) -> Rc<OsStr> {
1062         let rc = s.inner.into_rc();
1063         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1064     }
1065 }
1066
1067 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1068 impl<'a> From<OsString> for Cow<'a, OsStr> {
1069     /// Moves the string into a [`Cow::Owned`].
1070     #[inline]
1071     fn from(s: OsString) -> Cow<'a, OsStr> {
1072         Cow::Owned(s)
1073     }
1074 }
1075
1076 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1077 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
1078     /// Converts the string reference into a [`Cow::Borrowed`].
1079     #[inline]
1080     fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
1081         Cow::Borrowed(s)
1082     }
1083 }
1084
1085 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1086 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
1087     /// Converts the string reference into a [`Cow::Borrowed`].
1088     #[inline]
1089     fn from(s: &'a OsString) -> Cow<'a, OsStr> {
1090         Cow::Borrowed(s.as_os_str())
1091     }
1092 }
1093
1094 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
1095 impl<'a> From<Cow<'a, OsStr>> for OsString {
1096     /// Converts a `Cow<'a, OsStr>` into an [`OsString`],
1097     /// by copying the contents if they are borrowed.
1098     #[inline]
1099     fn from(s: Cow<'a, OsStr>) -> Self {
1100         s.into_owned()
1101     }
1102 }
1103
1104 #[stable(feature = "box_default_extra", since = "1.17.0")]
1105 impl Default for Box<OsStr> {
1106     #[inline]
1107     fn default() -> Box<OsStr> {
1108         let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
1109         unsafe { Box::from_raw(rw) }
1110     }
1111 }
1112
1113 #[stable(feature = "osstring_default", since = "1.9.0")]
1114 impl Default for &OsStr {
1115     /// Creates an empty `OsStr`.
1116     #[inline]
1117     fn default() -> Self {
1118         OsStr::new("")
1119     }
1120 }
1121
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl PartialEq for OsStr {
1124     #[inline]
1125     fn eq(&self, other: &OsStr) -> bool {
1126         self.bytes().eq(other.bytes())
1127     }
1128 }
1129
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 impl PartialEq<str> for OsStr {
1132     #[inline]
1133     fn eq(&self, other: &str) -> bool {
1134         *self == *OsStr::new(other)
1135     }
1136 }
1137
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 impl PartialEq<OsStr> for str {
1140     #[inline]
1141     fn eq(&self, other: &OsStr) -> bool {
1142         *other == *OsStr::new(self)
1143     }
1144 }
1145
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl Eq for OsStr {}
1148
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl PartialOrd for OsStr {
1151     #[inline]
1152     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1153         self.bytes().partial_cmp(other.bytes())
1154     }
1155     #[inline]
1156     fn lt(&self, other: &OsStr) -> bool {
1157         self.bytes().lt(other.bytes())
1158     }
1159     #[inline]
1160     fn le(&self, other: &OsStr) -> bool {
1161         self.bytes().le(other.bytes())
1162     }
1163     #[inline]
1164     fn gt(&self, other: &OsStr) -> bool {
1165         self.bytes().gt(other.bytes())
1166     }
1167     #[inline]
1168     fn ge(&self, other: &OsStr) -> bool {
1169         self.bytes().ge(other.bytes())
1170     }
1171 }
1172
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 impl PartialOrd<str> for OsStr {
1175     #[inline]
1176     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1177         self.partial_cmp(OsStr::new(other))
1178     }
1179 }
1180
1181 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1182 // have more flexible coherence rules.
1183
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl Ord for OsStr {
1186     #[inline]
1187     fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1188         self.bytes().cmp(other.bytes())
1189     }
1190 }
1191
1192 macro_rules! impl_cmp {
1193     ($lhs:ty, $rhs: ty) => {
1194         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1195         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1196             #[inline]
1197             fn eq(&self, other: &$rhs) -> bool {
1198                 <OsStr as PartialEq>::eq(self, other)
1199             }
1200         }
1201
1202         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1203         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1204             #[inline]
1205             fn eq(&self, other: &$lhs) -> bool {
1206                 <OsStr as PartialEq>::eq(self, other)
1207             }
1208         }
1209
1210         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1211         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
1212             #[inline]
1213             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1214                 <OsStr as PartialOrd>::partial_cmp(self, other)
1215             }
1216         }
1217
1218         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1219         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
1220             #[inline]
1221             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1222                 <OsStr as PartialOrd>::partial_cmp(self, other)
1223             }
1224         }
1225     };
1226 }
1227
1228 impl_cmp!(OsString, OsStr);
1229 impl_cmp!(OsString, &'a OsStr);
1230 impl_cmp!(Cow<'a, OsStr>, OsStr);
1231 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
1232 impl_cmp!(Cow<'a, OsStr>, OsString);
1233
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 impl Hash for OsStr {
1236     #[inline]
1237     fn hash<H: Hasher>(&self, state: &mut H) {
1238         self.bytes().hash(state)
1239     }
1240 }
1241
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl fmt::Debug for OsStr {
1244     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1245         fmt::Debug::fmt(&self.inner, formatter)
1246     }
1247 }
1248
1249 impl OsStr {
1250     pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1251         fmt::Display::fmt(&self.inner, formatter)
1252     }
1253 }
1254
1255 #[unstable(feature = "slice_concat_ext", issue = "27747")]
1256 impl<S: Borrow<OsStr>> alloc::slice::Join<&OsStr> for [S] {
1257     type Output = OsString;
1258
1259     fn join(slice: &Self, sep: &OsStr) -> OsString {
1260         let Some((first, suffix)) = slice.split_first() else {
1261             return OsString::new();
1262         };
1263         let first_owned = first.borrow().to_owned();
1264         suffix.iter().fold(first_owned, |mut a, b| {
1265             a.push(sep);
1266             a.push(b.borrow());
1267             a
1268         })
1269     }
1270 }
1271
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 impl Borrow<OsStr> for OsString {
1274     #[inline]
1275     fn borrow(&self) -> &OsStr {
1276         &self[..]
1277     }
1278 }
1279
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 impl ToOwned for OsStr {
1282     type Owned = OsString;
1283     #[inline]
1284     fn to_owned(&self) -> OsString {
1285         self.to_os_string()
1286     }
1287     #[inline]
1288     fn clone_into(&self, target: &mut OsString) {
1289         self.inner.clone_into(&mut target.inner)
1290     }
1291 }
1292
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl AsRef<OsStr> for OsStr {
1295     #[inline]
1296     fn as_ref(&self) -> &OsStr {
1297         self
1298     }
1299 }
1300
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl AsRef<OsStr> for OsString {
1303     #[inline]
1304     fn as_ref(&self) -> &OsStr {
1305         self
1306     }
1307 }
1308
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 impl AsRef<OsStr> for str {
1311     #[inline]
1312     fn as_ref(&self) -> &OsStr {
1313         OsStr::from_inner(Slice::from_str(self))
1314     }
1315 }
1316
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 impl AsRef<OsStr> for String {
1319     #[inline]
1320     fn as_ref(&self) -> &OsStr {
1321         (&**self).as_ref()
1322     }
1323 }
1324
1325 impl FromInner<Buf> for OsString {
1326     #[inline]
1327     fn from_inner(buf: Buf) -> OsString {
1328         OsString { inner: buf }
1329     }
1330 }
1331
1332 impl IntoInner<Buf> for OsString {
1333     #[inline]
1334     fn into_inner(self) -> Buf {
1335         self.inner
1336     }
1337 }
1338
1339 impl AsInner<Slice> for OsStr {
1340     #[inline]
1341     fn as_inner(&self) -> &Slice {
1342         &self.inner
1343     }
1344 }
1345
1346 #[stable(feature = "osstring_from_str", since = "1.45.0")]
1347 impl FromStr for OsString {
1348     type Err = core::convert::Infallible;
1349
1350     #[inline]
1351     fn from_str(s: &str) -> Result<Self, Self::Err> {
1352         Ok(OsString::from(s))
1353     }
1354 }
1355
1356 #[stable(feature = "osstring_extend", since = "1.52.0")]
1357 impl Extend<OsString> for OsString {
1358     #[inline]
1359     fn extend<T: IntoIterator<Item = OsString>>(&mut self, iter: T) {
1360         for s in iter {
1361             self.push(&s);
1362         }
1363     }
1364 }
1365
1366 #[stable(feature = "osstring_extend", since = "1.52.0")]
1367 impl<'a> Extend<&'a OsStr> for OsString {
1368     #[inline]
1369     fn extend<T: IntoIterator<Item = &'a OsStr>>(&mut self, iter: T) {
1370         for s in iter {
1371             self.push(s);
1372         }
1373     }
1374 }
1375
1376 #[stable(feature = "osstring_extend", since = "1.52.0")]
1377 impl<'a> Extend<Cow<'a, OsStr>> for OsString {
1378     #[inline]
1379     fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: T) {
1380         for s in iter {
1381             self.push(&s);
1382         }
1383     }
1384 }
1385
1386 #[stable(feature = "osstring_extend", since = "1.52.0")]
1387 impl FromIterator<OsString> for OsString {
1388     #[inline]
1389     fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1390         let mut iterator = iter.into_iter();
1391
1392         // Because we're iterating over `OsString`s, we can avoid at least
1393         // one allocation by getting the first string from the iterator
1394         // and appending to it all the subsequent strings.
1395         match iterator.next() {
1396             None => OsString::new(),
1397             Some(mut buf) => {
1398                 buf.extend(iterator);
1399                 buf
1400             }
1401         }
1402     }
1403 }
1404
1405 #[stable(feature = "osstring_extend", since = "1.52.0")]
1406 impl<'a> FromIterator<&'a OsStr> for OsString {
1407     #[inline]
1408     fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self {
1409         let mut buf = Self::new();
1410         for s in iter {
1411             buf.push(s);
1412         }
1413         buf
1414     }
1415 }
1416
1417 #[stable(feature = "osstring_extend", since = "1.52.0")]
1418 impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
1419     #[inline]
1420     fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
1421         let mut iterator = iter.into_iter();
1422
1423         // Because we're iterating over `OsString`s, we can avoid at least
1424         // one allocation by getting the first owned string from the iterator
1425         // and appending to it all the subsequent strings.
1426         match iterator.next() {
1427             None => OsString::new(),
1428             Some(Cow::Owned(mut buf)) => {
1429                 buf.extend(iterator);
1430                 buf
1431             }
1432             Some(Cow::Borrowed(buf)) => {
1433                 let mut buf = OsString::from(buf);
1434                 buf.extend(iterator);
1435                 buf
1436             }
1437         }
1438     }
1439 }