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