]> git.lizzy.rs Git - rust.git/blob - library/std/src/ffi/os_str.rs
Auto merge of #93146 - workingjubilee:use-std-simd, r=Mark-Simulacrum
[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> by moving the [`OsString`]
993     /// data into a new [`Arc`] buffer.
994     #[inline]
995     fn from(s: OsString) -> Arc<OsStr> {
996         let arc = s.inner.into_arc();
997         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
998     }
999 }
1000
1001 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1002 impl From<&OsStr> for Arc<OsStr> {
1003     #[inline]
1004     fn from(s: &OsStr) -> Arc<OsStr> {
1005         let arc = s.inner.into_arc();
1006         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1007     }
1008 }
1009
1010 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1011 impl From<OsString> for Rc<OsStr> {
1012     /// Converts an [`OsString`] into an <code>[Rc]<[OsStr]></code> by moving the [`OsString`]
1013     /// data into a new [`Rc`] buffer.
1014     #[inline]
1015     fn from(s: OsString) -> Rc<OsStr> {
1016         let rc = s.inner.into_rc();
1017         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1018     }
1019 }
1020
1021 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1022 impl From<&OsStr> for Rc<OsStr> {
1023     #[inline]
1024     fn from(s: &OsStr) -> Rc<OsStr> {
1025         let rc = s.inner.into_rc();
1026         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1027     }
1028 }
1029
1030 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1031 impl<'a> From<OsString> for Cow<'a, OsStr> {
1032     #[inline]
1033     fn from(s: OsString) -> Cow<'a, OsStr> {
1034         Cow::Owned(s)
1035     }
1036 }
1037
1038 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1039 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
1040     #[inline]
1041     fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
1042         Cow::Borrowed(s)
1043     }
1044 }
1045
1046 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1047 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
1048     #[inline]
1049     fn from(s: &'a OsString) -> Cow<'a, OsStr> {
1050         Cow::Borrowed(s.as_os_str())
1051     }
1052 }
1053
1054 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
1055 impl<'a> From<Cow<'a, OsStr>> for OsString {
1056     #[inline]
1057     fn from(s: Cow<'a, OsStr>) -> Self {
1058         s.into_owned()
1059     }
1060 }
1061
1062 #[stable(feature = "box_default_extra", since = "1.17.0")]
1063 impl Default for Box<OsStr> {
1064     #[inline]
1065     fn default() -> Box<OsStr> {
1066         let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
1067         unsafe { Box::from_raw(rw) }
1068     }
1069 }
1070
1071 #[stable(feature = "osstring_default", since = "1.9.0")]
1072 impl Default for &OsStr {
1073     /// Creates an empty `OsStr`.
1074     #[inline]
1075     fn default() -> Self {
1076         OsStr::new("")
1077     }
1078 }
1079
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl PartialEq for OsStr {
1082     #[inline]
1083     fn eq(&self, other: &OsStr) -> bool {
1084         self.bytes().eq(other.bytes())
1085     }
1086 }
1087
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 impl PartialEq<str> for OsStr {
1090     #[inline]
1091     fn eq(&self, other: &str) -> bool {
1092         *self == *OsStr::new(other)
1093     }
1094 }
1095
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl PartialEq<OsStr> for str {
1098     #[inline]
1099     fn eq(&self, other: &OsStr) -> bool {
1100         *other == *OsStr::new(self)
1101     }
1102 }
1103
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl Eq for OsStr {}
1106
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 impl PartialOrd for OsStr {
1109     #[inline]
1110     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1111         self.bytes().partial_cmp(other.bytes())
1112     }
1113     #[inline]
1114     fn lt(&self, other: &OsStr) -> bool {
1115         self.bytes().lt(other.bytes())
1116     }
1117     #[inline]
1118     fn le(&self, other: &OsStr) -> bool {
1119         self.bytes().le(other.bytes())
1120     }
1121     #[inline]
1122     fn gt(&self, other: &OsStr) -> bool {
1123         self.bytes().gt(other.bytes())
1124     }
1125     #[inline]
1126     fn ge(&self, other: &OsStr) -> bool {
1127         self.bytes().ge(other.bytes())
1128     }
1129 }
1130
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl PartialOrd<str> for OsStr {
1133     #[inline]
1134     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1135         self.partial_cmp(OsStr::new(other))
1136     }
1137 }
1138
1139 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1140 // have more flexible coherence rules.
1141
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 impl Ord for OsStr {
1144     #[inline]
1145     fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1146         self.bytes().cmp(other.bytes())
1147     }
1148 }
1149
1150 macro_rules! impl_cmp {
1151     ($lhs:ty, $rhs: ty) => {
1152         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1153         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1154             #[inline]
1155             fn eq(&self, other: &$rhs) -> bool {
1156                 <OsStr as PartialEq>::eq(self, other)
1157             }
1158         }
1159
1160         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1161         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1162             #[inline]
1163             fn eq(&self, other: &$lhs) -> bool {
1164                 <OsStr as PartialEq>::eq(self, other)
1165             }
1166         }
1167
1168         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1169         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
1170             #[inline]
1171             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1172                 <OsStr as PartialOrd>::partial_cmp(self, other)
1173             }
1174         }
1175
1176         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1177         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
1178             #[inline]
1179             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1180                 <OsStr as PartialOrd>::partial_cmp(self, other)
1181             }
1182         }
1183     };
1184 }
1185
1186 impl_cmp!(OsString, OsStr);
1187 impl_cmp!(OsString, &'a OsStr);
1188 impl_cmp!(Cow<'a, OsStr>, OsStr);
1189 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
1190 impl_cmp!(Cow<'a, OsStr>, OsString);
1191
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl Hash for OsStr {
1194     #[inline]
1195     fn hash<H: Hasher>(&self, state: &mut H) {
1196         self.bytes().hash(state)
1197     }
1198 }
1199
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 impl fmt::Debug for OsStr {
1202     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1203         fmt::Debug::fmt(&self.inner, formatter)
1204     }
1205 }
1206
1207 impl OsStr {
1208     pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1209         fmt::Display::fmt(&self.inner, formatter)
1210     }
1211 }
1212
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl Borrow<OsStr> for OsString {
1215     #[inline]
1216     fn borrow(&self) -> &OsStr {
1217         &self[..]
1218     }
1219 }
1220
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl ToOwned for OsStr {
1223     type Owned = OsString;
1224     #[inline]
1225     fn to_owned(&self) -> OsString {
1226         self.to_os_string()
1227     }
1228     #[inline]
1229     fn clone_into(&self, target: &mut OsString) {
1230         self.inner.clone_into(&mut target.inner)
1231     }
1232 }
1233
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 impl AsRef<OsStr> for OsStr {
1236     #[inline]
1237     fn as_ref(&self) -> &OsStr {
1238         self
1239     }
1240 }
1241
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl AsRef<OsStr> for OsString {
1244     #[inline]
1245     fn as_ref(&self) -> &OsStr {
1246         self
1247     }
1248 }
1249
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl AsRef<OsStr> for str {
1252     #[inline]
1253     fn as_ref(&self) -> &OsStr {
1254         OsStr::from_inner(Slice::from_str(self))
1255     }
1256 }
1257
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl AsRef<OsStr> for String {
1260     #[inline]
1261     fn as_ref(&self) -> &OsStr {
1262         (&**self).as_ref()
1263     }
1264 }
1265
1266 impl FromInner<Buf> for OsString {
1267     #[inline]
1268     fn from_inner(buf: Buf) -> OsString {
1269         OsString { inner: buf }
1270     }
1271 }
1272
1273 impl IntoInner<Buf> for OsString {
1274     #[inline]
1275     fn into_inner(self) -> Buf {
1276         self.inner
1277     }
1278 }
1279
1280 impl AsInner<Slice> for OsStr {
1281     #[inline]
1282     fn as_inner(&self) -> &Slice {
1283         &self.inner
1284     }
1285 }
1286
1287 #[stable(feature = "osstring_from_str", since = "1.45.0")]
1288 impl FromStr for OsString {
1289     type Err = core::convert::Infallible;
1290
1291     #[inline]
1292     fn from_str(s: &str) -> Result<Self, Self::Err> {
1293         Ok(OsString::from(s))
1294     }
1295 }
1296
1297 #[stable(feature = "osstring_extend", since = "1.52.0")]
1298 impl Extend<OsString> for OsString {
1299     #[inline]
1300     fn extend<T: IntoIterator<Item = OsString>>(&mut self, iter: T) {
1301         for s in iter {
1302             self.push(&s);
1303         }
1304     }
1305 }
1306
1307 #[stable(feature = "osstring_extend", since = "1.52.0")]
1308 impl<'a> Extend<&'a OsStr> for OsString {
1309     #[inline]
1310     fn extend<T: IntoIterator<Item = &'a OsStr>>(&mut self, iter: T) {
1311         for s in iter {
1312             self.push(s);
1313         }
1314     }
1315 }
1316
1317 #[stable(feature = "osstring_extend", since = "1.52.0")]
1318 impl<'a> Extend<Cow<'a, OsStr>> for OsString {
1319     #[inline]
1320     fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: T) {
1321         for s in iter {
1322             self.push(&s);
1323         }
1324     }
1325 }
1326
1327 #[stable(feature = "osstring_extend", since = "1.52.0")]
1328 impl FromIterator<OsString> for OsString {
1329     #[inline]
1330     fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1331         let mut iterator = iter.into_iter();
1332
1333         // Because we're iterating over `OsString`s, we can avoid at least
1334         // one allocation by getting the first string from the iterator
1335         // and appending to it all the subsequent strings.
1336         match iterator.next() {
1337             None => OsString::new(),
1338             Some(mut buf) => {
1339                 buf.extend(iterator);
1340                 buf
1341             }
1342         }
1343     }
1344 }
1345
1346 #[stable(feature = "osstring_extend", since = "1.52.0")]
1347 impl<'a> FromIterator<&'a OsStr> for OsString {
1348     #[inline]
1349     fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self {
1350         let mut buf = Self::new();
1351         for s in iter {
1352             buf.push(s);
1353         }
1354         buf
1355     }
1356 }
1357
1358 #[stable(feature = "osstring_extend", since = "1.52.0")]
1359 impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
1360     #[inline]
1361     fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
1362         let mut iterator = iter.into_iter();
1363
1364         // Because we're iterating over `OsString`s, we can avoid at least
1365         // one allocation by getting the first owned string from the iterator
1366         // and appending to it all the subsequent strings.
1367         match iterator.next() {
1368             None => OsString::new(),
1369             Some(Cow::Owned(mut buf)) => {
1370                 buf.extend(iterator);
1371                 buf
1372             }
1373             Some(Cow::Borrowed(buf)) => {
1374                 let mut buf = OsString::from(buf);
1375                 buf.extend(iterator);
1376                 buf
1377             }
1378         }
1379     }
1380 }