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.
295 /// See the main `OsString` documentation information about encoding and capacity units.
299 /// If the capacity overflows, or the allocator reports a failure, then an error
305 /// use std::ffi::{OsStr, OsString};
306 /// use std::collections::TryReserveError;
308 /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
309 /// let mut s = OsString::new();
311 /// // Pre-reserve the memory, exiting if we can't
312 /// s.try_reserve(OsStr::new(data).len())?;
314 /// // Now we know this can't OOM in the middle of our complex work
319 /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
321 #[stable(feature = "try_reserve_2", since = "1.63.0")]
323 pub fn try_reserve(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
324 self.inner
.try_reserve(additional
)
327 /// Reserves the minimum capacity for at least `additional` more capacity to
328 /// be inserted in the given `OsString`. Does nothing if the capacity is
329 /// already sufficient.
331 /// Note that the allocator may give the collection more space than it
332 /// requests. Therefore, capacity can not be relied upon to be precisely
333 /// minimal. Prefer [`reserve`] if future insertions are expected.
335 /// [`reserve`]: OsString::reserve
337 /// See the main `OsString` documentation information about encoding and capacity units.
342 /// use std::ffi::OsString;
344 /// let mut s = OsString::new();
345 /// s.reserve_exact(10);
346 /// assert!(s.capacity() >= 10);
348 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
350 pub fn reserve_exact(&mut self, additional
: usize) {
351 self.inner
.reserve_exact(additional
)
354 /// Tries to reserve the minimum capacity for at least `additional`
355 /// more length units in the given `OsString`. After calling
356 /// `try_reserve_exact`, capacity will be greater than or equal to
357 /// `self.len() + additional` if it returns `Ok(())`.
358 /// Does nothing if the capacity is already sufficient.
360 /// Note that the allocator may give the `OsString` more space than it
361 /// requests. Therefore, capacity can not be relied upon to be precisely
362 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
364 /// [`try_reserve`]: OsString::try_reserve
366 /// See the main `OsString` documentation information about encoding and capacity units.
370 /// If the capacity overflows, or the allocator reports a failure, then an error
376 /// use std::ffi::{OsStr, OsString};
377 /// use std::collections::TryReserveError;
379 /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
380 /// let mut s = OsString::new();
382 /// // Pre-reserve the memory, exiting if we can't
383 /// s.try_reserve_exact(OsStr::new(data).len())?;
385 /// // Now we know this can't OOM in the middle of our complex work
390 /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
392 #[stable(feature = "try_reserve_2", since = "1.63.0")]
394 pub fn try_reserve_exact(&mut self, additional
: usize) -> Result
<(), TryReserveError
> {
395 self.inner
.try_reserve_exact(additional
)
398 /// Shrinks the capacity of the `OsString` to match its length.
400 /// See the main `OsString` documentation information about encoding and capacity units.
405 /// use std::ffi::OsString;
407 /// let mut s = OsString::from("foo");
410 /// assert!(s.capacity() >= 100);
412 /// s.shrink_to_fit();
413 /// assert_eq!(3, s.capacity());
415 #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
417 pub fn shrink_to_fit(&mut self) {
418 self.inner
.shrink_to_fit()
421 /// Shrinks the capacity of the `OsString` with a lower bound.
423 /// The capacity will remain at least as large as both the length
424 /// and the supplied value.
426 /// If the current capacity is less than the lower limit, this is a no-op.
428 /// See the main `OsString` documentation information about encoding and capacity units.
433 /// use std::ffi::OsString;
435 /// let mut s = OsString::from("foo");
438 /// assert!(s.capacity() >= 100);
441 /// assert!(s.capacity() >= 10);
443 /// assert!(s.capacity() >= 3);
446 #[stable(feature = "shrink_to", since = "1.56.0")]
447 pub fn shrink_to(&mut self, min_capacity
: usize) {
448 self.inner
.shrink_to(min_capacity
)
451 /// Converts this `OsString` into a boxed [`OsStr`].
456 /// use std::ffi::{OsString, OsStr};
458 /// let s = OsString::from("hello");
460 /// let b: Box<OsStr> = s.into_boxed_os_str();
462 #[must_use = "`self` will be dropped if the result is not used"]
463 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
464 pub fn into_boxed_os_str(self) -> Box
<OsStr
> {
465 let rw
= Box
::into_raw(self.inner
.into_box()) as *mut OsStr
;
466 unsafe { Box::from_raw(rw) }
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl From
<String
> for OsString
{
472 /// Converts a [`String`] into an [`OsString`].
474 /// This conversion does not allocate or copy memory.
476 fn from(s
: String
) -> OsString
{
477 OsString { inner: Buf::from_string(s) }
481 #[stable(feature = "rust1", since = "1.0.0")]
482 impl<T
: ?Sized
+ AsRef
<OsStr
>> From
<&T
> for OsString
{
483 /// Copies any value implementing <code>[AsRef]<[OsStr]></code>
484 /// into a newly allocated [`OsString`].
485 fn from(s
: &T
) -> OsString
{
486 s
.as_ref().to_os_string()
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl ops
::Index
<ops
::RangeFull
> for OsString
{
495 fn index(&self, _index
: ops
::RangeFull
) -> &OsStr
{
496 OsStr
::from_inner(self.inner
.as_slice())
500 #[stable(feature = "mut_osstr", since = "1.44.0")]
501 impl ops
::IndexMut
<ops
::RangeFull
> for OsString
{
503 fn index_mut(&mut self, _index
: ops
::RangeFull
) -> &mut OsStr
{
504 OsStr
::from_inner_mut(self.inner
.as_mut_slice())
508 #[stable(feature = "rust1", since = "1.0.0")]
509 impl ops
::Deref
for OsString
{
513 fn deref(&self) -> &OsStr
{
518 #[stable(feature = "mut_osstr", since = "1.44.0")]
519 impl ops
::DerefMut
for OsString
{
521 fn deref_mut(&mut self) -> &mut OsStr
{
526 #[stable(feature = "osstring_default", since = "1.9.0")]
527 impl Default
for OsString
{
528 /// Constructs an empty `OsString`.
530 fn default() -> OsString
{
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl Clone
for OsString
{
538 fn clone(&self) -> Self {
539 OsString { inner: self.inner.clone() }
543 fn clone_from(&mut self, source
: &Self) {
544 self.inner
.clone_from(&source
.inner
)
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl fmt
::Debug
for OsString
{
550 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
551 fmt
::Debug
::fmt(&**self, formatter
)
555 #[stable(feature = "rust1", since = "1.0.0")]
556 impl PartialEq
for OsString
{
558 fn eq(&self, other
: &OsString
) -> bool
{
563 #[stable(feature = "rust1", since = "1.0.0")]
564 impl PartialEq
<str> for OsString
{
566 fn eq(&self, other
: &str) -> bool
{
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl PartialEq
<OsString
> for str {
574 fn eq(&self, other
: &OsString
) -> bool
{
579 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
580 impl PartialEq
<&str> for OsString
{
582 fn eq(&self, other
: &&str) -> bool
{
587 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
588 impl<'a
> PartialEq
<OsString
> for &'a
str {
590 fn eq(&self, other
: &OsString
) -> bool
{
595 #[stable(feature = "rust1", since = "1.0.0")]
596 impl Eq
for OsString {}
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl PartialOrd
for OsString
{
601 fn partial_cmp(&self, other
: &OsString
) -> Option
<cmp
::Ordering
> {
602 (&**self).partial_cmp(&**other
)
605 fn lt(&self, other
: &OsString
) -> bool
{
609 fn le(&self, other
: &OsString
) -> bool
{
613 fn gt(&self, other
: &OsString
) -> bool
{
617 fn ge(&self, other
: &OsString
) -> bool
{
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl PartialOrd
<str> for OsString
{
625 fn partial_cmp(&self, other
: &str) -> Option
<cmp
::Ordering
> {
626 (&**self).partial_cmp(other
)
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl Ord
for OsString
{
633 fn cmp(&self, other
: &OsString
) -> cmp
::Ordering
{
634 (&**self).cmp(&**other
)
638 #[stable(feature = "rust1", since = "1.0.0")]
639 impl Hash
for OsString
{
641 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
642 (&**self).hash(state
)
647 /// Coerces into an `OsStr` slice.
652 /// use std::ffi::OsStr;
654 /// let os_str = OsStr::new("foo");
657 #[stable(feature = "rust1", since = "1.0.0")]
658 pub fn new
<S
: AsRef
<OsStr
> + ?Sized
>(s
: &S
) -> &OsStr
{
663 fn from_inner(inner
: &Slice
) -> &OsStr
{
664 // SAFETY: OsStr is just a wrapper of Slice,
665 // therefore converting &Slice to &OsStr is safe.
666 unsafe { &*(inner as *const Slice as *const OsStr) }
670 fn from_inner_mut(inner
: &mut Slice
) -> &mut OsStr
{
671 // SAFETY: OsStr is just a wrapper of Slice,
672 // therefore converting &mut Slice to &mut OsStr is safe.
673 // Any method that mutates OsStr must be careful not to
674 // break platform-specific encoding, in particular Wtf8 on Windows.
675 unsafe { &mut *(inner as *mut Slice as *mut OsStr) }
678 /// Yields a <code>&[str]</code> slice if the `OsStr` is valid Unicode.
680 /// This conversion may entail doing a check for UTF-8 validity.
685 /// use std::ffi::OsStr;
687 /// let os_str = OsStr::new("foo");
688 /// assert_eq!(os_str.to_str(), Some("foo"));
690 #[stable(feature = "rust1", since = "1.0.0")]
691 #[must_use = "this returns the result of the operation, \
692 without modifying the original"]
694 pub fn to_str(&self) -> Option
<&str> {
698 /// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
700 /// Any non-Unicode sequences are replaced with
701 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
703 /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
707 /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
710 /// // Note, due to differences in how Unix and Windows represent strings,
711 /// // we are forced to complicate this example, setting up example `OsStr`s
712 /// // with different source data and via different platform extensions.
713 /// // Understand that in reality you could end up with such example invalid
714 /// // sequences simply through collecting user command line arguments, for
718 /// use std::ffi::OsStr;
719 /// use std::os::unix::ffi::OsStrExt;
721 /// // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
722 /// // respectively. The value 0x80 is a lone continuation byte, invalid
723 /// // in a UTF-8 sequence.
724 /// let source = [0x66, 0x6f, 0x80, 0x6f];
725 /// let os_str = OsStr::from_bytes(&source[..]);
727 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
729 /// #[cfg(windows)] {
730 /// use std::ffi::OsString;
731 /// use std::os::windows::prelude::*;
733 /// // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
734 /// // respectively. The value 0xD800 is a lone surrogate half, invalid
735 /// // in a UTF-16 sequence.
736 /// let source = [0x0066, 0x006f, 0xD800, 0x006f];
737 /// let os_string = OsString::from_wide(&source[..]);
738 /// let os_str = os_string.as_os_str();
740 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
743 #[stable(feature = "rust1", since = "1.0.0")]
744 #[must_use = "this returns the result of the operation, \
745 without modifying the original"]
747 pub fn to_string_lossy(&self) -> Cow
<'_
, str> {
748 self.inner
.to_string_lossy()
751 /// Copies the slice into an owned [`OsString`].
756 /// use std::ffi::{OsStr, OsString};
758 /// let os_str = OsStr::new("foo");
759 /// let os_string = os_str.to_os_string();
760 /// assert_eq!(os_string, OsString::from("foo"));
762 #[stable(feature = "rust1", since = "1.0.0")]
763 #[must_use = "this returns the result of the operation, \
764 without modifying the original"]
766 pub fn to_os_string(&self) -> OsString
{
767 OsString { inner: self.inner.to_owned() }
770 /// Checks whether the `OsStr` is empty.
775 /// use std::ffi::OsStr;
777 /// let os_str = OsStr::new("");
778 /// assert!(os_str.is_empty());
780 /// let os_str = OsStr::new("foo");
781 /// assert!(!os_str.is_empty());
783 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
786 pub fn is_empty(&self) -> bool
{
787 self.inner
.inner
.is_empty()
790 /// Returns the length of this `OsStr`.
792 /// Note that this does **not** return the number of bytes in the string in
795 /// The length returned is that of the underlying storage used by `OsStr`.
796 /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
797 /// store strings in a form best suited for cheap inter-conversion between
798 /// native-platform and Rust string forms, which may differ significantly
799 /// from both of them, including in storage size and encoding.
801 /// This number is simply useful for passing to other methods, like
802 /// [`OsString::with_capacity`] to avoid reallocations.
804 /// See the main `OsString` documentation information about encoding and capacity units.
809 /// use std::ffi::OsStr;
811 /// let os_str = OsStr::new("");
812 /// assert_eq!(os_str.len(), 0);
814 /// let os_str = OsStr::new("foo");
815 /// assert_eq!(os_str.len(), 3);
817 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
820 pub fn len(&self) -> usize {
821 self.inner
.inner
.len()
824 /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or allocating.
825 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
826 #[must_use = "`self` will be dropped if the result is not used"]
827 pub fn into_os_string(self: Box
<OsStr
>) -> OsString
{
828 let boxed
= unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) }
;
829 OsString { inner: Buf::from_box(boxed) }
832 /// Gets the underlying byte representation.
834 /// Note: it is *crucial* that this API is not externally public, to avoid
835 /// revealing the internal, platform-specific encodings.
837 pub(crate) fn bytes(&self) -> &[u8] {
838 unsafe { &*(&self.inner as *const _ as *const [u8]) }
841 /// Converts this string to its ASCII lower case equivalent in-place.
843 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
844 /// but non-ASCII letters are unchanged.
846 /// To return a new lowercased value without modifying the existing one, use
847 /// [`OsStr::to_ascii_lowercase`].
852 /// use std::ffi::OsString;
854 /// let mut s = OsString::from("GRÜßE, JÜRGEN ❤");
856 /// s.make_ascii_lowercase();
858 /// assert_eq!("grÜße, jÜrgen ❤", s);
860 #[stable(feature = "osstring_ascii", since = "1.53.0")]
862 pub fn make_ascii_lowercase(&mut self) {
863 self.inner
.make_ascii_lowercase()
866 /// Converts this string to its ASCII upper case equivalent in-place.
868 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
869 /// but non-ASCII letters are unchanged.
871 /// To return a new uppercased value without modifying the existing one, use
872 /// [`OsStr::to_ascii_uppercase`].
877 /// use std::ffi::OsString;
879 /// let mut s = OsString::from("Grüße, Jürgen ❤");
881 /// s.make_ascii_uppercase();
883 /// assert_eq!("GRüßE, JüRGEN ❤", s);
885 #[stable(feature = "osstring_ascii", since = "1.53.0")]
887 pub fn make_ascii_uppercase(&mut self) {
888 self.inner
.make_ascii_uppercase()
891 /// Returns a copy of this string where each character is mapped to its
892 /// ASCII lower case equivalent.
894 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
895 /// but non-ASCII letters are unchanged.
897 /// To lowercase the value in-place, use [`OsStr::make_ascii_lowercase`].
902 /// use std::ffi::OsString;
903 /// let s = OsString::from("Grüße, Jürgen ❤");
905 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
907 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase`"]
908 #[stable(feature = "osstring_ascii", since = "1.53.0")]
909 pub fn to_ascii_lowercase(&self) -> OsString
{
910 OsString
::from_inner(self.inner
.to_ascii_lowercase())
913 /// Returns a copy of this string where each character is mapped to its
914 /// ASCII upper case equivalent.
916 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
917 /// but non-ASCII letters are unchanged.
919 /// To uppercase the value in-place, use [`OsStr::make_ascii_uppercase`].
924 /// use std::ffi::OsString;
925 /// let s = OsString::from("Grüße, Jürgen ❤");
927 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
929 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase`"]
930 #[stable(feature = "osstring_ascii", since = "1.53.0")]
931 pub fn to_ascii_uppercase(&self) -> OsString
{
932 OsString
::from_inner(self.inner
.to_ascii_uppercase())
935 /// Checks if all characters in this string are within the ASCII range.
940 /// use std::ffi::OsString;
942 /// let ascii = OsString::from("hello!\n");
943 /// let non_ascii = OsString::from("Grüße, Jürgen ❤");
945 /// assert!(ascii.is_ascii());
946 /// assert!(!non_ascii.is_ascii());
948 #[stable(feature = "osstring_ascii", since = "1.53.0")]
951 pub fn is_ascii(&self) -> bool
{
952 self.inner
.is_ascii()
955 /// Checks that two strings are an ASCII case-insensitive match.
957 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
958 /// but without allocating and copying temporaries.
963 /// use std::ffi::OsString;
965 /// assert!(OsString::from("Ferris").eq_ignore_ascii_case("FERRIS"));
966 /// assert!(OsString::from("Ferrös").eq_ignore_ascii_case("FERRöS"));
967 /// assert!(!OsString::from("Ferrös").eq_ignore_ascii_case("FERRÖS"));
969 #[stable(feature = "osstring_ascii", since = "1.53.0")]
970 pub fn eq_ignore_ascii_case
<S
: AsRef
<OsStr
>>(&self, other
: S
) -> bool
{
971 self.inner
.eq_ignore_ascii_case(&other
.as_ref().inner
)
975 #[stable(feature = "box_from_os_str", since = "1.17.0")]
976 impl From
<&OsStr
> for Box
<OsStr
> {
977 /// Copies the string into a newly allocated <code>[Box]<[OsStr]></code>.
979 fn from(s
: &OsStr
) -> Box
<OsStr
> {
980 let rw
= Box
::into_raw(s
.inner
.into_box()) as *mut OsStr
;
981 unsafe { Box::from_raw(rw) }
985 #[stable(feature = "box_from_cow", since = "1.45.0")]
986 impl From
<Cow
<'_
, OsStr
>> for Box
<OsStr
> {
987 /// Converts a `Cow<'a, OsStr>` into a <code>[Box]<[OsStr]></code>,
988 /// by copying the contents if they are borrowed.
990 fn from(cow
: Cow
<'_
, OsStr
>) -> Box
<OsStr
> {
992 Cow
::Borrowed(s
) => Box
::from(s
),
993 Cow
::Owned(s
) => Box
::from(s
),
998 #[stable(feature = "os_string_from_box", since = "1.18.0")]
999 impl From
<Box
<OsStr
>> for OsString
{
1000 /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or
1003 fn from(boxed
: Box
<OsStr
>) -> OsString
{
1004 boxed
.into_os_string()
1008 #[stable(feature = "box_from_os_string", since = "1.20.0")]
1009 impl From
<OsString
> for Box
<OsStr
> {
1010 /// Converts an [`OsString`] into a <code>[Box]<[OsStr]></code> without copying or allocating.
1012 fn from(s
: OsString
) -> Box
<OsStr
> {
1013 s
.into_boxed_os_str()
1017 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1018 impl Clone
for Box
<OsStr
> {
1020 fn clone(&self) -> Self {
1021 self.to_os_string().into_boxed_os_str()
1025 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1026 impl From
<OsString
> for Arc
<OsStr
> {
1027 /// Converts an [`OsString`] into an <code>[Arc]<[OsStr]></code> by moving the [`OsString`]
1028 /// data into a new [`Arc`] buffer.
1030 fn from(s
: OsString
) -> Arc
<OsStr
> {
1031 let arc
= s
.inner
.into_arc();
1032 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1036 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1037 impl From
<&OsStr
> for Arc
<OsStr
> {
1038 /// Copies the string into a newly allocated <code>[Arc]<[OsStr]></code>.
1040 fn from(s
: &OsStr
) -> Arc
<OsStr
> {
1041 let arc
= s
.inner
.into_arc();
1042 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1046 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1047 impl From
<OsString
> for Rc
<OsStr
> {
1048 /// Converts an [`OsString`] into an <code>[Rc]<[OsStr]></code> by moving the [`OsString`]
1049 /// data into a new [`Rc`] buffer.
1051 fn from(s
: OsString
) -> Rc
<OsStr
> {
1052 let rc
= s
.inner
.into_rc();
1053 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1057 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
1058 impl From
<&OsStr
> for Rc
<OsStr
> {
1059 /// Copies the string into a newly allocated <code>[Rc]<[OsStr]></code>.
1061 fn from(s
: &OsStr
) -> Rc
<OsStr
> {
1062 let rc
= s
.inner
.into_rc();
1063 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1067 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1068 impl<'a
> From
<OsString
> for Cow
<'a
, OsStr
> {
1069 /// Moves the string into a [`Cow::Owned`].
1071 fn from(s
: OsString
) -> Cow
<'a
, OsStr
> {
1076 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1077 impl<'a
> From
<&'a OsStr
> for Cow
<'a
, OsStr
> {
1078 /// Converts the string reference into a [`Cow::Borrowed`].
1080 fn from(s
: &'a OsStr
) -> Cow
<'a
, OsStr
> {
1085 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
1086 impl<'a
> From
<&'a OsString
> for Cow
<'a
, OsStr
> {
1087 /// Converts the string reference into a [`Cow::Borrowed`].
1089 fn from(s
: &'a OsString
) -> Cow
<'a
, OsStr
> {
1090 Cow
::Borrowed(s
.as_os_str())
1094 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
1095 impl<'a
> From
<Cow
<'a
, OsStr
>> for OsString
{
1096 /// Converts a `Cow<'a, OsStr>` into an [`OsString`],
1097 /// by copying the contents if they are borrowed.
1099 fn from(s
: Cow
<'a
, OsStr
>) -> Self {
1104 #[stable(feature = "box_default_extra", since = "1.17.0")]
1105 impl Default
for Box
<OsStr
> {
1107 fn default() -> Box
<OsStr
> {
1108 let rw
= Box
::into_raw(Slice
::empty_box()) as *mut OsStr
;
1109 unsafe { Box::from_raw(rw) }
1113 #[stable(feature = "osstring_default", since = "1.9.0")]
1114 impl Default
for &OsStr
{
1115 /// Creates an empty `OsStr`.
1117 fn default() -> Self {
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl PartialEq
for OsStr
{
1125 fn eq(&self, other
: &OsStr
) -> bool
{
1126 self.bytes().eq(other
.bytes())
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 impl PartialEq
<str> for OsStr
{
1133 fn eq(&self, other
: &str) -> bool
{
1134 *self == *OsStr
::new(other
)
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 impl PartialEq
<OsStr
> for str {
1141 fn eq(&self, other
: &OsStr
) -> bool
{
1142 *other
== *OsStr
::new(self)
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl Eq
for OsStr {}
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl PartialOrd
for OsStr
{
1152 fn partial_cmp(&self, other
: &OsStr
) -> Option
<cmp
::Ordering
> {
1153 self.bytes().partial_cmp(other
.bytes())
1156 fn lt(&self, other
: &OsStr
) -> bool
{
1157 self.bytes().lt(other
.bytes())
1160 fn le(&self, other
: &OsStr
) -> bool
{
1161 self.bytes().le(other
.bytes())
1164 fn gt(&self, other
: &OsStr
) -> bool
{
1165 self.bytes().gt(other
.bytes())
1168 fn ge(&self, other
: &OsStr
) -> bool
{
1169 self.bytes().ge(other
.bytes())
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 impl PartialOrd
<str> for OsStr
{
1176 fn partial_cmp(&self, other
: &str) -> Option
<cmp
::Ordering
> {
1177 self.partial_cmp(OsStr
::new(other
))
1181 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1182 // have more flexible coherence rules.
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl Ord
for OsStr
{
1187 fn cmp(&self, other
: &OsStr
) -> cmp
::Ordering
{
1188 self.bytes().cmp(other
.bytes())
1192 macro_rules
! impl_cmp
{
1193 ($lhs
:ty
, $rhs
: ty
) => {
1194 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1195 impl<'a
, 'b
> PartialEq
<$rhs
> for $lhs
{
1197 fn eq(&self, other
: &$rhs
) -> bool
{
1198 <OsStr
as PartialEq
>::eq(self, other
)
1202 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1203 impl<'a
, 'b
> PartialEq
<$lhs
> for $rhs
{
1205 fn eq(&self, other
: &$lhs
) -> bool
{
1206 <OsStr
as PartialEq
>::eq(self, other
)
1210 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1211 impl<'a
, 'b
> PartialOrd
<$rhs
> for $lhs
{
1213 fn partial_cmp(&self, other
: &$rhs
) -> Option
<cmp
::Ordering
> {
1214 <OsStr
as PartialOrd
>::partial_cmp(self, other
)
1218 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1219 impl<'a
, 'b
> PartialOrd
<$lhs
> for $rhs
{
1221 fn partial_cmp(&self, other
: &$lhs
) -> Option
<cmp
::Ordering
> {
1222 <OsStr
as PartialOrd
>::partial_cmp(self, other
)
1228 impl_cmp
!(OsString
, OsStr
);
1229 impl_cmp
!(OsString
, &'a OsStr
);
1230 impl_cmp
!(Cow
<'a
, OsStr
>, OsStr
);
1231 impl_cmp
!(Cow
<'a
, OsStr
>, &'b OsStr
);
1232 impl_cmp
!(Cow
<'a
, OsStr
>, OsString
);
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 impl Hash
for OsStr
{
1237 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
1238 self.bytes().hash(state
)
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl fmt
::Debug
for OsStr
{
1244 fn fmt(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1245 fmt
::Debug
::fmt(&self.inner
, formatter
)
1250 pub(crate) fn display(&self, formatter
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1251 fmt
::Display
::fmt(&self.inner
, formatter
)
1255 #[unstable(feature = "slice_concat_ext", issue = "27747")]
1256 impl<S
: Borrow
<OsStr
>> alloc
::slice
::Join
<&OsStr
> for [S
] {
1257 type Output
= OsString
;
1259 fn join(slice
: &Self, sep
: &OsStr
) -> OsString
{
1260 let Some((first
, suffix
)) = slice
.split_first() else {
1261 return OsString
::new();
1263 let first_owned
= first
.borrow().to_owned();
1264 suffix
.iter().fold(first_owned
, |mut a
, b
| {
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 impl Borrow
<OsStr
> for OsString
{
1275 fn borrow(&self) -> &OsStr
{
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 impl ToOwned
for OsStr
{
1282 type Owned
= OsString
;
1284 fn to_owned(&self) -> OsString
{
1288 fn clone_into(&self, target
: &mut OsString
) {
1289 self.inner
.clone_into(&mut target
.inner
)
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl AsRef
<OsStr
> for OsStr
{
1296 fn as_ref(&self) -> &OsStr
{
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl AsRef
<OsStr
> for OsString
{
1304 fn as_ref(&self) -> &OsStr
{
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 impl AsRef
<OsStr
> for str {
1312 fn as_ref(&self) -> &OsStr
{
1313 OsStr
::from_inner(Slice
::from_str(self))
1317 #[stable(feature = "rust1", since = "1.0.0")]
1318 impl AsRef
<OsStr
> for String
{
1320 fn as_ref(&self) -> &OsStr
{
1325 impl FromInner
<Buf
> for OsString
{
1327 fn from_inner(buf
: Buf
) -> OsString
{
1328 OsString { inner: buf }
1332 impl IntoInner
<Buf
> for OsString
{
1334 fn into_inner(self) -> Buf
{
1339 impl AsInner
<Slice
> for OsStr
{
1341 fn as_inner(&self) -> &Slice
{
1346 #[stable(feature = "osstring_from_str", since = "1.45.0")]
1347 impl FromStr
for OsString
{
1348 type Err
= core
::convert
::Infallible
;
1351 fn from_str(s
: &str) -> Result
<Self, Self::Err
> {
1352 Ok(OsString
::from(s
))
1356 #[stable(feature = "osstring_extend", since = "1.52.0")]
1357 impl Extend
<OsString
> for OsString
{
1359 fn extend
<T
: IntoIterator
<Item
= OsString
>>(&mut self, iter
: T
) {
1366 #[stable(feature = "osstring_extend", since = "1.52.0")]
1367 impl<'a
> Extend
<&'a OsStr
> for OsString
{
1369 fn extend
<T
: IntoIterator
<Item
= &'a OsStr
>>(&mut self, iter
: T
) {
1376 #[stable(feature = "osstring_extend", since = "1.52.0")]
1377 impl<'a
> Extend
<Cow
<'a
, OsStr
>> for OsString
{
1379 fn extend
<T
: IntoIterator
<Item
= Cow
<'a
, OsStr
>>>(&mut self, iter
: T
) {
1386 #[stable(feature = "osstring_extend", since = "1.52.0")]
1387 impl FromIterator
<OsString
> for OsString
{
1389 fn from_iter
<I
: IntoIterator
<Item
= OsString
>>(iter
: I
) -> Self {
1390 let mut iterator
= iter
.into_iter();
1392 // Because we're iterating over `OsString`s, we can avoid at least
1393 // one allocation by getting the first string from the iterator
1394 // and appending to it all the subsequent strings.
1395 match iterator
.next() {
1396 None
=> OsString
::new(),
1398 buf
.extend(iterator
);
1405 #[stable(feature = "osstring_extend", since = "1.52.0")]
1406 impl<'a
> FromIterator
<&'a OsStr
> for OsString
{
1408 fn from_iter
<I
: IntoIterator
<Item
= &'a OsStr
>>(iter
: I
) -> Self {
1409 let mut buf
= Self::new();
1417 #[stable(feature = "osstring_extend", since = "1.52.0")]
1418 impl<'a
> FromIterator
<Cow
<'a
, OsStr
>> for OsString
{
1420 fn from_iter
<I
: IntoIterator
<Item
= Cow
<'a
, OsStr
>>>(iter
: I
) -> Self {
1421 let mut iterator
= iter
.into_iter();
1423 // Because we're iterating over `OsString`s, we can avoid at least
1424 // one allocation by getting the first owned string from the iterator
1425 // and appending to it all the subsequent strings.
1426 match iterator
.next() {
1427 None
=> OsString
::new(),
1428 Some(Cow
::Owned(mut buf
)) => {
1429 buf
.extend(iterator
);
1432 Some(Cow
::Borrowed(buf
)) => {
1433 let mut buf
= OsString
::from(buf
);
1434 buf
.extend(iterator
);