4 use crate::borrow::{Borrow, Cow};
6 use crate::collections::TryReserveError;
8 use crate::hash::{Hash, Hasher};
9 use crate::iter::Extend;
12 use crate::str::FromStr;
15 use crate::sys::os_str::{Buf, Slice};
16 use crate::sys_common::{AsInner, FromInner, IntoInner};
18 /// A type that can represent owned, mutable platform-native strings, but is
19 /// cheaply inter-convertible with Rust strings.
21 /// The need for this type arises from the fact that:
23 /// * On Unix systems, strings are often arbitrary sequences of non-zero
24 /// bytes, in many cases interpreted as UTF-8.
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.
29 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
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`].
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
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.
48 /// # Creating an `OsString`
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.
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.
60 /// # Extracting a borrowed reference to the whole OS string
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
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.
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")]
80 /// Allows extension traits within `std`.
81 #[unstable(feature = "sealed", issue = "none")]
82 impl crate::sealed::Sealed for OsString {}
84 /// Borrowed reference to an OS string (see [`OsString`]).
86 /// This type represents a borrowed reference to a string in the operating system's preferred
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.
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.
95 /// [conversions]: super#conversions
96 #[cfg_attr(not(test), rustc_diagnostic_item = "OsStr")]
97 #[stable(feature = "rust1", since = "1.0.0")]
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.
108 /// Allows extension traits within `std`.
109 #[unstable(feature = "sealed", issue = "none")]
110 impl crate::sealed::Sealed for OsStr {}
113 /// Constructs a new empty `OsString`.
118 /// use std::ffi::OsString;
120 /// let os_string = OsString::new();
122 #[stable(feature = "rust1", since = "1.0.0")]
125 pub fn new() -> OsString {
126 OsString { inner: Buf::from_string(String::new()) }
129 /// Converts to an [`OsStr`] slice.
134 /// use std::ffi::{OsString, OsStr};
136 /// let os_string = OsString::from("foo");
137 /// let os_str = OsStr::new("foo");
138 /// assert_eq!(os_string.as_os_str(), os_str);
140 #[stable(feature = "rust1", since = "1.0.0")]
143 pub fn as_os_str(&self) -> &OsStr {
147 /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
149 /// On failure, ownership of the original `OsString` is returned.
154 /// use std::ffi::OsString;
156 /// let os_string = OsString::from("foo");
157 /// let string = os_string.into_string();
158 /// assert_eq!(string, Ok(String::from("foo")));
160 #[stable(feature = "rust1", since = "1.0.0")]
162 pub fn into_string(self) -> Result<String, OsString> {
163 self.inner.into_string().map_err(|buf| OsString { inner: buf })
166 /// Extends the string with the given <code>&[OsStr]</code> slice.
171 /// use std::ffi::OsString;
173 /// let mut os_string = OsString::from("foo");
174 /// os_string.push("bar");
175 /// assert_eq!(&os_string, "foobar");
177 #[stable(feature = "rust1", since = "1.0.0")]
179 pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
180 self.inner.push_slice(&s.as_ref().inner)
183 /// Creates a new `OsString` with the given capacity.
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
189 /// See main `OsString` documentation information about encoding.
194 /// use std::ffi::OsString;
196 /// let mut os_string = OsString::with_capacity(10);
197 /// let capacity = os_string.capacity();
199 /// // This push is done without reallocating
200 /// os_string.push("foo");
202 /// assert_eq!(capacity, os_string.capacity());
204 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
207 pub fn with_capacity(capacity: usize) -> OsString {
208 OsString { inner: Buf::with_capacity(capacity) }
211 /// Truncates the `OsString` to zero length.
216 /// use std::ffi::OsString;
218 /// let mut os_string = OsString::from("foo");
219 /// assert_eq!(&os_string, "foo");
221 /// os_string.clear();
222 /// assert_eq!(&os_string, "");
224 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
226 pub fn clear(&mut self) {
230 /// Returns the capacity this `OsString` can hold without reallocating.
232 /// See `OsString` introduction for information about encoding.
237 /// use std::ffi::OsString;
239 /// let os_string = OsString::with_capacity(10);
240 /// assert!(os_string.capacity() >= 10);
242 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
245 pub fn capacity(&self) -> usize {
246 self.inner.capacity()
249 /// Reserves capacity for at least `additional` more capacity to be inserted
250 /// in the given `OsString`.
252 /// The collection may reserve more space to avoid frequent reallocations.
257 /// use std::ffi::OsString;
259 /// let mut s = OsString::new();
261 /// assert!(s.capacity() >= 10);
263 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
265 pub fn reserve(&mut self, additional: usize) {
266 self.inner.reserve(additional)
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.
277 /// If the capacity overflows, or the allocator reports a failure, then an error
283 /// #![feature(try_reserve_2)]
284 /// use std::ffi::{OsStr, OsString};
285 /// use std::collections::TryReserveError;
287 /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
288 /// let mut s = OsString::new();
290 /// // Pre-reserve the memory, exiting if we can't
291 /// s.try_reserve(OsStr::new(data).len())?;
293 /// // Now we know this can't OOM in the middle of our complex work
298 /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
300 #[unstable(feature = "try_reserve_2", issue = "91789")]
302 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
303 self.inner.try_reserve(additional)
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.
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.
314 /// [`reserve`]: OsString::reserve
319 /// use std::ffi::OsString;
321 /// let mut s = OsString::new();
322 /// s.reserve_exact(10);
323 /// assert!(s.capacity() >= 10);
325 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
327 pub fn reserve_exact(&mut self, additional: usize) {
328 self.inner.reserve_exact(additional)
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.
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.
341 /// [`try_reserve`]: OsString::try_reserve
345 /// If the capacity overflows, or the allocator reports a failure, then an error
351 /// #![feature(try_reserve_2)]
352 /// use std::ffi::{OsStr, OsString};
353 /// use std::collections::TryReserveError;
355 /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
356 /// let mut s = OsString::new();
358 /// // Pre-reserve the memory, exiting if we can't
359 /// s.try_reserve_exact(OsStr::new(data).len())?;
361 /// // Now we know this can't OOM in the middle of our complex work
366 /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
368 #[unstable(feature = "try_reserve_2", issue = "91789")]
370 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
371 self.inner.try_reserve_exact(additional)
374 /// Shrinks the capacity of the `OsString` to match its length.
379 /// use std::ffi::OsString;
381 /// let mut s = OsString::from("foo");
384 /// assert!(s.capacity() >= 100);
386 /// s.shrink_to_fit();
387 /// assert_eq!(3, s.capacity());
389 #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
391 pub fn shrink_to_fit(&mut self) {
392 self.inner.shrink_to_fit()
395 /// Shrinks the capacity of the `OsString` with a lower bound.
397 /// The capacity will remain at least as large as both the length
398 /// and the supplied value.
400 /// If the current capacity is less than the lower limit, this is a no-op.
405 /// use std::ffi::OsString;
407 /// let mut s = OsString::from("foo");
410 /// assert!(s.capacity() >= 100);
413 /// assert!(s.capacity() >= 10);
415 /// assert!(s.capacity() >= 3);
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)
423 /// Converts this `OsString` into a boxed [`OsStr`].
428 /// use std::ffi::{OsString, OsStr};
430 /// let s = OsString::from("hello");
432 /// let b: Box<OsStr> = s.into_boxed_os_str();
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) }
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl From<String> for OsString {
444 /// Converts a [`String`] into an [`OsString`].
446 /// This conversion does not allocate or copy memory.
448 fn from(s: String) -> OsString {
449 OsString { inner: Buf::from_string(s) }
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]<[OsStr]></code>
456 /// into a newly allocated [`OsString`].
457 fn from(s: &T) -> OsString {
458 s.as_ref().to_os_string()
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl ops::Index<ops::RangeFull> for OsString {
467 fn index(&self, _index: ops::RangeFull) -> &OsStr {
468 OsStr::from_inner(self.inner.as_slice())
472 #[stable(feature = "mut_osstr", since = "1.44.0")]
473 impl ops::IndexMut<ops::RangeFull> for OsString {
475 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut OsStr {
476 OsStr::from_inner_mut(self.inner.as_mut_slice())
480 #[stable(feature = "rust1", since = "1.0.0")]
481 impl ops::Deref for OsString {
485 fn deref(&self) -> &OsStr {
490 #[stable(feature = "mut_osstr", since = "1.44.0")]
491 impl ops::DerefMut for OsString {
493 fn deref_mut(&mut self) -> &mut OsStr {
498 #[stable(feature = "osstring_default", since = "1.9.0")]
499 impl Default for OsString {
500 /// Constructs an empty `OsString`.
502 fn default() -> OsString {
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl Clone for OsString {
510 fn clone(&self) -> Self {
511 OsString { inner: self.inner.clone() }
515 fn clone_from(&mut self, source: &Self) {
516 self.inner.clone_from(&source.inner)
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)
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl PartialEq for OsString {
530 fn eq(&self, other: &OsString) -> bool {
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl PartialEq<str> for OsString {
538 fn eq(&self, other: &str) -> bool {
543 #[stable(feature = "rust1", since = "1.0.0")]
544 impl PartialEq<OsString> for str {
546 fn eq(&self, other: &OsString) -> bool {
551 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
552 impl PartialEq<&str> for OsString {
554 fn eq(&self, other: &&str) -> bool {
559 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
560 impl<'a> PartialEq<OsString> for &'a str {
562 fn eq(&self, other: &OsString) -> bool {
567 #[stable(feature = "rust1", since = "1.0.0")]
568 impl Eq for OsString {}
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl PartialOrd for OsString {
573 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
574 (&**self).partial_cmp(&**other)
577 fn lt(&self, other: &OsString) -> bool {
581 fn le(&self, other: &OsString) -> bool {
585 fn gt(&self, other: &OsString) -> bool {
589 fn ge(&self, other: &OsString) -> bool {
594 #[stable(feature = "rust1", since = "1.0.0")]
595 impl PartialOrd<str> for OsString {
597 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
598 (&**self).partial_cmp(other)
602 #[stable(feature = "rust1", since = "1.0.0")]
603 impl Ord for OsString {
605 fn cmp(&self, other: &OsString) -> cmp::Ordering {
606 (&**self).cmp(&**other)
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl Hash for OsString {
613 fn hash<H: Hasher>(&self, state: &mut H) {
614 (&**self).hash(state)
619 /// Coerces into an `OsStr` slice.
624 /// use std::ffi::OsStr;
626 /// let os_str = OsStr::new("foo");
629 #[stable(feature = "rust1", since = "1.0.0")]
630 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
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) }
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) }
650 /// Yields a <code>&[str]</code> slice if the `OsStr` is valid Unicode.
652 /// This conversion may entail doing a check for UTF-8 validity.
657 /// use std::ffi::OsStr;
659 /// let os_str = OsStr::new("foo");
660 /// assert_eq!(os_str.to_str(), Some("foo"));
662 #[stable(feature = "rust1", since = "1.0.0")]
663 #[must_use = "this returns the result of the operation, \
664 without modifying the original"]
666 pub fn to_str(&self) -> Option<&str> {
670 /// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
672 /// Any non-Unicode sequences are replaced with
673 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
675 /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
679 /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
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
690 /// use std::ffi::OsStr;
691 /// use std::os::unix::ffi::OsStrExt;
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[..]);
699 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
701 /// #[cfg(windows)] {
702 /// use std::ffi::OsString;
703 /// use std::os::windows::prelude::*;
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();
712 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
715 #[stable(feature = "rust1", since = "1.0.0")]
716 #[must_use = "this returns the result of the operation, \
717 without modifying the original"]
719 pub fn to_string_lossy(&self) -> Cow<'_, str> {
720 self.inner.to_string_lossy()
723 /// Copies the slice into an owned [`OsString`].
728 /// use std::ffi::{OsStr, OsString};
730 /// let os_str = OsStr::new("foo");
731 /// let os_string = os_str.to_os_string();
732 /// assert_eq!(os_string, OsString::from("foo"));
734 #[stable(feature = "rust1", since = "1.0.0")]
735 #[must_use = "this returns the result of the operation, \
736 without modifying the original"]
738 pub fn to_os_string(&self) -> OsString {
739 OsString { inner: self.inner.to_owned() }
742 /// Checks whether the `OsStr` is empty.
747 /// use std::ffi::OsStr;
749 /// let os_str = OsStr::new("");
750 /// assert!(os_str.is_empty());
752 /// let os_str = OsStr::new("foo");
753 /// assert!(!os_str.is_empty());
755 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
758 pub fn is_empty(&self) -> bool {
759 self.inner.inner.is_empty()
762 /// Returns the length of this `OsStr`.
764 /// Note that this does **not** return the number of bytes in the string in
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.
773 /// This number is simply useful for passing to other methods, like
774 /// [`OsString::with_capacity`] to avoid reallocations.
779 /// use std::ffi::OsStr;
781 /// let os_str = OsStr::new("");
782 /// assert_eq!(os_str.len(), 0);
784 /// let os_str = OsStr::new("foo");
785 /// assert_eq!(os_str.len(), 3);
787 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
790 pub fn len(&self) -> usize {
791 self.inner.inner.len()
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) }
802 /// Gets the underlying byte representation.
804 /// Note: it is *crucial* that this API is not externally public, to avoid
805 /// revealing the internal, platform-specific encodings.
807 pub(crate) fn bytes(&self) -> &[u8] {
808 unsafe { &*(&self.inner as *const _ as *const [u8]) }
811 /// Converts this string to its ASCII lower case equivalent in-place.
813 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
814 /// but non-ASCII letters are unchanged.
816 /// To return a new lowercased value without modifying the existing one, use
817 /// [`OsStr::to_ascii_lowercase`].
822 /// use std::ffi::OsString;
824 /// let mut s = OsString::from("GRÜßE, JÜRGEN ❤");
826 /// s.make_ascii_lowercase();
828 /// assert_eq!("grÜße, jÜrgen ❤", s);
830 #[stable(feature = "osstring_ascii", since = "1.53.0")]
832 pub fn make_ascii_lowercase(&mut self) {
833 self.inner.make_ascii_lowercase()
836 /// Converts this string to its ASCII upper case equivalent in-place.
838 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
839 /// but non-ASCII letters are unchanged.
841 /// To return a new uppercased value without modifying the existing one, use
842 /// [`OsStr::to_ascii_uppercase`].
847 /// use std::ffi::OsString;
849 /// let mut s = OsString::from("Grüße, Jürgen ❤");
851 /// s.make_ascii_uppercase();
853 /// assert_eq!("GRüßE, JüRGEN ❤", s);
855 #[stable(feature = "osstring_ascii", since = "1.53.0")]
857 pub fn make_ascii_uppercase(&mut self) {
858 self.inner.make_ascii_uppercase()
861 /// Returns a copy of this string where each character is mapped to its
862 /// ASCII lower case equivalent.
864 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
865 /// but non-ASCII letters are unchanged.
867 /// To lowercase the value in-place, use [`OsStr::make_ascii_lowercase`].
872 /// use std::ffi::OsString;
873 /// let s = OsString::from("Grüße, Jürgen ❤");
875 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
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())
883 /// Returns a copy of this string where each character is mapped to its
884 /// ASCII upper case equivalent.
886 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
887 /// but non-ASCII letters are unchanged.
889 /// To uppercase the value in-place, use [`OsStr::make_ascii_uppercase`].
894 /// use std::ffi::OsString;
895 /// let s = OsString::from("Grüße, Jürgen ❤");
897 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
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())
905 /// Checks if all characters in this string are within the ASCII range.
910 /// use std::ffi::OsString;
912 /// let ascii = OsString::from("hello!\n");
913 /// let non_ascii = OsString::from("Grüße, Jürgen ❤");
915 /// assert!(ascii.is_ascii());
916 /// assert!(!non_ascii.is_ascii());
918 #[stable(feature = "osstring_ascii", since = "1.53.0")]
921 pub fn is_ascii(&self) -> bool {
922 self.inner.is_ascii()
925 /// Checks that two strings are an ASCII case-insensitive match.
927 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
928 /// but without allocating and copying temporaries.
933 /// use std::ffi::OsString;
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"));
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)
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]<[OsStr]></code>.
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) }
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]<[OsStr]></code>,
958 /// by copying the contents if they are borrowed.
960 fn from(cow: Cow<'_, OsStr>) -> Box<OsStr> {
962 Cow::Borrowed(s) => Box::from(s),
963 Cow::Owned(s) => Box::from(s),
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
973 fn from(boxed: Box<OsStr>) -> OsString {
974 boxed.into_os_string()
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.
982 fn from(s: OsString) -> Box<OsStr> {
983 s.into_boxed_os_str()
987 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
988 impl Clone for Box<OsStr> {
990 fn clone(&self) -> Self {
991 self.to_os_string().into_boxed_os_str()
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.
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) }
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]<[OsStr]></code>.
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) }
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.
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) }
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]<[OsStr]></code>.
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) }
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`].
1041 fn from(s: OsString) -> Cow<'a, OsStr> {
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`].
1050 fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
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`].
1059 fn from(s: &'a OsString) -> Cow<'a, OsStr> {
1060 Cow::Borrowed(s.as_os_str())
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.
1069 fn from(s: Cow<'a, OsStr>) -> Self {
1074 #[stable(feature = "box_default_extra", since = "1.17.0")]
1075 impl Default for Box<OsStr> {
1077 fn default() -> Box<OsStr> {
1078 let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
1079 unsafe { Box::from_raw(rw) }
1083 #[stable(feature = "osstring_default", since = "1.9.0")]
1084 impl Default for &OsStr {
1085 /// Creates an empty `OsStr`.
1087 fn default() -> Self {
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 impl PartialEq for OsStr {
1095 fn eq(&self, other: &OsStr) -> bool {
1096 self.bytes().eq(other.bytes())
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl PartialEq<str> for OsStr {
1103 fn eq(&self, other: &str) -> bool {
1104 *self == *OsStr::new(other)
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl PartialEq<OsStr> for str {
1111 fn eq(&self, other: &OsStr) -> bool {
1112 *other == *OsStr::new(self)
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl Eq for OsStr {}
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 impl PartialOrd for OsStr {
1122 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1123 self.bytes().partial_cmp(other.bytes())
1126 fn lt(&self, other: &OsStr) -> bool {
1127 self.bytes().lt(other.bytes())
1130 fn le(&self, other: &OsStr) -> bool {
1131 self.bytes().le(other.bytes())
1134 fn gt(&self, other: &OsStr) -> bool {
1135 self.bytes().gt(other.bytes())
1138 fn ge(&self, other: &OsStr) -> bool {
1139 self.bytes().ge(other.bytes())
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 impl PartialOrd<str> for OsStr {
1146 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1147 self.partial_cmp(OsStr::new(other))
1151 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1152 // have more flexible coherence rules.
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl Ord for OsStr {
1157 fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1158 self.bytes().cmp(other.bytes())
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 {
1167 fn eq(&self, other: &$rhs) -> bool {
1168 <OsStr as PartialEq>::eq(self, other)
1172 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1173 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1175 fn eq(&self, other: &$lhs) -> bool {
1176 <OsStr as PartialEq>::eq(self, other)
1180 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1181 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
1183 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1184 <OsStr as PartialOrd>::partial_cmp(self, other)
1188 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1189 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
1191 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1192 <OsStr as PartialOrd>::partial_cmp(self, other)
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);
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 impl Hash for OsStr {
1207 fn hash<H: Hasher>(&self, state: &mut H) {
1208 self.bytes().hash(state)
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)
1220 pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1221 fmt::Display::fmt(&self.inner, formatter)
1225 #[unstable(feature = "slice_concat_ext", issue = "27747")]
1226 impl<S: Borrow<OsStr>> alloc::slice::Join<&OsStr> for [S] {
1227 type Output = OsString;
1229 fn join(slice: &Self, sep: &OsStr) -> OsString {
1230 let Some((first, suffix)) = slice.split_first() else {
1231 return OsString::new();
1233 let first_owned = first.borrow().to_owned();
1234 suffix.iter().fold(first_owned, |mut a, b| {
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl Borrow<OsStr> for OsString {
1245 fn borrow(&self) -> &OsStr {
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl ToOwned for OsStr {
1252 type Owned = OsString;
1254 fn to_owned(&self) -> OsString {
1258 fn clone_into(&self, target: &mut OsString) {
1259 self.inner.clone_into(&mut target.inner)
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 impl AsRef<OsStr> for OsStr {
1266 fn as_ref(&self) -> &OsStr {
1271 #[stable(feature = "rust1", since = "1.0.0")]
1272 impl AsRef<OsStr> for OsString {
1274 fn as_ref(&self) -> &OsStr {
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 impl AsRef<OsStr> for str {
1282 fn as_ref(&self) -> &OsStr {
1283 OsStr::from_inner(Slice::from_str(self))
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 impl AsRef<OsStr> for String {
1290 fn as_ref(&self) -> &OsStr {
1295 impl FromInner<Buf> for OsString {
1297 fn from_inner(buf: Buf) -> OsString {
1298 OsString { inner: buf }
1302 impl IntoInner<Buf> for OsString {
1304 fn into_inner(self) -> Buf {
1309 impl AsInner<Slice> for OsStr {
1311 fn as_inner(&self) -> &Slice {
1316 #[stable(feature = "osstring_from_str", since = "1.45.0")]
1317 impl FromStr for OsString {
1318 type Err = core::convert::Infallible;
1321 fn from_str(s: &str) -> Result<Self, Self::Err> {
1322 Ok(OsString::from(s))
1326 #[stable(feature = "osstring_extend", since = "1.52.0")]
1327 impl Extend<OsString> for OsString {
1329 fn extend<T: IntoIterator<Item = OsString>>(&mut self, iter: T) {
1336 #[stable(feature = "osstring_extend", since = "1.52.0")]
1337 impl<'a> Extend<&'a OsStr> for OsString {
1339 fn extend<T: IntoIterator<Item = &'a OsStr>>(&mut self, iter: T) {
1346 #[stable(feature = "osstring_extend", since = "1.52.0")]
1347 impl<'a> Extend<Cow<'a, OsStr>> for OsString {
1349 fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: T) {
1356 #[stable(feature = "osstring_extend", since = "1.52.0")]
1357 impl FromIterator<OsString> for OsString {
1359 fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1360 let mut iterator = iter.into_iter();
1362 // Because we're iterating over `OsString`s, we can avoid at least
1363 // one allocation by getting the first string from the iterator
1364 // and appending to it all the subsequent strings.
1365 match iterator.next() {
1366 None => OsString::new(),
1368 buf.extend(iterator);
1375 #[stable(feature = "osstring_extend", since = "1.52.0")]
1376 impl<'a> FromIterator<&'a OsStr> for OsString {
1378 fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self {
1379 let mut buf = Self::new();
1387 #[stable(feature = "osstring_extend", since = "1.52.0")]
1388 impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
1390 fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
1391 let mut iterator = iter.into_iter();
1393 // Because we're iterating over `OsString`s, we can avoid at least
1394 // one allocation by getting the first owned string from the iterator
1395 // and appending to it all the subsequent strings.
1396 match iterator.next() {
1397 None => OsString::new(),
1398 Some(Cow::Owned(mut buf)) => {
1399 buf.extend(iterator);
1402 Some(Cow::Borrowed(buf)) => {
1403 let mut buf = OsString::from(buf);
1404 buf.extend(iterator);