]> git.lizzy.rs Git - rust.git/blob - library/std/src/ffi/os_str.rs
Rollup merge of #97087 - Nilstrieb:clarify-slice-iteration-order, r=dtolnay
[rust.git] / library / std / src / ffi / os_str.rs
1 #[cfg(test)]
2 mod tests;
3
4 use crate::borrow::{Borrow, Cow};
5 use crate::cmp;
6 use crate::collections::TryReserveError;
7 use crate::fmt;
8 use crate::hash::{Hash, Hasher};
9 use crate::iter::Extend;
10 use crate::ops;
11 use crate::rc::Rc;
12 use crate::str::FromStr;
13 use crate::sync::Arc;
14
15 use crate::sys::os_str::{Buf, Slice};
16 use crate::sys_common::{AsInner, FromInner, IntoInner};
17
18 /// A type that can represent owned, mutable platform-native strings, but is
19 /// cheaply inter-convertible with Rust strings.
20 ///
21 /// The need for this type arises from the fact that:
22 ///
23 /// * On Unix systems, strings are often arbitrary sequences of non-zero
24 ///   bytes, in many cases interpreted as UTF-8.
25 ///
26 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
27 ///   values, interpreted as UTF-16 when it is valid to do so.
28 ///
29 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
30 ///
31 /// `OsString` and [`OsStr`] bridge this gap by simultaneously representing Rust
32 /// and platform-native string values, and in particular allowing a Rust string
33 /// to be converted into an "OS" string with no cost if possible. A consequence
34 /// of this is that `OsString` instances are *not* `NUL` terminated; in order
35 /// to pass to e.g., Unix system call, you should create a [`CStr`].
36 ///
37 /// `OsString` is to <code>&[OsStr]</code> as [`String`] is to <code>&[str]</code>: the former
38 /// in each pair are owned strings; the latter are borrowed
39 /// references.
40 ///
41 /// Note, `OsString` and [`OsStr`] internally do not necessarily hold strings in
42 /// the form native to the platform; While on Unix, strings are stored as a
43 /// sequence of 8-bit values, on Windows, where strings are 16-bit value based
44 /// as just discussed, strings are also actually stored as a sequence of 8-bit
45 /// values, encoded in a less-strict variant of UTF-8. This is useful to
46 /// understand when handling capacity and length values.
47 ///
48 /// # 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     /// Copies any value implementing <code>[AsRef]&lt;[OsStr]&gt;</code>
456     /// into a newly allocated [`OsString`].
457     fn from(s: &T) -> OsString {
458         s.as_ref().to_os_string()
459     }
460 }
461
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl ops::Index<ops::RangeFull> for OsString {
464     type Output = OsStr;
465
466     #[inline]
467     fn index(&self, _index: ops::RangeFull) -> &OsStr {
468         OsStr::from_inner(self.inner.as_slice())
469     }
470 }
471
472 #[stable(feature = "mut_osstr", since = "1.44.0")]
473 impl ops::IndexMut<ops::RangeFull> for OsString {
474     #[inline]
475     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut OsStr {
476         OsStr::from_inner_mut(self.inner.as_mut_slice())
477     }
478 }
479
480 #[stable(feature = "rust1", since = "1.0.0")]
481 impl ops::Deref for OsString {
482     type Target = OsStr;
483
484     #[inline]
485     fn deref(&self) -> &OsStr {
486         &self[..]
487     }
488 }
489
490 #[stable(feature = "mut_osstr", since = "1.44.0")]
491 impl ops::DerefMut for OsString {
492     #[inline]
493     fn deref_mut(&mut self) -> &mut OsStr {
494         &mut self[..]
495     }
496 }
497
498 #[stable(feature = "osstring_default", since = "1.9.0")]
499 impl Default for OsString {
500     /// Constructs an empty `OsString`.
501     #[inline]
502     fn default() -> OsString {
503         OsString::new()
504     }
505 }
506
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl Clone for OsString {
509     #[inline]
510     fn clone(&self) -> Self {
511         OsString { inner: self.inner.clone() }
512     }
513
514     #[inline]
515     fn clone_from(&mut self, source: &Self) {
516         self.inner.clone_from(&source.inner)
517     }
518 }
519
520 #[stable(feature = "rust1", since = "1.0.0")]
521 impl fmt::Debug for OsString {
522     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
523         fmt::Debug::fmt(&**self, formatter)
524     }
525 }
526
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl PartialEq for OsString {
529     #[inline]
530     fn eq(&self, other: &OsString) -> bool {
531         &**self == &**other
532     }
533 }
534
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl PartialEq<str> for OsString {
537     #[inline]
538     fn eq(&self, other: &str) -> bool {
539         &**self == other
540     }
541 }
542
543 #[stable(feature = "rust1", since = "1.0.0")]
544 impl PartialEq<OsString> for str {
545     #[inline]
546     fn eq(&self, other: &OsString) -> bool {
547         &**other == self
548     }
549 }
550
551 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
552 impl PartialEq<&str> for OsString {
553     #[inline]
554     fn eq(&self, other: &&str) -> bool {
555         **self == **other
556     }
557 }
558
559 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
560 impl<'a> PartialEq<OsString> for &'a str {
561     #[inline]
562     fn eq(&self, other: &OsString) -> bool {
563         **other == **self
564     }
565 }
566
567 #[stable(feature = "rust1", since = "1.0.0")]
568 impl Eq for OsString {}
569
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl PartialOrd for OsString {
572     #[inline]
573     fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
574         (&**self).partial_cmp(&**other)
575     }
576     #[inline]
577     fn lt(&self, other: &OsString) -> bool {
578         &**self < &**other
579     }
580     #[inline]
581     fn le(&self, other: &OsString) -> bool {
582         &**self <= &**other
583     }
584     #[inline]
585     fn gt(&self, other: &OsString) -> bool {
586         &**self > &**other
587     }
588     #[inline]
589     fn ge(&self, other: &OsString) -> bool {
590         &**self >= &**other
591     }
592 }
593
594 #[stable(feature = "rust1", since = "1.0.0")]
595 impl PartialOrd<str> for OsString {
596     #[inline]
597     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
598         (&**self).partial_cmp(other)
599     }
600 }
601
602 #[stable(feature = "rust1", since = "1.0.0")]
603 impl Ord for OsString {
604     #[inline]
605     fn cmp(&self, other: &OsString) -> cmp::Ordering {
606         (&**self).cmp(&**other)
607     }
608 }
609
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl Hash for OsString {
612     #[inline]
613     fn hash<H: Hasher>(&self, state: &mut H) {
614         (&**self).hash(state)
615     }
616 }
617
618 impl OsStr {
619     /// Coerces into an `OsStr` slice.
620     ///
621     /// # Examples
622     ///
623     /// ```
624     /// use std::ffi::OsStr;
625     ///
626     /// let os_str = OsStr::new("foo");
627     /// ```
628     #[inline]
629     #[stable(feature = "rust1", since = "1.0.0")]
630     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
631         s.as_ref()
632     }
633
634     #[inline]
635     fn from_inner(inner: &Slice) -> &OsStr {
636         // SAFETY: OsStr is just a wrapper of Slice,
637         // therefore converting &Slice to &OsStr is safe.
638         unsafe { &*(inner as *const Slice as *const OsStr) }
639     }
640
641     #[inline]
642     fn from_inner_mut(inner: &mut Slice) -> &mut OsStr {
643         // SAFETY: OsStr is just a wrapper of Slice,
644         // therefore converting &mut Slice to &mut OsStr is safe.
645         // Any method that mutates OsStr must be careful not to
646         // break platform-specific encoding, in particular Wtf8 on Windows.
647         unsafe { &mut *(inner as *mut Slice as *mut OsStr) }
648     }
649
650     /// Yields a <code>&[str]</code> slice if the `OsStr` is valid Unicode.
651     ///
652     /// This conversion may entail doing a check for UTF-8 validity.
653     ///
654     /// # Examples
655     ///
656     /// ```
657     /// use std::ffi::OsStr;
658     ///
659     /// let os_str = OsStr::new("foo");
660     /// assert_eq!(os_str.to_str(), Some("foo"));
661     /// ```
662     #[stable(feature = "rust1", since = "1.0.0")]
663     #[must_use = "this returns the result of the operation, \
664                   without modifying the original"]
665     #[inline]
666     pub fn to_str(&self) -> Option<&str> {
667         self.inner.to_str()
668     }
669
670     /// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
671     ///
672     /// Any non-Unicode sequences are replaced with
673     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
674     ///
675     /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
676     ///
677     /// # Examples
678     ///
679     /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
680     ///
681     /// ```
682     /// // Note, due to differences in how Unix and Windows represent strings,
683     /// // we are forced to complicate this example, setting up example `OsStr`s
684     /// // with different source data and via different platform extensions.
685     /// // Understand that in reality you could end up with such example invalid
686     /// // sequences simply through collecting user command line arguments, for
687     /// // example.
688     ///
689     /// #[cfg(unix)] {
690     ///     use std::ffi::OsStr;
691     ///     use std::os::unix::ffi::OsStrExt;
692     ///
693     ///     // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
694     ///     // respectively. The value 0x80 is a lone continuation byte, invalid
695     ///     // in a UTF-8 sequence.
696     ///     let source = [0x66, 0x6f, 0x80, 0x6f];
697     ///     let os_str = OsStr::from_bytes(&source[..]);
698     ///
699     ///     assert_eq!(os_str.to_string_lossy(), "fo�o");
700     /// }
701     /// #[cfg(windows)] {
702     ///     use std::ffi::OsString;
703     ///     use std::os::windows::prelude::*;
704     ///
705     ///     // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
706     ///     // respectively. The value 0xD800 is a lone surrogate half, invalid
707     ///     // in a UTF-16 sequence.
708     ///     let source = [0x0066, 0x006f, 0xD800, 0x006f];
709     ///     let os_string = OsString::from_wide(&source[..]);
710     ///     let os_str = os_string.as_os_str();
711     ///
712     ///     assert_eq!(os_str.to_string_lossy(), "fo�o");
713     /// }
714     /// ```
715     #[stable(feature = "rust1", since = "1.0.0")]
716     #[must_use = "this returns the result of the operation, \
717                   without modifying the original"]
718     #[inline]
719     pub fn to_string_lossy(&self) -> Cow<'_, str> {
720         self.inner.to_string_lossy()
721     }
722
723     /// Copies the slice into an owned [`OsString`].
724     ///
725     /// # Examples
726     ///
727     /// ```
728     /// use std::ffi::{OsStr, OsString};
729     ///
730     /// let os_str = OsStr::new("foo");
731     /// let os_string = os_str.to_os_string();
732     /// assert_eq!(os_string, OsString::from("foo"));
733     /// ```
734     #[stable(feature = "rust1", since = "1.0.0")]
735     #[must_use = "this returns the result of the operation, \
736                   without modifying the original"]
737     #[inline]
738     pub fn to_os_string(&self) -> OsString {
739         OsString { inner: self.inner.to_owned() }
740     }
741
742     /// Checks whether the `OsStr` is empty.
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// use std::ffi::OsStr;
748     ///
749     /// let os_str = OsStr::new("");
750     /// assert!(os_str.is_empty());
751     ///
752     /// let os_str = OsStr::new("foo");
753     /// assert!(!os_str.is_empty());
754     /// ```
755     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
756     #[must_use]
757     #[inline]
758     pub fn is_empty(&self) -> bool {
759         self.inner.inner.is_empty()
760     }
761
762     /// Returns the length of this `OsStr`.
763     ///
764     /// Note that this does **not** return the number of bytes in the string in
765     /// OS string form.
766     ///
767     /// The length returned is that of the underlying storage used by `OsStr`.
768     /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
769     /// store strings in a form best suited for cheap inter-conversion between
770     /// native-platform and Rust string forms, which may differ significantly
771     /// from both of them, including in storage size and encoding.
772     ///
773     /// This number is simply useful for passing to other methods, like
774     /// [`OsString::with_capacity`] to avoid reallocations.
775     ///
776     /// # Examples
777     ///
778     /// ```
779     /// use std::ffi::OsStr;
780     ///
781     /// let os_str = OsStr::new("");
782     /// assert_eq!(os_str.len(), 0);
783     ///
784     /// let os_str = OsStr::new("foo");
785     /// assert_eq!(os_str.len(), 3);
786     /// ```
787     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
788     #[must_use]
789     #[inline]
790     pub fn len(&self) -> usize {
791         self.inner.inner.len()
792     }
793
794     /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or allocating.
795     #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
796     #[must_use = "`self` will be dropped if the result is not used"]
797     pub fn into_os_string(self: Box<OsStr>) -> OsString {
798         let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
799         OsString { inner: Buf::from_box(boxed) }
800     }
801
802     /// Gets the underlying byte representation.
803     ///
804     /// Note: it is *crucial* that this API is not externally public, to avoid
805     /// revealing the internal, platform-specific encodings.
806     #[inline]
807     pub(crate) fn bytes(&self) -> &[u8] {
808         unsafe { &*(&self.inner as *const _ as *const [u8]) }
809     }
810
811     /// Converts this string to its ASCII lower case equivalent in-place.
812     ///
813     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
814     /// but non-ASCII letters are unchanged.
815     ///
816     /// To return a new lowercased value without modifying the existing one, use
817     /// [`OsStr::to_ascii_lowercase`].
818     ///
819     /// # Examples
820     ///
821     /// ```
822     /// use std::ffi::OsString;
823     ///
824     /// let mut s = OsString::from("GRÜßE, JÜRGEN ❤");
825     ///
826     /// s.make_ascii_lowercase();
827     ///
828     /// assert_eq!("grÜße, jÜrgen ❤", s);
829     /// ```
830     #[stable(feature = "osstring_ascii", since = "1.53.0")]
831     #[inline]
832     pub fn make_ascii_lowercase(&mut self) {
833         self.inner.make_ascii_lowercase()
834     }
835
836     /// Converts this string to its ASCII upper case equivalent in-place.
837     ///
838     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
839     /// but non-ASCII letters are unchanged.
840     ///
841     /// To return a new uppercased value without modifying the existing one, use
842     /// [`OsStr::to_ascii_uppercase`].
843     ///
844     /// # Examples
845     ///
846     /// ```
847     /// use std::ffi::OsString;
848     ///
849     /// let mut s = OsString::from("Grüße, Jürgen ❤");
850     ///
851     /// s.make_ascii_uppercase();
852     ///
853     /// assert_eq!("GRüßE, JüRGEN ❤", s);
854     /// ```
855     #[stable(feature = "osstring_ascii", since = "1.53.0")]
856     #[inline]
857     pub fn make_ascii_uppercase(&mut self) {
858         self.inner.make_ascii_uppercase()
859     }
860
861     /// Returns a copy of this string where each character is mapped to its
862     /// ASCII lower case equivalent.
863     ///
864     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
865     /// but non-ASCII letters are unchanged.
866     ///
867     /// To lowercase the value in-place, use [`OsStr::make_ascii_lowercase`].
868     ///
869     /// # Examples
870     ///
871     /// ```
872     /// use std::ffi::OsString;
873     /// let s = OsString::from("Grüße, Jürgen ❤");
874     ///
875     /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
876     /// ```
877     #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase`"]
878     #[stable(feature = "osstring_ascii", since = "1.53.0")]
879     pub fn to_ascii_lowercase(&self) -> OsString {
880         OsString::from_inner(self.inner.to_ascii_lowercase())
881     }
882
883     /// Returns a copy of this string where each character is mapped to its
884     /// ASCII upper case equivalent.
885     ///
886     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
887     /// but non-ASCII letters are unchanged.
888     ///
889     /// To uppercase the value in-place, use [`OsStr::make_ascii_uppercase`].
890     ///
891     /// # Examples
892     ///
893     /// ```
894     /// use std::ffi::OsString;
895     /// let s = OsString::from("Grüße, Jürgen ❤");
896     ///
897     /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
898     /// ```
899     #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase`"]
900     #[stable(feature = "osstring_ascii", since = "1.53.0")]
901     pub fn to_ascii_uppercase(&self) -> OsString {
902         OsString::from_inner(self.inner.to_ascii_uppercase())
903     }
904
905     /// Checks if all characters in this string are within the ASCII range.
906     ///
907     /// # Examples
908     ///
909     /// ```
910     /// use std::ffi::OsString;
911     ///
912     /// let ascii = OsString::from("hello!\n");
913     /// let non_ascii = OsString::from("Grüße, Jürgen ❤");
914     ///
915     /// assert!(ascii.is_ascii());
916     /// assert!(!non_ascii.is_ascii());
917     /// ```
918     #[stable(feature = "osstring_ascii", since = "1.53.0")]
919     #[must_use]
920     #[inline]
921     pub fn is_ascii(&self) -> bool {
922         self.inner.is_ascii()
923     }
924
925     /// Checks that two strings are an ASCII case-insensitive match.
926     ///
927     /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
928     /// but without allocating and copying temporaries.
929     ///
930     /// # Examples
931     ///
932     /// ```
933     /// use std::ffi::OsString;
934     ///
935     /// assert!(OsString::from("Ferris").eq_ignore_ascii_case("FERRIS"));
936     /// assert!(OsString::from("Ferrös").eq_ignore_ascii_case("FERRöS"));
937     /// assert!(!OsString::from("Ferrös").eq_ignore_ascii_case("FERRÖS"));
938     /// ```
939     #[stable(feature = "osstring_ascii", since = "1.53.0")]
940     pub fn eq_ignore_ascii_case<S: AsRef<OsStr>>(&self, other: S) -> bool {
941         self.inner.eq_ignore_ascii_case(&other.as_ref().inner)
942     }
943 }
944
945 #[stable(feature = "box_from_os_str", since = "1.17.0")]
946 impl From<&OsStr> for Box<OsStr> {
947     /// Copies the string into a newly allocated <code>[Box]&lt;[OsStr]&gt;</code>.
948     #[inline]
949     fn from(s: &OsStr) -> Box<OsStr> {
950         let rw = Box::into_raw(s.inner.into_box()) as *mut OsStr;
951         unsafe { Box::from_raw(rw) }
952     }
953 }
954
955 #[stable(feature = "box_from_cow", since = "1.45.0")]
956 impl From<Cow<'_, OsStr>> for Box<OsStr> {
957     /// Converts a `Cow<'a, OsStr>` into a <code>[Box]&lt;[OsStr]&gt;</code>,
958     /// by copying the contents if they are borrowed.
959     #[inline]
960     fn from(cow: Cow<'_, OsStr>) -> Box<OsStr> {
961         match cow {
962             Cow::Borrowed(s) => Box::from(s),
963             Cow::Owned(s) => Box::from(s),
964         }
965     }
966 }
967
968 #[stable(feature = "os_string_from_box", since = "1.18.0")]
969 impl From<Box<OsStr>> for OsString {
970     /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or
971     /// allocating.
972     #[inline]
973     fn from(boxed: Box<OsStr>) -> OsString {
974         boxed.into_os_string()
975     }
976 }
977
978 #[stable(feature = "box_from_os_string", since = "1.20.0")]
979 impl From<OsString> for Box<OsStr> {
980     /// Converts an [`OsString`] into a <code>[Box]<[OsStr]></code> without copying or allocating.
981     #[inline]
982     fn from(s: OsString) -> Box<OsStr> {
983         s.into_boxed_os_str()
984     }
985 }
986
987 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
988 impl Clone for Box<OsStr> {
989     #[inline]
990     fn clone(&self) -> Self {
991         self.to_os_string().into_boxed_os_str()
992     }
993 }
994
995 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
996 impl From<OsString> for Arc<OsStr> {
997     /// Converts an [`OsString`] into an <code>[Arc]<[OsStr]></code> by moving the [`OsString`]
998     /// data into a new [`Arc`] buffer.
999     #[inline]
1000     fn from(s: OsString) -> Arc<OsStr> {
1001         let arc = s.inner.into_arc();
1002         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1003     }
1004 }
1005
1006 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1007 impl From<&OsStr> for Arc<OsStr> {
1008     /// Copies the string into a newly allocated <code>[Arc]&lt;[OsStr]&gt;</code>.
1009     #[inline]
1010     fn from(s: &OsStr) -> Arc<OsStr> {
1011         let arc = s.inner.into_arc();
1012         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1013     }
1014 }
1015
1016 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1017 impl From<OsString> for Rc<OsStr> {
1018     /// Converts an [`OsString`] into an <code>[Rc]<[OsStr]></code> by moving the [`OsString`]
1019     /// data into a new [`Rc`] buffer.
1020     #[inline]
1021     fn from(s: OsString) -> Rc<OsStr> {
1022         let rc = s.inner.into_rc();
1023         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1024     }
1025 }
1026
1027 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1028 impl From<&OsStr> for Rc<OsStr> {
1029     /// Copies the string into a newly allocated <code>[Rc]&lt;[OsStr]&gt;</code>.
1030     #[inline]
1031     fn from(s: &OsStr) -> Rc<OsStr> {
1032         let rc = s.inner.into_rc();
1033         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1034     }
1035 }
1036
1037 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1038 impl<'a> From<OsString> for Cow<'a, OsStr> {
1039     /// Moves the string into a [`Cow::Owned`].
1040     #[inline]
1041     fn from(s: OsString) -> Cow<'a, OsStr> {
1042         Cow::Owned(s)
1043     }
1044 }
1045
1046 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1047 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
1048     /// Converts the string reference into a [`Cow::Borrowed`].
1049     #[inline]
1050     fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
1051         Cow::Borrowed(s)
1052     }
1053 }
1054
1055 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1056 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
1057     /// Converts the string reference into a [`Cow::Borrowed`].
1058     #[inline]
1059     fn from(s: &'a OsString) -> Cow<'a, OsStr> {
1060         Cow::Borrowed(s.as_os_str())
1061     }
1062 }
1063
1064 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
1065 impl<'a> From<Cow<'a, OsStr>> for OsString {
1066     /// Converts a `Cow<'a, OsStr>` into an [`OsString`],
1067     /// by copying the contents if they are borrowed.
1068     #[inline]
1069     fn from(s: Cow<'a, OsStr>) -> Self {
1070         s.into_owned()
1071     }
1072 }
1073
1074 #[stable(feature = "box_default_extra", since = "1.17.0")]
1075 impl Default for Box<OsStr> {
1076     #[inline]
1077     fn default() -> Box<OsStr> {
1078         let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
1079         unsafe { Box::from_raw(rw) }
1080     }
1081 }
1082
1083 #[stable(feature = "osstring_default", since = "1.9.0")]
1084 impl Default for &OsStr {
1085     /// Creates an empty `OsStr`.
1086     #[inline]
1087     fn default() -> Self {
1088         OsStr::new("")
1089     }
1090 }
1091
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 impl PartialEq for OsStr {
1094     #[inline]
1095     fn eq(&self, other: &OsStr) -> bool {
1096         self.bytes().eq(other.bytes())
1097     }
1098 }
1099
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl PartialEq<str> for OsStr {
1102     #[inline]
1103     fn eq(&self, other: &str) -> bool {
1104         *self == *OsStr::new(other)
1105     }
1106 }
1107
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl PartialEq<OsStr> for str {
1110     #[inline]
1111     fn eq(&self, other: &OsStr) -> bool {
1112         *other == *OsStr::new(self)
1113     }
1114 }
1115
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl Eq for OsStr {}
1118
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl PartialOrd for OsStr {
1121     #[inline]
1122     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1123         self.bytes().partial_cmp(other.bytes())
1124     }
1125     #[inline]
1126     fn lt(&self, other: &OsStr) -> bool {
1127         self.bytes().lt(other.bytes())
1128     }
1129     #[inline]
1130     fn le(&self, other: &OsStr) -> bool {
1131         self.bytes().le(other.bytes())
1132     }
1133     #[inline]
1134     fn gt(&self, other: &OsStr) -> bool {
1135         self.bytes().gt(other.bytes())
1136     }
1137     #[inline]
1138     fn ge(&self, other: &OsStr) -> bool {
1139         self.bytes().ge(other.bytes())
1140     }
1141 }
1142
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl PartialOrd<str> for OsStr {
1145     #[inline]
1146     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1147         self.partial_cmp(OsStr::new(other))
1148     }
1149 }
1150
1151 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1152 // have more flexible coherence rules.
1153
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl Ord for OsStr {
1156     #[inline]
1157     fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1158         self.bytes().cmp(other.bytes())
1159     }
1160 }
1161
1162 macro_rules! impl_cmp {
1163     ($lhs:ty, $rhs: ty) => {
1164         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1165         impl<'a, 'b> PartialEq<$rhs> for $lhs {
1166             #[inline]
1167             fn eq(&self, other: &$rhs) -> bool {
1168                 <OsStr as PartialEq>::eq(self, other)
1169             }
1170         }
1171
1172         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1173         impl<'a, 'b> PartialEq<$lhs> for $rhs {
1174             #[inline]
1175             fn eq(&self, other: &$lhs) -> bool {
1176                 <OsStr as PartialEq>::eq(self, other)
1177             }
1178         }
1179
1180         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1181         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
1182             #[inline]
1183             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1184                 <OsStr as PartialOrd>::partial_cmp(self, other)
1185             }
1186         }
1187
1188         #[stable(feature = "cmp_os_str", since = "1.8.0")]
1189         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
1190             #[inline]
1191             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1192                 <OsStr as PartialOrd>::partial_cmp(self, other)
1193             }
1194         }
1195     };
1196 }
1197
1198 impl_cmp!(OsString, OsStr);
1199 impl_cmp!(OsString, &'a OsStr);
1200 impl_cmp!(Cow<'a, OsStr>, OsStr);
1201 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
1202 impl_cmp!(Cow<'a, OsStr>, OsString);
1203
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 impl Hash for OsStr {
1206     #[inline]
1207     fn hash<H: Hasher>(&self, state: &mut H) {
1208         self.bytes().hash(state)
1209     }
1210 }
1211
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 impl fmt::Debug for OsStr {
1214     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1215         fmt::Debug::fmt(&self.inner, formatter)
1216     }
1217 }
1218
1219 impl OsStr {
1220     pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1221         fmt::Display::fmt(&self.inner, formatter)
1222     }
1223 }
1224
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl Borrow<OsStr> for OsString {
1227     #[inline]
1228     fn borrow(&self) -> &OsStr {
1229         &self[..]
1230     }
1231 }
1232
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl ToOwned for OsStr {
1235     type Owned = OsString;
1236     #[inline]
1237     fn to_owned(&self) -> OsString {
1238         self.to_os_string()
1239     }
1240     #[inline]
1241     fn clone_into(&self, target: &mut OsString) {
1242         self.inner.clone_into(&mut target.inner)
1243     }
1244 }
1245
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 impl AsRef<OsStr> for OsStr {
1248     #[inline]
1249     fn as_ref(&self) -> &OsStr {
1250         self
1251     }
1252 }
1253
1254 #[stable(feature = "rust1", since = "1.0.0")]
1255 impl AsRef<OsStr> for OsString {
1256     #[inline]
1257     fn as_ref(&self) -> &OsStr {
1258         self
1259     }
1260 }
1261
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl AsRef<OsStr> for str {
1264     #[inline]
1265     fn as_ref(&self) -> &OsStr {
1266         OsStr::from_inner(Slice::from_str(self))
1267     }
1268 }
1269
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 impl AsRef<OsStr> for String {
1272     #[inline]
1273     fn as_ref(&self) -> &OsStr {
1274         (&**self).as_ref()
1275     }
1276 }
1277
1278 impl FromInner<Buf> for OsString {
1279     #[inline]
1280     fn from_inner(buf: Buf) -> OsString {
1281         OsString { inner: buf }
1282     }
1283 }
1284
1285 impl IntoInner<Buf> for OsString {
1286     #[inline]
1287     fn into_inner(self) -> Buf {
1288         self.inner
1289     }
1290 }
1291
1292 impl AsInner<Slice> for OsStr {
1293     #[inline]
1294     fn as_inner(&self) -> &Slice {
1295         &self.inner
1296     }
1297 }
1298
1299 #[stable(feature = "osstring_from_str", since = "1.45.0")]
1300 impl FromStr for OsString {
1301     type Err = core::convert::Infallible;
1302
1303     #[inline]
1304     fn from_str(s: &str) -> Result<Self, Self::Err> {
1305         Ok(OsString::from(s))
1306     }
1307 }
1308
1309 #[stable(feature = "osstring_extend", since = "1.52.0")]
1310 impl Extend<OsString> for OsString {
1311     #[inline]
1312     fn extend<T: IntoIterator<Item = OsString>>(&mut self, iter: T) {
1313         for s in iter {
1314             self.push(&s);
1315         }
1316     }
1317 }
1318
1319 #[stable(feature = "osstring_extend", since = "1.52.0")]
1320 impl<'a> Extend<&'a OsStr> for OsString {
1321     #[inline]
1322     fn extend<T: IntoIterator<Item = &'a OsStr>>(&mut self, iter: T) {
1323         for s in iter {
1324             self.push(s);
1325         }
1326     }
1327 }
1328
1329 #[stable(feature = "osstring_extend", since = "1.52.0")]
1330 impl<'a> Extend<Cow<'a, OsStr>> for OsString {
1331     #[inline]
1332     fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: T) {
1333         for s in iter {
1334             self.push(&s);
1335         }
1336     }
1337 }
1338
1339 #[stable(feature = "osstring_extend", since = "1.52.0")]
1340 impl FromIterator<OsString> for OsString {
1341     #[inline]
1342     fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1343         let mut iterator = iter.into_iter();
1344
1345         // Because we're iterating over `OsString`s, we can avoid at least
1346         // one allocation by getting the first string from the iterator
1347         // and appending to it all the subsequent strings.
1348         match iterator.next() {
1349             None => OsString::new(),
1350             Some(mut buf) => {
1351                 buf.extend(iterator);
1352                 buf
1353             }
1354         }
1355     }
1356 }
1357
1358 #[stable(feature = "osstring_extend", since = "1.52.0")]
1359 impl<'a> FromIterator<&'a OsStr> for OsString {
1360     #[inline]
1361     fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self {
1362         let mut buf = Self::new();
1363         for s in iter {
1364             buf.push(s);
1365         }
1366         buf
1367     }
1368 }
1369
1370 #[stable(feature = "osstring_extend", since = "1.52.0")]
1371 impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
1372     #[inline]
1373     fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
1374         let mut iterator = iter.into_iter();
1375
1376         // Because we're iterating over `OsString`s, we can avoid at least
1377         // one allocation by getting the first owned string from the iterator
1378         // and appending to it all the subsequent strings.
1379         match iterator.next() {
1380             None => OsString::new(),
1381             Some(Cow::Owned(mut buf)) => {
1382                 buf.extend(iterator);
1383                 buf
1384             }
1385             Some(Cow::Borrowed(buf)) => {
1386                 let mut buf = OsString::from(buf);
1387                 buf.extend(iterator);
1388                 buf
1389             }
1390         }
1391     }
1392 }