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