4 use crate::borrow::{Borrow, Cow};
6 use crate::collections::TryReserveError;
8 use crate::hash::{Hash, Hasher};
9 use crate::iter::{Extend, FromIterator};
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 fn from(s: &T) -> OsString {
456 s.as_ref().to_os_string()
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl ops::Index<ops::RangeFull> for OsString {
465 fn index(&self, _index: ops::RangeFull) -> &OsStr {
466 OsStr::from_inner(self.inner.as_slice())
470 #[stable(feature = "mut_osstr", since = "1.44.0")]
471 impl ops::IndexMut<ops::RangeFull> for OsString {
473 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut OsStr {
474 OsStr::from_inner_mut(self.inner.as_mut_slice())
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl ops::Deref for OsString {
483 fn deref(&self) -> &OsStr {
488 #[stable(feature = "mut_osstr", since = "1.44.0")]
489 impl ops::DerefMut for OsString {
491 fn deref_mut(&mut self) -> &mut OsStr {
496 #[stable(feature = "osstring_default", since = "1.9.0")]
497 impl Default for OsString {
498 /// Constructs an empty `OsString`.
500 fn default() -> OsString {
505 #[stable(feature = "rust1", since = "1.0.0")]
506 impl Clone for OsString {
508 fn clone(&self) -> Self {
509 OsString { inner: self.inner.clone() }
513 fn clone_from(&mut self, source: &Self) {
514 self.inner.clone_from(&source.inner)
518 #[stable(feature = "rust1", since = "1.0.0")]
519 impl fmt::Debug for OsString {
520 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
521 fmt::Debug::fmt(&**self, formatter)
525 #[stable(feature = "rust1", since = "1.0.0")]
526 impl PartialEq for OsString {
528 fn eq(&self, other: &OsString) -> bool {
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl PartialEq<str> for OsString {
536 fn eq(&self, other: &str) -> bool {
541 #[stable(feature = "rust1", since = "1.0.0")]
542 impl PartialEq<OsString> for str {
544 fn eq(&self, other: &OsString) -> bool {
549 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
550 impl PartialEq<&str> for OsString {
552 fn eq(&self, other: &&str) -> bool {
557 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
558 impl<'a> PartialEq<OsString> for &'a str {
560 fn eq(&self, other: &OsString) -> bool {
565 #[stable(feature = "rust1", since = "1.0.0")]
566 impl Eq for OsString {}
568 #[stable(feature = "rust1", since = "1.0.0")]
569 impl PartialOrd for OsString {
571 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
572 (&**self).partial_cmp(&**other)
575 fn lt(&self, other: &OsString) -> bool {
579 fn le(&self, other: &OsString) -> bool {
583 fn gt(&self, other: &OsString) -> bool {
587 fn ge(&self, other: &OsString) -> bool {
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl PartialOrd<str> for OsString {
595 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
596 (&**self).partial_cmp(other)
600 #[stable(feature = "rust1", since = "1.0.0")]
601 impl Ord for OsString {
603 fn cmp(&self, other: &OsString) -> cmp::Ordering {
604 (&**self).cmp(&**other)
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl Hash for OsString {
611 fn hash<H: Hasher>(&self, state: &mut H) {
612 (&**self).hash(state)
617 /// Coerces into an `OsStr` slice.
622 /// use std::ffi::OsStr;
624 /// let os_str = OsStr::new("foo");
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
633 fn from_inner(inner: &Slice) -> &OsStr {
634 // SAFETY: OsStr is just a wrapper of Slice,
635 // therefore converting &Slice to &OsStr is safe.
636 unsafe { &*(inner as *const Slice as *const OsStr) }
640 fn from_inner_mut(inner: &mut Slice) -> &mut OsStr {
641 // SAFETY: OsStr is just a wrapper of Slice,
642 // therefore converting &mut Slice to &mut OsStr is safe.
643 // Any method that mutates OsStr must be careful not to
644 // break platform-specific encoding, in particular Wtf8 on Windows.
645 unsafe { &mut *(inner as *mut Slice as *mut OsStr) }
648 /// Yields a <code>&[str]</code> slice if the `OsStr` is valid Unicode.
650 /// This conversion may entail doing a check for UTF-8 validity.
655 /// use std::ffi::OsStr;
657 /// let os_str = OsStr::new("foo");
658 /// assert_eq!(os_str.to_str(), Some("foo"));
660 #[stable(feature = "rust1", since = "1.0.0")]
661 #[must_use = "this returns the result of the operation, \
662 without modifying the original"]
664 pub fn to_str(&self) -> Option<&str> {
668 /// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
670 /// Any non-Unicode sequences are replaced with
671 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
673 /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
677 /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
680 /// // Note, due to differences in how Unix and Windows represent strings,
681 /// // we are forced to complicate this example, setting up example `OsStr`s
682 /// // with different source data and via different platform extensions.
683 /// // Understand that in reality you could end up with such example invalid
684 /// // sequences simply through collecting user command line arguments, for
688 /// use std::ffi::OsStr;
689 /// use std::os::unix::ffi::OsStrExt;
691 /// // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
692 /// // respectively. The value 0x80 is a lone continuation byte, invalid
693 /// // in a UTF-8 sequence.
694 /// let source = [0x66, 0x6f, 0x80, 0x6f];
695 /// let os_str = OsStr::from_bytes(&source[..]);
697 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
699 /// #[cfg(windows)] {
700 /// use std::ffi::OsString;
701 /// use std::os::windows::prelude::*;
703 /// // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
704 /// // respectively. The value 0xD800 is a lone surrogate half, invalid
705 /// // in a UTF-16 sequence.
706 /// let source = [0x0066, 0x006f, 0xD800, 0x006f];
707 /// let os_string = OsString::from_wide(&source[..]);
708 /// let os_str = os_string.as_os_str();
710 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
713 #[stable(feature = "rust1", since = "1.0.0")]
714 #[must_use = "this returns the result of the operation, \
715 without modifying the original"]
717 pub fn to_string_lossy(&self) -> Cow<'_, str> {
718 self.inner.to_string_lossy()
721 /// Copies the slice into an owned [`OsString`].
726 /// use std::ffi::{OsStr, OsString};
728 /// let os_str = OsStr::new("foo");
729 /// let os_string = os_str.to_os_string();
730 /// assert_eq!(os_string, OsString::from("foo"));
732 #[stable(feature = "rust1", since = "1.0.0")]
733 #[must_use = "this returns the result of the operation, \
734 without modifying the original"]
736 pub fn to_os_string(&self) -> OsString {
737 OsString { inner: self.inner.to_owned() }
740 /// Checks whether the `OsStr` is empty.
745 /// use std::ffi::OsStr;
747 /// let os_str = OsStr::new("");
748 /// assert!(os_str.is_empty());
750 /// let os_str = OsStr::new("foo");
751 /// assert!(!os_str.is_empty());
753 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
756 pub fn is_empty(&self) -> bool {
757 self.inner.inner.is_empty()
760 /// Returns the length of this `OsStr`.
762 /// Note that this does **not** return the number of bytes in the string in
765 /// The length returned is that of the underlying storage used by `OsStr`.
766 /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
767 /// store strings in a form best suited for cheap inter-conversion between
768 /// native-platform and Rust string forms, which may differ significantly
769 /// from both of them, including in storage size and encoding.
771 /// This number is simply useful for passing to other methods, like
772 /// [`OsString::with_capacity`] to avoid reallocations.
777 /// use std::ffi::OsStr;
779 /// let os_str = OsStr::new("");
780 /// assert_eq!(os_str.len(), 0);
782 /// let os_str = OsStr::new("foo");
783 /// assert_eq!(os_str.len(), 3);
785 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
788 pub fn len(&self) -> usize {
789 self.inner.inner.len()
792 /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or allocating.
793 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
794 #[must_use = "`self` will be dropped if the result is not used"]
795 pub fn into_os_string(self: Box<OsStr>) -> OsString {
796 let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
797 OsString { inner: Buf::from_box(boxed) }
800 /// Gets the underlying byte representation.
802 /// Note: it is *crucial* that this API is not externally public, to avoid
803 /// revealing the internal, platform-specific encodings.
805 pub(crate) fn bytes(&self) -> &[u8] {
806 unsafe { &*(&self.inner as *const _ as *const [u8]) }
809 /// Converts this string to its ASCII lower case equivalent in-place.
811 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
812 /// but non-ASCII letters are unchanged.
814 /// To return a new lowercased value without modifying the existing one, use
815 /// [`OsStr::to_ascii_lowercase`].
820 /// use std::ffi::OsString;
822 /// let mut s = OsString::from("GRÜßE, JÜRGEN ❤");
824 /// s.make_ascii_lowercase();
826 /// assert_eq!("grÜße, jÜrgen ❤", s);
828 #[stable(feature = "osstring_ascii", since = "1.53.0")]
830 pub fn make_ascii_lowercase(&mut self) {
831 self.inner.make_ascii_lowercase()
834 /// Converts this string to its ASCII upper case equivalent in-place.
836 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
837 /// but non-ASCII letters are unchanged.
839 /// To return a new uppercased value without modifying the existing one, use
840 /// [`OsStr::to_ascii_uppercase`].
845 /// use std::ffi::OsString;
847 /// let mut s = OsString::from("Grüße, Jürgen ❤");
849 /// s.make_ascii_uppercase();
851 /// assert_eq!("GRüßE, JüRGEN ❤", s);
853 #[stable(feature = "osstring_ascii", since = "1.53.0")]
855 pub fn make_ascii_uppercase(&mut self) {
856 self.inner.make_ascii_uppercase()
859 /// Returns a copy of this string where each character is mapped to its
860 /// ASCII lower case equivalent.
862 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
863 /// but non-ASCII letters are unchanged.
865 /// To lowercase the value in-place, use [`OsStr::make_ascii_lowercase`].
870 /// use std::ffi::OsString;
871 /// let s = OsString::from("Grüße, Jürgen ❤");
873 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
875 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase`"]
876 #[stable(feature = "osstring_ascii", since = "1.53.0")]
877 pub fn to_ascii_lowercase(&self) -> OsString {
878 OsString::from_inner(self.inner.to_ascii_lowercase())
881 /// Returns a copy of this string where each character is mapped to its
882 /// ASCII upper case equivalent.
884 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
885 /// but non-ASCII letters are unchanged.
887 /// To uppercase the value in-place, use [`OsStr::make_ascii_uppercase`].
892 /// use std::ffi::OsString;
893 /// let s = OsString::from("Grüße, Jürgen ❤");
895 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
897 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase`"]
898 #[stable(feature = "osstring_ascii", since = "1.53.0")]
899 pub fn to_ascii_uppercase(&self) -> OsString {
900 OsString::from_inner(self.inner.to_ascii_uppercase())
903 /// Checks if all characters in this string are within the ASCII range.
908 /// use std::ffi::OsString;
910 /// let ascii = OsString::from("hello!\n");
911 /// let non_ascii = OsString::from("Grüße, Jürgen ❤");
913 /// assert!(ascii.is_ascii());
914 /// assert!(!non_ascii.is_ascii());
916 #[stable(feature = "osstring_ascii", since = "1.53.0")]
919 pub fn is_ascii(&self) -> bool {
920 self.inner.is_ascii()
923 /// Checks that two strings are an ASCII case-insensitive match.
925 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
926 /// but without allocating and copying temporaries.
931 /// use std::ffi::OsString;
933 /// assert!(OsString::from("Ferris").eq_ignore_ascii_case("FERRIS"));
934 /// assert!(OsString::from("Ferrös").eq_ignore_ascii_case("FERRöS"));
935 /// assert!(!OsString::from("Ferrös").eq_ignore_ascii_case("FERRÖS"));
937 #[stable(feature = "osstring_ascii", since = "1.53.0")]
938 pub fn eq_ignore_ascii_case<S: AsRef<OsStr>>(&self, other: S) -> bool {
939 self.inner.eq_ignore_ascii_case(&other.as_ref().inner)
943 #[stable(feature = "box_from_os_str", since = "1.17.0")]
944 impl From<&OsStr> for Box<OsStr> {
946 fn from(s: &OsStr) -> Box<OsStr> {
947 let rw = Box::into_raw(s.inner.into_box()) as *mut OsStr;
948 unsafe { Box::from_raw(rw) }
952 #[stable(feature = "box_from_cow", since = "1.45.0")]
953 impl From<Cow<'_, OsStr>> for Box<OsStr> {
955 fn from(cow: Cow<'_, OsStr>) -> Box<OsStr> {
957 Cow::Borrowed(s) => Box::from(s),
958 Cow::Owned(s) => Box::from(s),
963 #[stable(feature = "os_string_from_box", since = "1.18.0")]
964 impl From<Box<OsStr>> for OsString {
965 /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or
968 fn from(boxed: Box<OsStr>) -> OsString {
969 boxed.into_os_string()
973 #[stable(feature = "box_from_os_string", since = "1.20.0")]
974 impl From<OsString> for Box<OsStr> {
975 /// Converts an [`OsString`] into a <code>[Box]<[OsStr]></code> without copying or allocating.
977 fn from(s: OsString) -> Box<OsStr> {
978 s.into_boxed_os_str()
982 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
983 impl Clone for Box<OsStr> {
985 fn clone(&self) -> Self {
986 self.to_os_string().into_boxed_os_str()
990 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
991 impl From<OsString> for Arc<OsStr> {
992 /// Converts an [`OsString`] into an <code>[Arc]<[OsStr]></code> by moving the [`OsString`]
993 /// data into a new [`Arc`] buffer.
995 fn from(s: OsString) -> Arc<OsStr> {
996 let arc = s.inner.into_arc();
997 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1001 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1002 impl From<&OsStr> for Arc<OsStr> {
1004 fn from(s: &OsStr) -> Arc<OsStr> {
1005 let arc = s.inner.into_arc();
1006 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1010 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1011 impl From<OsString> for Rc<OsStr> {
1012 /// Converts an [`OsString`] into an <code>[Rc]<[OsStr]></code> by moving the [`OsString`]
1013 /// data into a new [`Rc`] buffer.
1015 fn from(s: OsString) -> Rc<OsStr> {
1016 let rc = s.inner.into_rc();
1017 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1021 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1022 impl From<&OsStr> for Rc<OsStr> {
1024 fn from(s: &OsStr) -> Rc<OsStr> {
1025 let rc = s.inner.into_rc();
1026 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1030 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1031 impl<'a> From<OsString> for Cow<'a, OsStr> {
1033 fn from(s: OsString) -> Cow<'a, OsStr> {
1038 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1039 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
1041 fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
1046 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1047 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
1049 fn from(s: &'a OsString) -> Cow<'a, OsStr> {
1050 Cow::Borrowed(s.as_os_str())
1054 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
1055 impl<'a> From<Cow<'a, OsStr>> for OsString {
1057 fn from(s: Cow<'a, OsStr>) -> Self {
1062 #[stable(feature = "box_default_extra", since = "1.17.0")]
1063 impl Default for Box<OsStr> {
1065 fn default() -> Box<OsStr> {
1066 let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
1067 unsafe { Box::from_raw(rw) }
1071 #[stable(feature = "osstring_default", since = "1.9.0")]
1072 impl Default for &OsStr {
1073 /// Creates an empty `OsStr`.
1075 fn default() -> Self {
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl PartialEq for OsStr {
1083 fn eq(&self, other: &OsStr) -> bool {
1084 self.bytes().eq(other.bytes())
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 impl PartialEq<str> for OsStr {
1091 fn eq(&self, other: &str) -> bool {
1092 *self == *OsStr::new(other)
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl PartialEq<OsStr> for str {
1099 fn eq(&self, other: &OsStr) -> bool {
1100 *other == *OsStr::new(self)
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl Eq for OsStr {}
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 impl PartialOrd for OsStr {
1110 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1111 self.bytes().partial_cmp(other.bytes())
1114 fn lt(&self, other: &OsStr) -> bool {
1115 self.bytes().lt(other.bytes())
1118 fn le(&self, other: &OsStr) -> bool {
1119 self.bytes().le(other.bytes())
1122 fn gt(&self, other: &OsStr) -> bool {
1123 self.bytes().gt(other.bytes())
1126 fn ge(&self, other: &OsStr) -> bool {
1127 self.bytes().ge(other.bytes())
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl PartialOrd<str> for OsStr {
1134 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1135 self.partial_cmp(OsStr::new(other))
1139 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1140 // have more flexible coherence rules.
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 impl Ord for OsStr {
1145 fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1146 self.bytes().cmp(other.bytes())
1150 macro_rules! impl_cmp {
1151 ($lhs:ty, $rhs: ty) => {
1152 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1153 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1155 fn eq(&self, other: &$rhs) -> bool {
1156 <OsStr as PartialEq>::eq(self, other)
1160 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1161 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1163 fn eq(&self, other: &$lhs) -> bool {
1164 <OsStr as PartialEq>::eq(self, other)
1168 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1169 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
1171 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1172 <OsStr as PartialOrd>::partial_cmp(self, other)
1176 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1177 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
1179 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1180 <OsStr as PartialOrd>::partial_cmp(self, other)
1186 impl_cmp!(OsString, OsStr);
1187 impl_cmp!(OsString, &'a OsStr);
1188 impl_cmp!(Cow<'a, OsStr>, OsStr);
1189 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
1190 impl_cmp!(Cow<'a, OsStr>, OsString);
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl Hash for OsStr {
1195 fn hash<H: Hasher>(&self, state: &mut H) {
1196 self.bytes().hash(state)
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 impl fmt::Debug for OsStr {
1202 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1203 fmt::Debug::fmt(&self.inner, formatter)
1208 pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1209 fmt::Display::fmt(&self.inner, formatter)
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl Borrow<OsStr> for OsString {
1216 fn borrow(&self) -> &OsStr {
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl ToOwned for OsStr {
1223 type Owned = OsString;
1225 fn to_owned(&self) -> OsString {
1229 fn clone_into(&self, target: &mut OsString) {
1230 self.inner.clone_into(&mut target.inner)
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 impl AsRef<OsStr> for OsStr {
1237 fn as_ref(&self) -> &OsStr {
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl AsRef<OsStr> for OsString {
1245 fn as_ref(&self) -> &OsStr {
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl AsRef<OsStr> for str {
1253 fn as_ref(&self) -> &OsStr {
1254 OsStr::from_inner(Slice::from_str(self))
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl AsRef<OsStr> for String {
1261 fn as_ref(&self) -> &OsStr {
1266 impl FromInner<Buf> for OsString {
1268 fn from_inner(buf: Buf) -> OsString {
1269 OsString { inner: buf }
1273 impl IntoInner<Buf> for OsString {
1275 fn into_inner(self) -> Buf {
1280 impl AsInner<Slice> for OsStr {
1282 fn as_inner(&self) -> &Slice {
1287 #[stable(feature = "osstring_from_str", since = "1.45.0")]
1288 impl FromStr for OsString {
1289 type Err = core::convert::Infallible;
1292 fn from_str(s: &str) -> Result<Self, Self::Err> {
1293 Ok(OsString::from(s))
1297 #[stable(feature = "osstring_extend", since = "1.52.0")]
1298 impl Extend<OsString> for OsString {
1300 fn extend<T: IntoIterator<Item = OsString>>(&mut self, iter: T) {
1307 #[stable(feature = "osstring_extend", since = "1.52.0")]
1308 impl<'a> Extend<&'a OsStr> for OsString {
1310 fn extend<T: IntoIterator<Item = &'a OsStr>>(&mut self, iter: T) {
1317 #[stable(feature = "osstring_extend", since = "1.52.0")]
1318 impl<'a> Extend<Cow<'a, OsStr>> for OsString {
1320 fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: T) {
1327 #[stable(feature = "osstring_extend", since = "1.52.0")]
1328 impl FromIterator<OsString> for OsString {
1330 fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1331 let mut iterator = iter.into_iter();
1333 // Because we're iterating over `OsString`s, we can avoid at least
1334 // one allocation by getting the first string from the iterator
1335 // and appending to it all the subsequent strings.
1336 match iterator.next() {
1337 None => OsString::new(),
1339 buf.extend(iterator);
1346 #[stable(feature = "osstring_extend", since = "1.52.0")]
1347 impl<'a> FromIterator<&'a OsStr> for OsString {
1349 fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self {
1350 let mut buf = Self::new();
1358 #[stable(feature = "osstring_extend", since = "1.52.0")]
1359 impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
1361 fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
1362 let mut iterator = iter.into_iter();
1364 // Because we're iterating over `OsString`s, we can avoid at least
1365 // one allocation by getting the first owned string from the iterator
1366 // and appending to it all the subsequent strings.
1367 match iterator.next() {
1368 None => OsString::new(),
1369 Some(Cow::Owned(mut buf)) => {
1370 buf.extend(iterator);
1373 Some(Cow::Borrowed(buf)) => {
1374 let mut buf = OsString::from(buf);
1375 buf.extend(iterator);