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 /// # Capacity of `OsString`
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:
54 /// use std::ffi::{OsStr, OsString};
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
64 /// # Creating an `OsString`
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.
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.
76 /// # Extracting a borrowed reference to the whole OS string
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
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.
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")]
96 /// Allows extension traits within `std`.
97 #[unstable(feature = "sealed", issue = "none")]
98 impl crate::sealed::Sealed for OsString {}
100 /// Borrowed reference to an OS string (see [`OsString`]).
102 /// This type represents a borrowed reference to a string in the operating system's preferred
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.
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.
111 /// [conversions]: super#conversions
112 #[cfg_attr(not(test), rustc_diagnostic_item = "OsStr")]
113 #[stable(feature = "rust1", since = "1.0.0")]
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.
124 /// Allows extension traits within `std`.
125 #[unstable(feature = "sealed", issue = "none")]
126 impl crate::sealed::Sealed for OsStr {}
129 /// Constructs a new empty `OsString`.
134 /// use std::ffi::OsString;
136 /// let os_string = OsString::new();
138 #[stable(feature = "rust1", since = "1.0.0")]
141 pub fn new() -> OsString {
142 OsString { inner: Buf::from_string(String::new()) }
145 /// Converts to an [`OsStr`] slice.
150 /// use std::ffi::{OsString, OsStr};
152 /// let os_string = OsString::from("foo");
153 /// let os_str = OsStr::new("foo");
154 /// assert_eq!(os_string.as_os_str(), os_str);
156 #[stable(feature = "rust1", since = "1.0.0")]
159 pub fn as_os_str(&self) -> &OsStr {
163 /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
165 /// On failure, ownership of the original `OsString` is returned.
170 /// use std::ffi::OsString;
172 /// let os_string = OsString::from("foo");
173 /// let string = os_string.into_string();
174 /// assert_eq!(string, Ok(String::from("foo")));
176 #[stable(feature = "rust1", since = "1.0.0")]
178 pub fn into_string(self) -> Result<String, OsString> {
179 self.inner.into_string().map_err(|buf| OsString { inner: buf })
182 /// Extends the string with the given <code>&[OsStr]</code> slice.
187 /// use std::ffi::OsString;
189 /// let mut os_string = OsString::from("foo");
190 /// os_string.push("bar");
191 /// assert_eq!(&os_string, "foobar");
193 #[stable(feature = "rust1", since = "1.0.0")]
195 pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
196 self.inner.push_slice(&s.as_ref().inner)
199 /// Creates a new `OsString` with at least the given capacity.
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
206 /// See the main `OsString` documentation information about encoding and capacity units.
211 /// use std::ffi::OsString;
213 /// let mut os_string = OsString::with_capacity(10);
214 /// let capacity = os_string.capacity();
216 /// // This push is done without reallocating
217 /// os_string.push("foo");
219 /// assert_eq!(capacity, os_string.capacity());
221 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
224 pub fn with_capacity(capacity: usize) -> OsString {
225 OsString { inner: Buf::with_capacity(capacity) }
228 /// Truncates the `OsString` to zero length.
233 /// use std::ffi::OsString;
235 /// let mut os_string = OsString::from("foo");
236 /// assert_eq!(&os_string, "foo");
238 /// os_string.clear();
239 /// assert_eq!(&os_string, "");
241 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
243 pub fn clear(&mut self) {
247 /// Returns the capacity this `OsString` can hold without reallocating.
249 /// See the main `OsString` documentation information about encoding and capacity units.
254 /// use std::ffi::OsString;
256 /// let os_string = OsString::with_capacity(10);
257 /// assert!(os_string.capacity() >= 10);
259 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
262 pub fn capacity(&self) -> usize {
263 self.inner.capacity()
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.
270 /// The collection may reserve more space to speculatively avoid frequent reallocations.
272 /// See the main `OsString` documentation information about encoding and capacity units.
277 /// use std::ffi::OsString;
279 /// let mut s = OsString::new();
281 /// assert!(s.capacity() >= 10);
283 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
285 pub fn reserve(&mut self, additional: usize) {
286 self.inner.reserve(additional)
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.
296 /// See the main `OsString` documentation information about encoding and capacity units.
300 /// If the capacity overflows, or the allocator reports a failure, then an error
306 /// use std::ffi::{OsStr, OsString};
307 /// use std::collections::TryReserveError;
309 /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
310 /// let mut s = OsString::new();
312 /// // Pre-reserve the memory, exiting if we can't
313 /// s.try_reserve(OsStr::new(data).len())?;
315 /// // Now we know this can't OOM in the middle of our complex work
320 /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
322 #[stable(feature = "try_reserve_2", since = "1.63.0")]
324 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
325 self.inner.try_reserve(additional)
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.
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.
336 /// [`reserve`]: OsString::reserve
338 /// See the main `OsString` documentation information about encoding and capacity units.
343 /// use std::ffi::OsString;
345 /// let mut s = OsString::new();
346 /// s.reserve_exact(10);
347 /// assert!(s.capacity() >= 10);
349 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
351 pub fn reserve_exact(&mut self, additional: usize) {
352 self.inner.reserve_exact(additional)
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.
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.
365 /// [`try_reserve`]: OsString::try_reserve
367 /// See the main `OsString` documentation information about encoding and capacity units.
371 /// If the capacity overflows, or the allocator reports a failure, then an error
377 /// use std::ffi::{OsStr, OsString};
378 /// use std::collections::TryReserveError;
380 /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
381 /// let mut s = OsString::new();
383 /// // Pre-reserve the memory, exiting if we can't
384 /// s.try_reserve_exact(OsStr::new(data).len())?;
386 /// // Now we know this can't OOM in the middle of our complex work
391 /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
393 #[stable(feature = "try_reserve_2", since = "1.63.0")]
395 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
396 self.inner.try_reserve_exact(additional)
399 /// Shrinks the capacity of the `OsString` to match its length.
401 /// See the main `OsString` documentation information about encoding and capacity units.
406 /// use std::ffi::OsString;
408 /// let mut s = OsString::from("foo");
411 /// assert!(s.capacity() >= 100);
413 /// s.shrink_to_fit();
414 /// assert_eq!(3, s.capacity());
416 #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
418 pub fn shrink_to_fit(&mut self) {
419 self.inner.shrink_to_fit()
422 /// Shrinks the capacity of the `OsString` with a lower bound.
424 /// The capacity will remain at least as large as both the length
425 /// and the supplied value.
427 /// If the current capacity is less than the lower limit, this is a no-op.
429 /// See the main `OsString` documentation information about encoding and capacity units.
434 /// use std::ffi::OsString;
436 /// let mut s = OsString::from("foo");
439 /// assert!(s.capacity() >= 100);
442 /// assert!(s.capacity() >= 10);
444 /// assert!(s.capacity() >= 3);
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)
452 /// Converts this `OsString` into a boxed [`OsStr`].
457 /// use std::ffi::{OsString, OsStr};
459 /// let s = OsString::from("hello");
461 /// let b: Box<OsStr> = s.into_boxed_os_str();
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) }
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl From<String> for OsString {
473 /// Converts a [`String`] into an [`OsString`].
475 /// This conversion does not allocate or copy memory.
477 fn from(s: String) -> OsString {
478 OsString { inner: Buf::from_string(s) }
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]<[OsStr]></code>
485 /// into a newly allocated [`OsString`].
486 fn from(s: &T) -> OsString {
487 s.as_ref().to_os_string()
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl ops::Index<ops::RangeFull> for OsString {
496 fn index(&self, _index: ops::RangeFull) -> &OsStr {
497 OsStr::from_inner(self.inner.as_slice())
501 #[stable(feature = "mut_osstr", since = "1.44.0")]
502 impl ops::IndexMut<ops::RangeFull> for OsString {
504 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut OsStr {
505 OsStr::from_inner_mut(self.inner.as_mut_slice())
509 #[stable(feature = "rust1", since = "1.0.0")]
510 impl ops::Deref for OsString {
514 fn deref(&self) -> &OsStr {
519 #[stable(feature = "mut_osstr", since = "1.44.0")]
520 impl ops::DerefMut for OsString {
522 fn deref_mut(&mut self) -> &mut OsStr {
527 #[stable(feature = "osstring_default", since = "1.9.0")]
528 impl Default for OsString {
529 /// Constructs an empty `OsString`.
531 fn default() -> OsString {
536 #[stable(feature = "rust1", since = "1.0.0")]
537 impl Clone for OsString {
539 fn clone(&self) -> Self {
540 OsString { inner: self.inner.clone() }
544 fn clone_from(&mut self, source: &Self) {
545 self.inner.clone_from(&source.inner)
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)
556 #[stable(feature = "rust1", since = "1.0.0")]
557 impl PartialEq for OsString {
559 fn eq(&self, other: &OsString) -> bool {
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl PartialEq<str> for OsString {
567 fn eq(&self, other: &str) -> bool {
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl PartialEq<OsString> for str {
575 fn eq(&self, other: &OsString) -> bool {
580 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
581 impl PartialEq<&str> for OsString {
583 fn eq(&self, other: &&str) -> bool {
588 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
589 impl<'a> PartialEq<OsString> for &'a str {
591 fn eq(&self, other: &OsString) -> bool {
596 #[stable(feature = "rust1", since = "1.0.0")]
597 impl Eq for OsString {}
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl PartialOrd for OsString {
602 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
603 (&**self).partial_cmp(&**other)
606 fn lt(&self, other: &OsString) -> bool {
610 fn le(&self, other: &OsString) -> bool {
614 fn gt(&self, other: &OsString) -> bool {
618 fn ge(&self, other: &OsString) -> bool {
623 #[stable(feature = "rust1", since = "1.0.0")]
624 impl PartialOrd<str> for OsString {
626 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
627 (&**self).partial_cmp(other)
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl Ord for OsString {
634 fn cmp(&self, other: &OsString) -> cmp::Ordering {
635 (&**self).cmp(&**other)
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl Hash for OsString {
642 fn hash<H: Hasher>(&self, state: &mut H) {
643 (&**self).hash(state)
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 {
656 /// Coerces into an `OsStr` slice.
661 /// use std::ffi::OsStr;
663 /// let os_str = OsStr::new("foo");
666 #[stable(feature = "rust1", since = "1.0.0")]
667 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
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) }
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) }
687 /// Yields a <code>&[str]</code> slice if the `OsStr` is valid Unicode.
689 /// This conversion may entail doing a check for UTF-8 validity.
694 /// use std::ffi::OsStr;
696 /// let os_str = OsStr::new("foo");
697 /// assert_eq!(os_str.to_str(), Some("foo"));
699 #[stable(feature = "rust1", since = "1.0.0")]
700 #[must_use = "this returns the result of the operation, \
701 without modifying the original"]
703 pub fn to_str(&self) -> Option<&str> {
707 /// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
709 /// Any non-Unicode sequences are replaced with
710 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
712 /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
716 /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
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
727 /// use std::ffi::OsStr;
728 /// use std::os::unix::ffi::OsStrExt;
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[..]);
736 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
738 /// #[cfg(windows)] {
739 /// use std::ffi::OsString;
740 /// use std::os::windows::prelude::*;
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();
749 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
752 #[stable(feature = "rust1", since = "1.0.0")]
753 #[must_use = "this returns the result of the operation, \
754 without modifying the original"]
756 pub fn to_string_lossy(&self) -> Cow<'_, str> {
757 self.inner.to_string_lossy()
760 /// Copies the slice into an owned [`OsString`].
765 /// use std::ffi::{OsStr, OsString};
767 /// let os_str = OsStr::new("foo");
768 /// let os_string = os_str.to_os_string();
769 /// assert_eq!(os_string, OsString::from("foo"));
771 #[stable(feature = "rust1", since = "1.0.0")]
772 #[must_use = "this returns the result of the operation, \
773 without modifying the original"]
775 pub fn to_os_string(&self) -> OsString {
776 OsString { inner: self.inner.to_owned() }
779 /// Checks whether the `OsStr` is empty.
784 /// use std::ffi::OsStr;
786 /// let os_str = OsStr::new("");
787 /// assert!(os_str.is_empty());
789 /// let os_str = OsStr::new("foo");
790 /// assert!(!os_str.is_empty());
792 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
795 pub fn is_empty(&self) -> bool {
796 self.inner.inner.is_empty()
799 /// Returns the length of this `OsStr`.
801 /// Note that this does **not** return the number of bytes in the string in
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.
810 /// This number is simply useful for passing to other methods, like
811 /// [`OsString::with_capacity`] to avoid reallocations.
813 /// See the main `OsString` documentation information about encoding and capacity units.
818 /// use std::ffi::OsStr;
820 /// let os_str = OsStr::new("");
821 /// assert_eq!(os_str.len(), 0);
823 /// let os_str = OsStr::new("foo");
824 /// assert_eq!(os_str.len(), 3);
826 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
829 pub fn len(&self) -> usize {
830 self.inner.inner.len()
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) }
841 /// Gets the underlying byte representation.
843 /// Note: it is *crucial* that this API is not externally public, to avoid
844 /// revealing the internal, platform-specific encodings.
846 pub(crate) fn bytes(&self) -> &[u8] {
847 unsafe { &*(&self.inner as *const _ as *const [u8]) }
850 /// Converts this string to its ASCII lower case equivalent in-place.
852 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
853 /// but non-ASCII letters are unchanged.
855 /// To return a new lowercased value without modifying the existing one, use
856 /// [`OsStr::to_ascii_lowercase`].
861 /// use std::ffi::OsString;
863 /// let mut s = OsString::from("GRÜßE, JÜRGEN ❤");
865 /// s.make_ascii_lowercase();
867 /// assert_eq!("grÜße, jÜrgen ❤", s);
869 #[stable(feature = "osstring_ascii", since = "1.53.0")]
871 pub fn make_ascii_lowercase(&mut self) {
872 self.inner.make_ascii_lowercase()
875 /// Converts this string to its ASCII upper case equivalent in-place.
877 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
878 /// but non-ASCII letters are unchanged.
880 /// To return a new uppercased value without modifying the existing one, use
881 /// [`OsStr::to_ascii_uppercase`].
886 /// use std::ffi::OsString;
888 /// let mut s = OsString::from("Grüße, Jürgen ❤");
890 /// s.make_ascii_uppercase();
892 /// assert_eq!("GRüßE, JüRGEN ❤", s);
894 #[stable(feature = "osstring_ascii", since = "1.53.0")]
896 pub fn make_ascii_uppercase(&mut self) {
897 self.inner.make_ascii_uppercase()
900 /// Returns a copy of this string where each character is mapped to its
901 /// ASCII lower case equivalent.
903 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
904 /// but non-ASCII letters are unchanged.
906 /// To lowercase the value in-place, use [`OsStr::make_ascii_lowercase`].
911 /// use std::ffi::OsString;
912 /// let s = OsString::from("Grüße, Jürgen ❤");
914 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
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())
922 /// Returns a copy of this string where each character is mapped to its
923 /// ASCII upper case equivalent.
925 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
926 /// but non-ASCII letters are unchanged.
928 /// To uppercase the value in-place, use [`OsStr::make_ascii_uppercase`].
933 /// use std::ffi::OsString;
934 /// let s = OsString::from("Grüße, Jürgen ❤");
936 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
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())
944 /// Checks if all characters in this string are within the ASCII range.
949 /// use std::ffi::OsString;
951 /// let ascii = OsString::from("hello!\n");
952 /// let non_ascii = OsString::from("Grüße, Jürgen ❤");
954 /// assert!(ascii.is_ascii());
955 /// assert!(!non_ascii.is_ascii());
957 #[stable(feature = "osstring_ascii", since = "1.53.0")]
960 pub fn is_ascii(&self) -> bool {
961 self.inner.is_ascii()
964 /// Checks that two strings are an ASCII case-insensitive match.
966 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
967 /// but without allocating and copying temporaries.
972 /// use std::ffi::OsString;
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"));
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)
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]<[OsStr]></code>.
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) }
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]<[OsStr]></code>,
997 /// by copying the contents if they are borrowed.
999 fn from(cow: Cow<'_, OsStr>) -> Box<OsStr> {
1001 Cow::Borrowed(s) => Box::from(s),
1002 Cow::Owned(s) => Box::from(s),
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
1012 fn from(boxed: Box<OsStr>) -> OsString {
1013 boxed.into_os_string()
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.
1021 fn from(s: OsString) -> Box<OsStr> {
1022 s.into_boxed_os_str()
1026 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1027 impl Clone for Box<OsStr> {
1029 fn clone(&self) -> Self {
1030 self.to_os_string().into_boxed_os_str()
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.
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) }
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]<[OsStr]></code>.
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) }
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.
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) }
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]<[OsStr]></code>.
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) }
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`].
1080 fn from(s: OsString) -> Cow<'a, OsStr> {
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`].
1089 fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
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`].
1098 fn from(s: &'a OsString) -> Cow<'a, OsStr> {
1099 Cow::Borrowed(s.as_os_str())
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.
1108 fn from(s: Cow<'a, OsStr>) -> Self {
1113 #[stable(feature = "box_default_extra", since = "1.17.0")]
1114 impl Default for Box<OsStr> {
1116 fn default() -> Box<OsStr> {
1117 let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
1118 unsafe { Box::from_raw(rw) }
1122 #[stable(feature = "osstring_default", since = "1.9.0")]
1123 impl Default for &OsStr {
1124 /// Creates an empty `OsStr`.
1126 fn default() -> Self {
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl PartialEq for OsStr {
1134 fn eq(&self, other: &OsStr) -> bool {
1135 self.bytes().eq(other.bytes())
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl PartialEq<str> for OsStr {
1142 fn eq(&self, other: &str) -> bool {
1143 *self == *OsStr::new(other)
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl PartialEq<OsStr> for str {
1150 fn eq(&self, other: &OsStr) -> bool {
1151 *other == *OsStr::new(self)
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 impl Eq for OsStr {}
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl PartialOrd for OsStr {
1161 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1162 self.bytes().partial_cmp(other.bytes())
1165 fn lt(&self, other: &OsStr) -> bool {
1166 self.bytes().lt(other.bytes())
1169 fn le(&self, other: &OsStr) -> bool {
1170 self.bytes().le(other.bytes())
1173 fn gt(&self, other: &OsStr) -> bool {
1174 self.bytes().gt(other.bytes())
1177 fn ge(&self, other: &OsStr) -> bool {
1178 self.bytes().ge(other.bytes())
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 impl PartialOrd<str> for OsStr {
1185 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1186 self.partial_cmp(OsStr::new(other))
1190 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1191 // have more flexible coherence rules.
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl Ord for OsStr {
1196 fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1197 self.bytes().cmp(other.bytes())
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 {
1206 fn eq(&self, other: &$rhs) -> bool {
1207 <OsStr as PartialEq>::eq(self, other)
1211 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1212 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1214 fn eq(&self, other: &$lhs) -> bool {
1215 <OsStr as PartialEq>::eq(self, other)
1219 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1220 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
1222 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1223 <OsStr as PartialOrd>::partial_cmp(self, other)
1227 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1228 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
1230 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1231 <OsStr as PartialOrd>::partial_cmp(self, other)
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);
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl Hash for OsStr {
1246 fn hash<H: Hasher>(&self, state: &mut H) {
1247 self.bytes().hash(state)
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)
1259 pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1260 fmt::Display::fmt(&self.inner, formatter)
1264 #[unstable(feature = "slice_concat_ext", issue = "27747")]
1265 impl<S: Borrow<OsStr>> alloc::slice::Join<&OsStr> for [S] {
1266 type Output = OsString;
1268 fn join(slice: &Self, sep: &OsStr) -> OsString {
1269 let Some((first, suffix)) = slice.split_first() else {
1270 return OsString::new();
1272 let first_owned = first.borrow().to_owned();
1273 suffix.iter().fold(first_owned, |mut a, b| {
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl Borrow<OsStr> for OsString {
1284 fn borrow(&self) -> &OsStr {
1289 #[stable(feature = "rust1", since = "1.0.0")]
1290 impl ToOwned for OsStr {
1291 type Owned = OsString;
1293 fn to_owned(&self) -> OsString {
1297 fn clone_into(&self, target: &mut OsString) {
1298 self.inner.clone_into(&mut target.inner)
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 impl AsRef<OsStr> for OsStr {
1305 fn as_ref(&self) -> &OsStr {
1310 #[stable(feature = "rust1", since = "1.0.0")]
1311 impl AsRef<OsStr> for OsString {
1313 fn as_ref(&self) -> &OsStr {
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl AsRef<OsStr> for str {
1321 fn as_ref(&self) -> &OsStr {
1322 OsStr::from_inner(Slice::from_str(self))
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl AsRef<OsStr> for String {
1329 fn as_ref(&self) -> &OsStr {
1334 impl FromInner<Buf> for OsString {
1336 fn from_inner(buf: Buf) -> OsString {
1337 OsString { inner: buf }
1341 impl IntoInner<Buf> for OsString {
1343 fn into_inner(self) -> Buf {
1348 impl AsInner<Slice> for OsStr {
1350 fn as_inner(&self) -> &Slice {
1355 #[stable(feature = "osstring_from_str", since = "1.45.0")]
1356 impl FromStr for OsString {
1357 type Err = core::convert::Infallible;
1360 fn from_str(s: &str) -> Result<Self, Self::Err> {
1361 Ok(OsString::from(s))
1365 #[stable(feature = "osstring_extend", since = "1.52.0")]
1366 impl Extend<OsString> for OsString {
1368 fn extend<T: IntoIterator<Item = OsString>>(&mut self, iter: T) {
1375 #[stable(feature = "osstring_extend", since = "1.52.0")]
1376 impl<'a> Extend<&'a OsStr> for OsString {
1378 fn extend<T: IntoIterator<Item = &'a OsStr>>(&mut self, iter: T) {
1385 #[stable(feature = "osstring_extend", since = "1.52.0")]
1386 impl<'a> Extend<Cow<'a, OsStr>> for OsString {
1388 fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: T) {
1395 #[stable(feature = "osstring_extend", since = "1.52.0")]
1396 impl FromIterator<OsString> for OsString {
1398 fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1399 let mut iterator = iter.into_iter();
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(),
1407 buf.extend(iterator);
1414 #[stable(feature = "osstring_extend", since = "1.52.0")]
1415 impl<'a> FromIterator<&'a OsStr> for OsString {
1417 fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self {
1418 let mut buf = Self::new();
1426 #[stable(feature = "osstring_extend", since = "1.52.0")]
1427 impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
1429 fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
1430 let mut iterator = iter.into_iter();
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);
1441 Some(Cow::Borrowed(buf)) => {
1442 let mut buf = OsString::from(buf);
1443 buf.extend(iterator);