std/ffi/os_str.rs
1//! The [`OsStr`] and [`OsString`] types and associated utilities.
2
3#[cfg(test)]
4mod tests;
5
6use core::clone::CloneToUninit;
7
8use crate::alloc::Allocator;
9use crate::borrow::{Borrow, Cow};
10use crate::collections::TryReserveError;
11use crate::hash::{Hash, Hasher};
12use crate::ops::{self, Range};
13use crate::rc::Rc;
14use crate::str::FromStr;
15use crate::sync::Arc;
16use crate::sys::os_str::{Buf, Slice};
17use crate::sys::{AsInner, FromInner, IntoInner};
18use crate::{cmp, fmt, slice};
19
20/// A type that can represent owned, mutable platform-native strings, but is
21/// cheaply inter-convertible with Rust strings.
22///
23/// The need for this type arises from the fact that:
24///
25/// * On Unix systems, strings are often arbitrary sequences of non-zero
26/// bytes, in many cases interpreted as UTF-8.
27///
28/// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
29/// values, interpreted as UTF-16 when it is valid to do so.
30///
31/// * In Rust, strings are always valid UTF-8, which may contain zeros.
32///
33/// `OsString` and [`OsStr`] bridge this gap by simultaneously representing Rust
34/// and platform-native string values, and in particular allowing a Rust string
35/// to be converted into an "OS" string with no cost if possible. A consequence
36/// of this is that `OsString` instances are *not* `NUL` terminated; in order
37/// to pass to e.g., Unix system call, you should create a [`CStr`].
38///
39/// `OsString` is to <code>&[OsStr]</code> as [`String`] is to <code>&[str]</code>: the former
40/// in each pair are owned strings; the latter are borrowed
41/// references.
42///
43/// Note, `OsString` and [`OsStr`] internally do not necessarily hold strings in
44/// the form native to the platform; While on Unix, strings are stored as a
45/// sequence of 8-bit values, on Windows, where strings are 16-bit value based
46/// as just discussed, strings are also actually stored as a sequence of 8-bit
47/// values, encoded in a less-strict variant of UTF-8. This is useful to
48/// understand when handling capacity and length values.
49///
50/// # Capacity of `OsString`
51///
52/// Capacity uses units of UTF-8 bytes for OS strings which were created from valid unicode, and
53/// uses units of bytes in an unspecified encoding for other contents. On a given target, all
54/// `OsString` and `OsStr` values use the same units for capacity, so the following will work:
55/// ```
56/// use std::ffi::{OsStr, OsString};
57///
58/// fn concat_os_strings(a: &OsStr, b: &OsStr) -> OsString {
59/// let mut ret = OsString::with_capacity(a.len() + b.len()); // This will allocate
60/// ret.push(a); // This will not allocate further
61/// ret.push(b); // This will not allocate further
62/// ret
63/// }
64/// ```
65///
66/// # Creating an `OsString`
67///
68/// **From a Rust string**: `OsString` implements
69/// <code>[From]<[String]></code>, so you can use <code>my_string.[into]\()</code> to
70/// create an `OsString` from a normal Rust string.
71///
72/// **From slices:** Just like you can start with an empty Rust
73/// [`String`] and then [`String::push_str`] some <code>&[str]</code>
74/// sub-string slices into it, you can create an empty `OsString` with
75/// the [`OsString::new`] method and then push string slices into it with the
76/// [`OsString::push`] method.
77///
78/// # Extracting a borrowed reference to the whole OS string
79///
80/// You can use the [`OsString::as_os_str`] method to get an <code>&[OsStr]</code> from
81/// an `OsString`; this is effectively a borrowed reference to the
82/// whole string.
83///
84/// # Conversions
85///
86/// See the [module's toplevel documentation about conversions][conversions] for a discussion on
87/// the traits which `OsString` implements for [conversions] from/to native representations.
88///
89/// [`CStr`]: crate::ffi::CStr
90/// [conversions]: super#conversions
91/// [into]: Into::into
92#[cfg_attr(not(test), rustc_diagnostic_item = "OsString")]
93#[stable(feature = "rust1", since = "1.0.0")]
94pub struct OsString {
95 inner: Buf,
96}
97
98/// Borrowed reference to an OS string (see [`OsString`]).
99///
100/// This type represents a borrowed reference to a string in the operating system's preferred
101/// representation.
102///
103/// `&OsStr` is to [`OsString`] as <code>&[str]</code> is to [`String`]: the
104/// former in each pair are borrowed references; the latter are owned strings.
105///
106/// See the [module's toplevel documentation about conversions][conversions] for a discussion on
107/// the traits which `OsStr` implements for [conversions] from/to native representations.
108///
109/// [conversions]: super#conversions
110#[cfg_attr(not(test), rustc_diagnostic_item = "OsStr")]
111#[stable(feature = "rust1", since = "1.0.0")]
112// `OsStr::from_inner` and `impl CloneToUninit for OsStr` current implementation relies
113// on `OsStr` being layout-compatible with `Slice`.
114// However, `OsStr` layout is considered an implementation detail and must not be relied upon.
115#[repr(transparent)]
116pub struct OsStr {
117 inner: Slice,
118}
119
120impl OsString {
121 /// Constructs a new empty `OsString`.
122 ///
123 /// # Examples
124 ///
125 /// ```
126 /// use std::ffi::OsString;
127 ///
128 /// let os_string = OsString::new();
129 /// ```
130 #[stable(feature = "rust1", since = "1.0.0")]
131 #[must_use]
132 #[inline]
133 #[rustc_const_stable(feature = "const_pathbuf_osstring_new", since = "1.91.0")]
134 pub const fn new() -> OsString {
135 OsString { inner: Buf::from_string(String::new()) }
136 }
137
138 /// Converts bytes to an `OsString` without checking that the bytes contains
139 /// valid [`OsStr`]-encoded data.
140 ///
141 /// The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8.
142 /// By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit
143 /// ASCII.
144 ///
145 /// See the [module's toplevel documentation about conversions][conversions] for safe,
146 /// cross-platform [conversions] from/to native representations.
147 ///
148 /// # Safety
149 ///
150 /// As the encoding is unspecified, callers must pass in bytes that originated as a mixture of
151 /// validated UTF-8 and bytes from [`OsStr::as_encoded_bytes`] from within the same Rust version
152 /// built for the same target platform. For example, reconstructing an `OsString` from bytes sent
153 /// over the network or stored in a file will likely violate these safety rules.
154 ///
155 /// Due to the encoding being self-synchronizing, the bytes from [`OsStr::as_encoded_bytes`] can be
156 /// split either immediately before or immediately after any valid non-empty UTF-8 substring.
157 ///
158 /// # Example
159 ///
160 /// ```
161 /// use std::ffi::OsStr;
162 ///
163 /// let os_str = OsStr::new("Mary had a little lamb");
164 /// let bytes = os_str.as_encoded_bytes();
165 /// let words = bytes.split(|b| *b == b' ');
166 /// let words: Vec<&OsStr> = words.map(|word| {
167 /// // SAFETY:
168 /// // - Each `word` only contains content that originated from `OsStr::as_encoded_bytes`
169 /// // - Only split with ASCII whitespace which is a non-empty UTF-8 substring
170 /// unsafe { OsStr::from_encoded_bytes_unchecked(word) }
171 /// }).collect();
172 /// ```
173 ///
174 /// [conversions]: super#conversions
175 #[inline]
176 #[stable(feature = "os_str_bytes", since = "1.74.0")]
177 pub unsafe fn from_encoded_bytes_unchecked(bytes: Vec<u8>) -> Self {
178 OsString { inner: unsafe { Buf::from_encoded_bytes_unchecked(bytes) } }
179 }
180
181 /// Converts to an [`OsStr`] slice.
182 ///
183 /// # Examples
184 ///
185 /// ```
186 /// use std::ffi::{OsString, OsStr};
187 ///
188 /// let os_string = OsString::from("foo");
189 /// let os_str = OsStr::new("foo");
190 /// assert_eq!(os_string.as_os_str(), os_str);
191 /// ```
192 #[cfg_attr(not(test), rustc_diagnostic_item = "os_string_as_os_str")]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 #[must_use]
195 #[inline]
196 pub fn as_os_str(&self) -> &OsStr {
197 self
198 }
199
200 /// Converts the `OsString` into a byte vector. To convert the byte vector back into an
201 /// `OsString`, use the [`OsString::from_encoded_bytes_unchecked`] function.
202 ///
203 /// The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8.
204 /// By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit
205 /// ASCII.
206 ///
207 /// Note: As the encoding is unspecified, any sub-slice of bytes that is not valid UTF-8 should
208 /// be treated as opaque and only comparable within the same Rust version built for the same
209 /// target platform. For example, sending the bytes over the network or storing it in a file
210 /// will likely result in incompatible data. See [`OsString`] for more encoding details
211 /// and [`std::ffi`] for platform-specific, specified conversions.
212 ///
213 /// [`std::ffi`]: crate::ffi
214 #[inline]
215 #[stable(feature = "os_str_bytes", since = "1.74.0")]
216 pub fn into_encoded_bytes(self) -> Vec<u8> {
217 self.inner.into_encoded_bytes()
218 }
219
220 /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
221 ///
222 /// On failure, ownership of the original `OsString` is returned.
223 ///
224 /// # Examples
225 ///
226 /// ```
227 /// use std::ffi::OsString;
228 ///
229 /// let os_string = OsString::from("foo");
230 /// let string = os_string.into_string();
231 /// assert_eq!(string, Ok(String::from("foo")));
232 /// ```
233 #[stable(feature = "rust1", since = "1.0.0")]
234 #[inline]
235 pub fn into_string(self) -> Result<String, OsString> {
236 self.inner.into_string().map_err(|buf| OsString { inner: buf })
237 }
238
239 /// Extends the string with the given <code>&[OsStr]</code> slice.
240 ///
241 /// # Examples
242 ///
243 /// ```
244 /// use std::ffi::OsString;
245 ///
246 /// let mut os_string = OsString::from("foo");
247 /// os_string.push("bar");
248 /// assert_eq!(&os_string, "foobar");
249 /// ```
250 #[stable(feature = "rust1", since = "1.0.0")]
251 #[inline]
252 #[rustc_confusables("append", "put")]
253 pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
254 trait SpecPushTo {
255 fn spec_push_to(&self, buf: &mut OsString);
256 }
257
258 impl<T: AsRef<OsStr>> SpecPushTo for T {
259 #[inline]
260 default fn spec_push_to(&self, buf: &mut OsString) {
261 buf.inner.push_slice(&self.as_ref().inner);
262 }
263 }
264
265 // Use a more efficient implementation when the string is UTF-8.
266 macro spec_str($T:ty) {
267 impl SpecPushTo for $T {
268 #[inline]
269 fn spec_push_to(&self, buf: &mut OsString) {
270 buf.inner.push_str(self);
271 }
272 }
273 }
274 spec_str!(str);
275 spec_str!(String);
276
277 s.spec_push_to(self)
278 }
279
280 /// Creates a new `OsString` with at least the given capacity.
281 ///
282 /// The string will be able to hold at least `capacity` length units of other
283 /// OS strings without reallocating. This method is allowed to allocate for
284 /// more units than `capacity`. If `capacity` is 0, the string will not
285 /// allocate.
286 ///
287 /// See the main `OsString` documentation information about encoding and capacity units.
288 ///
289 /// # Examples
290 ///
291 /// ```
292 /// use std::ffi::OsString;
293 ///
294 /// let mut os_string = OsString::with_capacity(10);
295 /// let capacity = os_string.capacity();
296 ///
297 /// // This push is done without reallocating
298 /// os_string.push("foo");
299 ///
300 /// assert_eq!(capacity, os_string.capacity());
301 /// ```
302 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
303 #[must_use]
304 #[inline]
305 pub fn with_capacity(capacity: usize) -> OsString {
306 OsString { inner: Buf::with_capacity(capacity) }
307 }
308
309 /// Truncates the `OsString` to zero length.
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// use std::ffi::OsString;
315 ///
316 /// let mut os_string = OsString::from("foo");
317 /// assert_eq!(&os_string, "foo");
318 ///
319 /// os_string.clear();
320 /// assert_eq!(&os_string, "");
321 /// ```
322 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
323 #[inline]
324 pub fn clear(&mut self) {
325 self.inner.clear()
326 }
327
328 /// Returns the capacity this `OsString` can hold without reallocating.
329 ///
330 /// See the main `OsString` documentation information about encoding and capacity units.
331 ///
332 /// # Examples
333 ///
334 /// ```
335 /// use std::ffi::OsString;
336 ///
337 /// let os_string = OsString::with_capacity(10);
338 /// assert!(os_string.capacity() >= 10);
339 /// ```
340 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
341 #[must_use]
342 #[inline]
343 pub fn capacity(&self) -> usize {
344 self.inner.capacity()
345 }
346
347 /// Reserves capacity for at least `additional` more capacity to be inserted
348 /// in the given `OsString`. Does nothing if the capacity is
349 /// already sufficient.
350 ///
351 /// The collection may reserve more space to speculatively avoid frequent reallocations.
352 ///
353 /// See the main `OsString` documentation information about encoding and capacity units.
354 ///
355 /// # Examples
356 ///
357 /// ```
358 /// use std::ffi::OsString;
359 ///
360 /// let mut s = OsString::new();
361 /// s.reserve(10);
362 /// assert!(s.capacity() >= 10);
363 /// ```
364 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
365 #[inline]
366 pub fn reserve(&mut self, additional: usize) {
367 self.inner.reserve(additional)
368 }
369
370 /// Tries to reserve capacity for at least `additional` more length units
371 /// in the given `OsString`. The string may reserve more space to speculatively avoid
372 /// frequent reallocations. After calling `try_reserve`, capacity will be
373 /// greater than or equal to `self.len() + additional` if it returns `Ok(())`.
374 /// Does nothing if capacity is already sufficient. This method preserves
375 /// the contents even if an error occurs.
376 ///
377 /// See the main `OsString` documentation information about encoding and capacity units.
378 ///
379 /// # Errors
380 ///
381 /// If the capacity overflows, or the allocator reports a failure, then an error
382 /// is returned.
383 ///
384 /// # Examples
385 ///
386 /// ```
387 /// use std::ffi::{OsStr, OsString};
388 /// use std::collections::TryReserveError;
389 ///
390 /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
391 /// let mut s = OsString::new();
392 ///
393 /// // Pre-reserve the memory, exiting if we can't
394 /// s.try_reserve(OsStr::new(data).len())?;
395 ///
396 /// // Now we know this can't OOM in the middle of our complex work
397 /// s.push(data);
398 ///
399 /// Ok(s)
400 /// }
401 /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
402 /// ```
403 #[stable(feature = "try_reserve_2", since = "1.63.0")]
404 #[inline]
405 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
406 self.inner.try_reserve(additional)
407 }
408
409 /// Reserves the minimum capacity for at least `additional` more capacity to
410 /// be inserted in the given `OsString`. Does nothing if the capacity is
411 /// already sufficient.
412 ///
413 /// Note that the allocator may give the collection more space than it
414 /// requests. Therefore, capacity can not be relied upon to be precisely
415 /// minimal. Prefer [`reserve`] if future insertions are expected.
416 ///
417 /// [`reserve`]: OsString::reserve
418 ///
419 /// See the main `OsString` documentation information about encoding and capacity units.
420 ///
421 /// # Examples
422 ///
423 /// ```
424 /// use std::ffi::OsString;
425 ///
426 /// let mut s = OsString::new();
427 /// s.reserve_exact(10);
428 /// assert!(s.capacity() >= 10);
429 /// ```
430 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
431 #[inline]
432 pub fn reserve_exact(&mut self, additional: usize) {
433 self.inner.reserve_exact(additional)
434 }
435
436 /// Tries to reserve the minimum capacity for at least `additional`
437 /// more length units in the given `OsString`. After calling
438 /// `try_reserve_exact`, capacity will be greater than or equal to
439 /// `self.len() + additional` if it returns `Ok(())`.
440 /// Does nothing if the capacity is already sufficient.
441 ///
442 /// Note that the allocator may give the `OsString` more space than it
443 /// requests. Therefore, capacity can not be relied upon to be precisely
444 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
445 ///
446 /// [`try_reserve`]: OsString::try_reserve
447 ///
448 /// See the main `OsString` documentation information about encoding and capacity units.
449 ///
450 /// # Errors
451 ///
452 /// If the capacity overflows, or the allocator reports a failure, then an error
453 /// is returned.
454 ///
455 /// # Examples
456 ///
457 /// ```
458 /// use std::ffi::{OsStr, OsString};
459 /// use std::collections::TryReserveError;
460 ///
461 /// fn process_data(data: &str) -> Result<OsString, TryReserveError> {
462 /// let mut s = OsString::new();
463 ///
464 /// // Pre-reserve the memory, exiting if we can't
465 /// s.try_reserve_exact(OsStr::new(data).len())?;
466 ///
467 /// // Now we know this can't OOM in the middle of our complex work
468 /// s.push(data);
469 ///
470 /// Ok(s)
471 /// }
472 /// # process_data("123").expect("why is the test harness OOMing on 3 bytes?");
473 /// ```
474 #[stable(feature = "try_reserve_2", since = "1.63.0")]
475 #[inline]
476 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
477 self.inner.try_reserve_exact(additional)
478 }
479
480 /// Shrinks the capacity of the `OsString` to match its length.
481 ///
482 /// See the main `OsString` documentation information about encoding and capacity units.
483 ///
484 /// # Examples
485 ///
486 /// ```
487 /// use std::ffi::OsString;
488 ///
489 /// let mut s = OsString::from("foo");
490 ///
491 /// s.reserve(100);
492 /// assert!(s.capacity() >= 100);
493 ///
494 /// s.shrink_to_fit();
495 /// assert_eq!(3, s.capacity());
496 /// ```
497 #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
498 #[inline]
499 pub fn shrink_to_fit(&mut self) {
500 self.inner.shrink_to_fit()
501 }
502
503 /// Shrinks the capacity of the `OsString` with a lower bound.
504 ///
505 /// The capacity will remain at least as large as both the length
506 /// and the supplied value.
507 ///
508 /// If the current capacity is less than the lower limit, this is a no-op.
509 ///
510 /// See the main `OsString` documentation information about encoding and capacity units.
511 ///
512 /// # Examples
513 ///
514 /// ```
515 /// use std::ffi::OsString;
516 ///
517 /// let mut s = OsString::from("foo");
518 ///
519 /// s.reserve(100);
520 /// assert!(s.capacity() >= 100);
521 ///
522 /// s.shrink_to(10);
523 /// assert!(s.capacity() >= 10);
524 /// s.shrink_to(0);
525 /// assert!(s.capacity() >= 3);
526 /// ```
527 #[inline]
528 #[stable(feature = "shrink_to", since = "1.56.0")]
529 pub fn shrink_to(&mut self, min_capacity: usize) {
530 self.inner.shrink_to(min_capacity)
531 }
532
533 /// Converts this `OsString` into a boxed [`OsStr`].
534 ///
535 /// # Examples
536 ///
537 /// ```
538 /// use std::ffi::{OsString, OsStr};
539 ///
540 /// let s = OsString::from("hello");
541 ///
542 /// let b: Box<OsStr> = s.into_boxed_os_str();
543 /// ```
544 #[must_use = "`self` will be dropped if the result is not used"]
545 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
546 pub fn into_boxed_os_str(self) -> Box<OsStr> {
547 let rw = Box::into_raw(self.inner.into_box()) as *mut OsStr;
548 unsafe { Box::from_raw(rw) }
549 }
550
551 /// Consumes and leaks the `OsString`, returning a mutable reference to the contents,
552 /// `&'a mut OsStr`.
553 ///
554 /// The caller has free choice over the returned lifetime, including 'static.
555 /// Indeed, this function is ideally used for data that lives for the remainder of
556 /// the program’s life, as dropping the returned reference will cause a memory leak.
557 ///
558 /// It does not reallocate or shrink the `OsString`, so the leaked allocation may include
559 /// unused capacity that is not part of the returned slice. If you want to discard excess
560 /// capacity, call [`into_boxed_os_str`], and then [`Box::leak`] instead.
561 /// However, keep in mind that trimming the capacity may result in a reallocation and copy.
562 ///
563 /// [`into_boxed_os_str`]: Self::into_boxed_os_str
564 #[stable(feature = "os_string_pathbuf_leak", since = "1.89.0")]
565 #[inline]
566 pub fn leak<'a>(self) -> &'a mut OsStr {
567 OsStr::from_inner_mut(self.inner.leak())
568 }
569
570 /// Truncate the `OsString` to the specified length.
571 ///
572 /// If `new_len` is greater than or equal to the string's current length,
573 /// this has no effect.
574 ///
575 /// # Panics
576 ///
577 /// Panics if `len` does not lie on a valid `OsStr` boundary
578 /// (as described in [`OsStr::slice_encoded_bytes`]).
579 #[inline]
580 #[unstable(feature = "os_string_truncate", issue = "133262")]
581 pub fn truncate(&mut self, len: usize) {
582 if len >= self.len() {
583 return;
584 }
585 self.as_os_str().inner.check_public_boundary(len);
586 // SAFETY: The length was just checked to be at a valid boundary.
587 unsafe { self.inner.truncate_unchecked(len) };
588 }
589
590 /// Provides plumbing to `Vec::extend_from_slice` without giving full
591 /// mutable access to the `Vec`.
592 ///
593 /// # Safety
594 ///
595 /// The slice must be valid for the platform encoding (as described in
596 /// [`OsStr::from_encoded_bytes_unchecked`]).
597 ///
598 /// This bypasses the encoding-dependent surrogate joining, so either
599 /// `self` must not end with a leading surrogate half, or `other` must not
600 /// start with a trailing surrogate half.
601 #[inline]
602 pub(crate) unsafe fn extend_from_slice_unchecked(&mut self, other: &[u8]) {
603 // SAFETY: Guaranteed by caller.
604 unsafe { self.inner.extend_from_slice_unchecked(other) };
605 }
606}
607
608#[stable(feature = "rust1", since = "1.0.0")]
609impl From<String> for OsString {
610 /// Converts a [`String`] into an [`OsString`].
611 ///
612 /// This conversion does not allocate or copy memory.
613 #[inline]
614 fn from(s: String) -> OsString {
615 OsString { inner: Buf::from_string(s) }
616 }
617}
618
619#[stable(feature = "rust1", since = "1.0.0")]
620impl<T: ?Sized + AsRef<OsStr>> From<&T> for OsString {
621 /// Copies any value implementing <code>[AsRef]<[OsStr]></code>
622 /// into a newly allocated [`OsString`].
623 fn from(s: &T) -> OsString {
624 trait SpecToOsString {
625 fn spec_to_os_string(&self) -> OsString;
626 }
627
628 impl<T: AsRef<OsStr>> SpecToOsString for T {
629 #[inline]
630 default fn spec_to_os_string(&self) -> OsString {
631 self.as_ref().to_os_string()
632 }
633 }
634
635 // Preserve the known-UTF-8 property for strings.
636 macro spec_str($T:ty) {
637 impl SpecToOsString for $T {
638 #[inline]
639 fn spec_to_os_string(&self) -> OsString {
640 OsString::from(String::from(self))
641 }
642 }
643 }
644 spec_str!(str);
645 spec_str!(String);
646
647 s.spec_to_os_string()
648 }
649}
650
651#[ferrocene::prevalidated]
652#[stable(feature = "rust1", since = "1.0.0")]
653impl ops::Index<ops::RangeFull> for OsString {
654 type Output = OsStr;
655
656 #[inline]
657 fn index(&self, _index: ops::RangeFull) -> &OsStr {
658 OsStr::from_inner(self.inner.as_slice())
659 }
660}
661
662#[stable(feature = "mut_osstr", since = "1.44.0")]
663impl ops::IndexMut<ops::RangeFull> for OsString {
664 #[inline]
665 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut OsStr {
666 OsStr::from_inner_mut(self.inner.as_mut_slice())
667 }
668}
669
670#[ferrocene::prevalidated]
671#[stable(feature = "rust1", since = "1.0.0")]
672impl ops::Deref for OsString {
673 type Target = OsStr;
674
675 #[inline]
676 fn deref(&self) -> &OsStr {
677 &self[..]
678 }
679}
680
681#[stable(feature = "mut_osstr", since = "1.44.0")]
682impl ops::DerefMut for OsString {
683 #[inline]
684 fn deref_mut(&mut self) -> &mut OsStr {
685 &mut self[..]
686 }
687}
688
689#[stable(feature = "osstring_default", since = "1.9.0")]
690impl Default for OsString {
691 /// Constructs an empty `OsString`.
692 #[inline]
693 fn default() -> OsString {
694 OsString::new()
695 }
696}
697
698#[stable(feature = "rust1", since = "1.0.0")]
699impl Clone for OsString {
700 #[inline]
701 fn clone(&self) -> Self {
702 OsString { inner: self.inner.clone() }
703 }
704
705 /// Clones the contents of `source` into `self`.
706 ///
707 /// This method is preferred over simply assigning `source.clone()` to `self`,
708 /// as it avoids reallocation if possible.
709 #[inline]
710 fn clone_from(&mut self, source: &Self) {
711 self.inner.clone_from(&source.inner)
712 }
713}
714
715#[stable(feature = "rust1", since = "1.0.0")]
716impl fmt::Debug for OsString {
717 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
718 fmt::Debug::fmt(&**self, formatter)
719 }
720}
721
722#[stable(feature = "rust1", since = "1.0.0")]
723impl PartialEq for OsString {
724 #[inline]
725 fn eq(&self, other: &OsString) -> bool {
726 **self == **other
727 }
728}
729
730#[stable(feature = "rust1", since = "1.0.0")]
731impl PartialEq<str> for OsString {
732 #[inline]
733 fn eq(&self, other: &str) -> bool {
734 &**self == other
735 }
736}
737
738#[stable(feature = "rust1", since = "1.0.0")]
739impl PartialEq<OsString> for str {
740 #[inline]
741 fn eq(&self, other: &OsString) -> bool {
742 &**other == self
743 }
744}
745
746#[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
747impl PartialEq<&str> for OsString {
748 #[inline]
749 fn eq(&self, other: &&str) -> bool {
750 **self == **other
751 }
752}
753
754#[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
755impl<'a> PartialEq<OsString> for &'a str {
756 #[inline]
757 fn eq(&self, other: &OsString) -> bool {
758 **other == **self
759 }
760}
761
762#[stable(feature = "rust1", since = "1.0.0")]
763impl Eq for OsString {}
764
765#[stable(feature = "rust1", since = "1.0.0")]
766impl PartialOrd for OsString {
767 #[inline]
768 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
769 (**self).partial_cmp(&**other)
770 }
771 #[inline]
772 fn lt(&self, other: &OsString) -> bool {
773 **self < **other
774 }
775 #[inline]
776 fn le(&self, other: &OsString) -> bool {
777 **self <= **other
778 }
779 #[inline]
780 fn gt(&self, other: &OsString) -> bool {
781 **self > **other
782 }
783 #[inline]
784 fn ge(&self, other: &OsString) -> bool {
785 **self >= **other
786 }
787}
788
789#[stable(feature = "rust1", since = "1.0.0")]
790impl PartialOrd<str> for OsString {
791 #[inline]
792 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
793 (**self).partial_cmp(other)
794 }
795}
796
797#[stable(feature = "rust1", since = "1.0.0")]
798impl Ord for OsString {
799 #[inline]
800 fn cmp(&self, other: &OsString) -> cmp::Ordering {
801 (**self).cmp(&**other)
802 }
803}
804
805#[stable(feature = "rust1", since = "1.0.0")]
806impl Hash for OsString {
807 #[inline]
808 fn hash<H: Hasher>(&self, state: &mut H) {
809 (**self).hash(state)
810 }
811}
812
813#[stable(feature = "os_string_fmt_write", since = "1.64.0")]
814impl fmt::Write for OsString {
815 fn write_str(&mut self, s: &str) -> fmt::Result {
816 self.push(s);
817 Ok(())
818 }
819}
820
821impl OsStr {
822 /// Coerces into an `OsStr` slice.
823 ///
824 /// # Examples
825 ///
826 /// ```
827 /// use std::ffi::OsStr;
828 ///
829 /// let os_str = OsStr::new("foo");
830 /// ```
831 #[inline]
832 #[stable(feature = "rust1", since = "1.0.0")]
833 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
834 pub const fn new<S: [const] AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
835 s.as_ref()
836 }
837
838 /// Converts a slice of bytes to an OS string slice without checking that the string contains
839 /// valid `OsStr`-encoded data.
840 ///
841 /// The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8.
842 /// By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit
843 /// ASCII.
844 ///
845 /// See the [module's toplevel documentation about conversions][conversions] for safe,
846 /// cross-platform [conversions] from/to native representations.
847 ///
848 /// # Safety
849 ///
850 /// As the encoding is unspecified, callers must pass in bytes that originated as a mixture of
851 /// validated UTF-8 and bytes from [`OsStr::as_encoded_bytes`] from within the same Rust version
852 /// built for the same target platform. For example, reconstructing an `OsStr` from bytes sent
853 /// over the network or stored in a file will likely violate these safety rules.
854 ///
855 /// Due to the encoding being self-synchronizing, the bytes from [`OsStr::as_encoded_bytes`] can be
856 /// split either immediately before or immediately after any valid non-empty UTF-8 substring.
857 ///
858 /// # Example
859 ///
860 /// ```
861 /// use std::ffi::OsStr;
862 ///
863 /// let os_str = OsStr::new("Mary had a little lamb");
864 /// let bytes = os_str.as_encoded_bytes();
865 /// let words = bytes.split(|b| *b == b' ');
866 /// let words: Vec<&OsStr> = words.map(|word| {
867 /// // SAFETY:
868 /// // - Each `word` only contains content that originated from `OsStr::as_encoded_bytes`
869 /// // - Only split with ASCII whitespace which is a non-empty UTF-8 substring
870 /// unsafe { OsStr::from_encoded_bytes_unchecked(word) }
871 /// }).collect();
872 /// ```
873 ///
874 /// [conversions]: super#conversions
875 #[inline]
876 #[stable(feature = "os_str_bytes", since = "1.74.0")]
877 pub unsafe fn from_encoded_bytes_unchecked(bytes: &[u8]) -> &Self {
878 Self::from_inner(unsafe { Slice::from_encoded_bytes_unchecked(bytes) })
879 }
880
881 #[ferrocene::prevalidated]
882 #[inline]
883 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
884 const fn from_inner(inner: &Slice) -> &OsStr {
885 // SAFETY: OsStr is just a wrapper of Slice,
886 // therefore converting &Slice to &OsStr is safe.
887 unsafe { &*(inner as *const Slice as *const OsStr) }
888 }
889
890 #[inline]
891 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
892 const fn from_inner_mut(inner: &mut Slice) -> &mut OsStr {
893 // SAFETY: OsStr is just a wrapper of Slice,
894 // therefore converting &mut Slice to &mut OsStr is safe.
895 // Any method that mutates OsStr must be careful not to
896 // break platform-specific encoding, in particular Wtf8 on Windows.
897 unsafe { &mut *(inner as *mut Slice as *mut OsStr) }
898 }
899
900 /// Yields a <code>&[str]</code> slice if the `OsStr` is valid Unicode.
901 ///
902 /// This conversion may entail doing a check for UTF-8 validity.
903 ///
904 /// # Examples
905 ///
906 /// ```
907 /// use std::ffi::OsStr;
908 ///
909 /// let os_str = OsStr::new("foo");
910 /// assert_eq!(os_str.to_str(), Some("foo"));
911 /// ```
912 #[ferrocene::prevalidated]
913 #[stable(feature = "rust1", since = "1.0.0")]
914 #[must_use = "this returns the result of the operation, \
915 without modifying the original"]
916 #[inline]
917 pub fn to_str(&self) -> Option<&str> {
918 self.inner.to_str().ok()
919 }
920
921 /// Converts an `OsStr` to a <code>[Cow]<[str]></code>.
922 ///
923 /// Any non-UTF-8 sequences are replaced with
924 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
925 ///
926 /// [U+FFFD]: char::REPLACEMENT_CHARACTER
927 ///
928 /// # Examples
929 ///
930 /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
931 ///
932 /// ```
933 /// // Note, due to differences in how Unix and Windows represent strings,
934 /// // we are forced to complicate this example, setting up example `OsStr`s
935 /// // with different source data and via different platform extensions.
936 /// // Understand that in reality you could end up with such example invalid
937 /// // sequences simply through collecting user command line arguments, for
938 /// // example.
939 ///
940 /// #[cfg(unix)] {
941 /// use std::ffi::OsStr;
942 /// use std::os::unix::ffi::OsStrExt;
943 ///
944 /// // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
945 /// // respectively. The value 0x80 is a lone continuation byte, invalid
946 /// // in a UTF-8 sequence.
947 /// let source = [0x66, 0x6f, 0x80, 0x6f];
948 /// let os_str = OsStr::from_bytes(&source[..]);
949 ///
950 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
951 /// }
952 /// #[cfg(windows)] {
953 /// use std::ffi::OsString;
954 /// use std::os::windows::prelude::*;
955 ///
956 /// // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
957 /// // respectively. The value 0xD800 is a lone surrogate half, invalid
958 /// // in a UTF-16 sequence.
959 /// let source = [0x0066, 0x006f, 0xD800, 0x006f];
960 /// let os_string = OsString::from_wide(&source[..]);
961 /// let os_str = os_string.as_os_str();
962 ///
963 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
964 /// }
965 /// ```
966 #[stable(feature = "rust1", since = "1.0.0")]
967 #[must_use = "this returns the result of the operation, \
968 without modifying the original"]
969 #[inline]
970 pub fn to_string_lossy(&self) -> Cow<'_, str> {
971 self.inner.to_string_lossy()
972 }
973
974 /// Copies the slice into an owned [`OsString`].
975 ///
976 /// # Examples
977 ///
978 /// ```
979 /// use std::ffi::{OsStr, OsString};
980 ///
981 /// let os_str = OsStr::new("foo");
982 /// let os_string = os_str.to_os_string();
983 /// assert_eq!(os_string, OsString::from("foo"));
984 /// ```
985 #[stable(feature = "rust1", since = "1.0.0")]
986 #[must_use = "this returns the result of the operation, \
987 without modifying the original"]
988 #[inline]
989 #[cfg_attr(not(test), rustc_diagnostic_item = "os_str_to_os_string")]
990 pub fn to_os_string(&self) -> OsString {
991 OsString { inner: self.inner.to_owned() }
992 }
993
994 /// Checks whether the `OsStr` is empty.
995 ///
996 /// # Examples
997 ///
998 /// ```
999 /// use std::ffi::OsStr;
1000 ///
1001 /// let os_str = OsStr::new("");
1002 /// assert!(os_str.is_empty());
1003 ///
1004 /// let os_str = OsStr::new("foo");
1005 /// assert!(!os_str.is_empty());
1006 /// ```
1007 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
1008 #[must_use]
1009 #[inline]
1010 pub fn is_empty(&self) -> bool {
1011 self.inner.inner.is_empty()
1012 }
1013
1014 /// Returns the length of this `OsStr`.
1015 ///
1016 /// Note that this does **not** return the number of bytes in the string in
1017 /// OS string form.
1018 ///
1019 /// The length returned is that of the underlying storage used by `OsStr`.
1020 /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
1021 /// store strings in a form best suited for cheap inter-conversion between
1022 /// native-platform and Rust string forms, which may differ significantly
1023 /// from both of them, including in storage size and encoding.
1024 ///
1025 /// This number is simply useful for passing to other methods, like
1026 /// [`OsString::with_capacity`] to avoid reallocations.
1027 ///
1028 /// See the main `OsString` documentation information about encoding and capacity units.
1029 ///
1030 /// # Examples
1031 ///
1032 /// ```
1033 /// use std::ffi::OsStr;
1034 ///
1035 /// let os_str = OsStr::new("");
1036 /// assert_eq!(os_str.len(), 0);
1037 ///
1038 /// let os_str = OsStr::new("foo");
1039 /// assert_eq!(os_str.len(), 3);
1040 /// ```
1041 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
1042 #[must_use]
1043 #[inline]
1044 pub fn len(&self) -> usize {
1045 self.inner.inner.len()
1046 }
1047
1048 /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or allocating.
1049 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
1050 #[must_use = "`self` will be dropped if the result is not used"]
1051 pub fn into_os_string(self: Box<Self>) -> OsString {
1052 let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
1053 OsString { inner: Buf::from_box(boxed) }
1054 }
1055
1056 /// Divides one string slice into two at an index.
1057 ///
1058 /// The two slices returned go from the start of the string slice to `mid`, and from `mid` to the end of the string slice.
1059 ///
1060 /// The argument, `mid`, should be a byte offset from the start of the string.
1061 /// It must also be on a valid `OsStr` boundary.
1062 /// See [`split_at_checked`][Self::split_at_checked] for the definition of a valid boundary.
1063 ///
1064 /// Panics
1065 ///
1066 /// Panics if `mid` is not on a valid boundary, or if it is past the end of the last code point of the string slice.
1067 /// For a non-panicking alternative see [`split_at_checked`][Self::split_at_checked].
1068 #[unstable(feature = "os_str_split_at", issue = "none")]
1069 pub fn split_at(&self, mid: usize) -> (&OsStr, &OsStr) {
1070 self.inner.check_public_boundary(mid);
1071
1072 // SAFETY: we've checked it's in bounds and a valid boundary
1073 unsafe { self.split_at_unchecked(mid) }
1074 }
1075
1076 /// Divides one string slice into two at an index.
1077 ///
1078 /// The two slices returned go from the start of the string slice to `mid`, and from `mid` to the end of the string slice.
1079 ///
1080 /// The argument, `mid`, should be a valid byte offset from the start of the string.
1081 /// It must also be on a valid `OsStr` boundary.
1082 /// The method returns `None` if that’s not the case.
1083 /// A valid `OsStr` boundary is one of:
1084 /// - The start of the string
1085 /// - The end of the string
1086 /// - The start of a valid non-empty UTF-8 substring
1087 /// - Immediately follows a valid non-empty UTF-8 substring
1088 #[unstable(feature = "os_str_split_at", issue = "none")]
1089 pub fn split_at_checked(&self, mid: usize) -> Option<(&OsStr, &OsStr)> {
1090 self.inner.try_check_public_boundary(mid)?;
1091
1092 // SAFETY: we've checked it's in bounds and a valid boundary
1093 unsafe { Some(self.split_at_unchecked(mid)) }
1094 }
1095
1096 /// Splits an `OsStr` without checking if `mid` is a valid boundary.
1097 /// You should use `split_at` or `split_at_checked` instead.
1098 ///
1099 /// # Safety
1100 ///
1101 /// Any caller must ensure `mid` is within bounds and lies on
1102 /// a valid `OsStr` boundary for the platform.
1103 #[unstable(feature = "str_split_at_unchecked", issue = "165545")]
1104 pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&OsStr, &OsStr) {
1105 debug_assert!(
1106 self.inner.try_check_public_boundary(mid).is_some(),
1107 "OsStr::split_at_unchecked requires the index to be on a valid `OsStr` boundary",
1108 );
1109
1110 // SAFETY: it's up to the caller to ensure this is safe.
1111 unsafe {
1112 let (first, second) = self.as_encoded_bytes().split_at_unchecked(mid);
1113 (Self::from_encoded_bytes_unchecked(first), Self::from_encoded_bytes_unchecked(second))
1114 }
1115 }
1116
1117 /// Converts an OS string slice to a byte slice. To convert the byte slice back into an OS
1118 /// string slice, use the [`OsStr::from_encoded_bytes_unchecked`] function.
1119 ///
1120 /// The byte encoding is an unspecified, platform-specific, self-synchronizing superset of UTF-8.
1121 /// By being a self-synchronizing superset of UTF-8, this encoding is also a superset of 7-bit
1122 /// ASCII.
1123 ///
1124 /// Note: As the encoding is unspecified, any sub-slice of bytes that is not valid UTF-8 should
1125 /// be treated as opaque and only comparable within the same Rust version built for the same
1126 /// target platform. For example, sending the slice over the network or storing it in a file
1127 /// will likely result in incompatible byte slices. See [`OsString`] for more encoding details
1128 /// and [`std::ffi`] for platform-specific, specified conversions.
1129 ///
1130 /// [`std::ffi`]: crate::ffi
1131 #[inline]
1132 #[stable(feature = "os_str_bytes", since = "1.74.0")]
1133 pub fn as_encoded_bytes(&self) -> &[u8] {
1134 self.inner.as_encoded_bytes()
1135 }
1136
1137 /// Takes a substring based on a range that corresponds to the return value of
1138 /// [`OsStr::as_encoded_bytes`].
1139 ///
1140 /// The range's start and end must lie on valid `OsStr` boundaries.
1141 /// A valid `OsStr` boundary is one of:
1142 /// - The start of the string
1143 /// - The end of the string
1144 /// - Immediately before a valid non-empty UTF-8 substring
1145 /// - Immediately after a valid non-empty UTF-8 substring
1146 ///
1147 /// # Panics
1148 ///
1149 /// Panics if `range` does not lie on valid `OsStr` boundaries or if it
1150 /// exceeds the end of the string.
1151 ///
1152 /// # Example
1153 ///
1154 /// ```
1155 /// #![feature(os_str_slice)]
1156 ///
1157 /// use std::ffi::OsStr;
1158 ///
1159 /// let os_str = OsStr::new("foo=bar");
1160 /// let bytes = os_str.as_encoded_bytes();
1161 /// if let Some(index) = bytes.iter().position(|b| *b == b'=') {
1162 /// let key = os_str.slice_encoded_bytes(..index);
1163 /// let value = os_str.slice_encoded_bytes(index + 1..);
1164 /// assert_eq!(key, "foo");
1165 /// assert_eq!(value, "bar");
1166 /// }
1167 /// ```
1168 #[unstable(feature = "os_str_slice", issue = "118485")]
1169 pub fn slice_encoded_bytes<R: ops::RangeBounds<usize>>(&self, range: R) -> &Self {
1170 let encoded_bytes = self.as_encoded_bytes();
1171 let Range { start, end } = slice::range(range, ..encoded_bytes.len());
1172
1173 // `check_public_boundary` should panic if the index does not lie on an
1174 // `OsStr` boundary as described above. It's possible to do this in an
1175 // encoding-agnostic way, but details of the internal encoding might
1176 // permit a more efficient implementation.
1177 self.inner.check_public_boundary(start);
1178 self.inner.check_public_boundary(end);
1179
1180 // SAFETY: `slice::range` ensures that `start` and `end` are valid
1181 let slice = unsafe { encoded_bytes.get_unchecked(start..end) };
1182
1183 // SAFETY: `slice` comes from `self` and we validated the boundaries
1184 unsafe { Self::from_encoded_bytes_unchecked(slice) }
1185 }
1186
1187 /// Converts this string to its ASCII lower case equivalent in-place.
1188 ///
1189 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1190 /// but non-ASCII letters are unchanged.
1191 ///
1192 /// To return a new lowercased value without modifying the existing one, use
1193 /// [`OsStr::to_ascii_lowercase`].
1194 ///
1195 /// # Examples
1196 ///
1197 /// ```
1198 /// use std::ffi::OsString;
1199 ///
1200 /// let mut s = OsString::from("GRÜßE, JÜRGEN ❤");
1201 ///
1202 /// s.make_ascii_lowercase();
1203 ///
1204 /// assert_eq!("grÜße, jÜrgen ❤", s);
1205 /// ```
1206 #[stable(feature = "osstring_ascii", since = "1.53.0")]
1207 #[inline]
1208 pub fn make_ascii_lowercase(&mut self) {
1209 self.inner.make_ascii_lowercase()
1210 }
1211
1212 /// Converts this string to its ASCII upper case equivalent in-place.
1213 ///
1214 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1215 /// but non-ASCII letters are unchanged.
1216 ///
1217 /// To return a new uppercased value without modifying the existing one, use
1218 /// [`OsStr::to_ascii_uppercase`].
1219 ///
1220 /// # Examples
1221 ///
1222 /// ```
1223 /// use std::ffi::OsString;
1224 ///
1225 /// let mut s = OsString::from("Grüße, Jürgen ❤");
1226 ///
1227 /// s.make_ascii_uppercase();
1228 ///
1229 /// assert_eq!("GRüßE, JüRGEN ❤", s);
1230 /// ```
1231 #[stable(feature = "osstring_ascii", since = "1.53.0")]
1232 #[inline]
1233 pub fn make_ascii_uppercase(&mut self) {
1234 self.inner.make_ascii_uppercase()
1235 }
1236
1237 /// Returns a copy of this string where each character is mapped to its
1238 /// ASCII lower case equivalent.
1239 ///
1240 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1241 /// but non-ASCII letters are unchanged.
1242 ///
1243 /// To lowercase the value in-place, use [`OsStr::make_ascii_lowercase`].
1244 ///
1245 /// # Examples
1246 ///
1247 /// ```
1248 /// use std::ffi::OsString;
1249 /// let s = OsString::from("Grüße, Jürgen ❤");
1250 ///
1251 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
1252 /// ```
1253 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase`"]
1254 #[stable(feature = "osstring_ascii", since = "1.53.0")]
1255 pub fn to_ascii_lowercase(&self) -> OsString {
1256 OsString::from_inner(self.inner.to_ascii_lowercase())
1257 }
1258
1259 /// Returns a copy of this string where each character is mapped to its
1260 /// ASCII upper case equivalent.
1261 ///
1262 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1263 /// but non-ASCII letters are unchanged.
1264 ///
1265 /// To uppercase the value in-place, use [`OsStr::make_ascii_uppercase`].
1266 ///
1267 /// # Examples
1268 ///
1269 /// ```
1270 /// use std::ffi::OsString;
1271 /// let s = OsString::from("Grüße, Jürgen ❤");
1272 ///
1273 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
1274 /// ```
1275 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase`"]
1276 #[stable(feature = "osstring_ascii", since = "1.53.0")]
1277 pub fn to_ascii_uppercase(&self) -> OsString {
1278 OsString::from_inner(self.inner.to_ascii_uppercase())
1279 }
1280
1281 /// Checks if all characters in this string are within the ASCII range.
1282 ///
1283 /// An empty string returns `true`.
1284 ///
1285 /// # Examples
1286 ///
1287 /// ```
1288 /// use std::ffi::OsString;
1289 ///
1290 /// let ascii = OsString::from("hello!\n");
1291 /// let non_ascii = OsString::from("Grüße, Jürgen ❤");
1292 ///
1293 /// assert!(ascii.is_ascii());
1294 /// assert!(!non_ascii.is_ascii());
1295 /// ```
1296 #[stable(feature = "osstring_ascii", since = "1.53.0")]
1297 #[must_use]
1298 #[inline]
1299 pub fn is_ascii(&self) -> bool {
1300 self.inner.is_ascii()
1301 }
1302
1303 /// Checks that two strings are an ASCII case-insensitive match.
1304 ///
1305 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
1306 /// but without allocating and copying temporaries.
1307 ///
1308 /// # Examples
1309 ///
1310 /// ```
1311 /// use std::ffi::OsString;
1312 ///
1313 /// assert!(OsString::from("Ferris").eq_ignore_ascii_case("FERRIS"));
1314 /// assert!(OsString::from("Ferrös").eq_ignore_ascii_case("FERRöS"));
1315 /// assert!(!OsString::from("Ferrös").eq_ignore_ascii_case("FERRÖS"));
1316 /// ```
1317 #[stable(feature = "osstring_ascii", since = "1.53.0")]
1318 pub fn eq_ignore_ascii_case<S: AsRef<OsStr>>(&self, other: S) -> bool {
1319 self.inner.eq_ignore_ascii_case(&other.as_ref().inner)
1320 }
1321
1322 /// Returns an object that implements [`Display`] for safely printing an
1323 /// [`OsStr`] that may contain non-Unicode data. This may perform lossy
1324 /// conversion, depending on the platform. If you would like an
1325 /// implementation which escapes the [`OsStr`] please use [`Debug`]
1326 /// instead.
1327 ///
1328 /// [`Display`]: fmt::Display
1329 /// [`Debug`]: fmt::Debug
1330 ///
1331 /// # Examples
1332 ///
1333 /// ```
1334 /// use std::ffi::OsStr;
1335 ///
1336 /// let s = OsStr::new("Hello, world!");
1337 /// println!("{}", s.display());
1338 /// ```
1339 #[stable(feature = "os_str_display", since = "1.87.0")]
1340 #[must_use = "this does not display the `OsStr`; \
1341 it returns an object that can be displayed"]
1342 #[inline]
1343 pub fn display(&self) -> Display<'_> {
1344 Display { os_str: self }
1345 }
1346
1347 /// Returns the same string as a string slice `&OsStr`.
1348 ///
1349 /// This method is redundant when used directly on `&OsStr`, but
1350 /// it helps dereferencing other string-like types to string slices,
1351 /// for example references to `Box<OsStr>` or `Arc<OsStr>`.
1352 #[inline]
1353 #[unstable(feature = "str_as_str", issue = "130366")]
1354 pub const fn as_os_str(&self) -> &OsStr {
1355 self
1356 }
1357}
1358
1359#[stable(feature = "box_from_os_str", since = "1.17.0")]
1360impl From<&OsStr> for Box<OsStr> {
1361 /// Copies the string into a newly allocated <code>[Box]<[OsStr]></code>.
1362 #[inline]
1363 fn from(s: &OsStr) -> Box<OsStr> {
1364 Box::clone_from_ref(s)
1365 }
1366}
1367
1368#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
1369impl From<&mut OsStr> for Box<OsStr> {
1370 /// Copies the string into a newly allocated <code>[Box]<[OsStr]></code>.
1371 #[inline]
1372 fn from(s: &mut OsStr) -> Box<OsStr> {
1373 Self::from(&*s)
1374 }
1375}
1376
1377#[stable(feature = "box_from_cow", since = "1.45.0")]
1378impl From<Cow<'_, OsStr>> for Box<OsStr> {
1379 /// Converts a `Cow<'a, OsStr>` into a <code>[Box]<[OsStr]></code>,
1380 /// by copying the contents if they are borrowed.
1381 #[inline]
1382 fn from(cow: Cow<'_, OsStr>) -> Box<OsStr> {
1383 match cow {
1384 Cow::Borrowed(s) => Box::from(s),
1385 Cow::Owned(s) => Box::from(s),
1386 }
1387 }
1388}
1389
1390#[stable(feature = "os_string_from_box", since = "1.18.0")]
1391impl From<Box<OsStr>> for OsString {
1392 /// Converts a <code>[Box]<[OsStr]></code> into an [`OsString`] without copying or
1393 /// allocating.
1394 #[inline]
1395 fn from(boxed: Box<OsStr>) -> OsString {
1396 boxed.into_os_string()
1397 }
1398}
1399
1400#[stable(feature = "box_from_os_string", since = "1.20.0")]
1401impl From<OsString> for Box<OsStr> {
1402 /// Converts an [`OsString`] into a <code>[Box]<[OsStr]></code> without copying or allocating.
1403 #[inline]
1404 fn from(s: OsString) -> Box<OsStr> {
1405 s.into_boxed_os_str()
1406 }
1407}
1408
1409#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1410impl<A: Allocator + Clone> Clone for Box<OsStr, A> {
1411 #[inline]
1412 fn clone(&self) -> Self {
1413 Box::clone_from_ref_in(&**self, Self::allocator(self).clone())
1414 }
1415}
1416
1417#[unstable(feature = "clone_to_uninit", issue = "126799")]
1418unsafe impl CloneToUninit for OsStr {
1419 #[inline]
1420 #[cfg_attr(debug_assertions, track_caller)]
1421 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
1422 // SAFETY: we're just a transparent wrapper around a platform-specific Slice
1423 unsafe { self.inner.clone_to_uninit(dst) }
1424 }
1425}
1426
1427#[stable(feature = "shared_from_slice2", since = "1.24.0")]
1428impl From<OsString> for Arc<OsStr> {
1429 /// Converts an [`OsString`] into an <code>[Arc]<[OsStr]></code> by moving the [`OsString`]
1430 /// data into a new [`Arc`] buffer.
1431 #[inline]
1432 fn from(s: OsString) -> Arc<OsStr> {
1433 let arc = s.inner.into_arc();
1434 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1435 }
1436}
1437
1438#[stable(feature = "shared_from_slice2", since = "1.24.0")]
1439impl From<&OsStr> for Arc<OsStr> {
1440 /// Copies the string into a newly allocated <code>[Arc]<[OsStr]></code>.
1441 #[inline]
1442 fn from(s: &OsStr) -> Arc<OsStr> {
1443 let arc = s.inner.into_arc();
1444 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
1445 }
1446}
1447
1448#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
1449impl From<&mut OsStr> for Arc<OsStr> {
1450 /// Copies the string into a newly allocated <code>[Arc]<[OsStr]></code>.
1451 #[inline]
1452 fn from(s: &mut OsStr) -> Arc<OsStr> {
1453 Arc::from(&*s)
1454 }
1455}
1456
1457#[stable(feature = "shared_from_slice2", since = "1.24.0")]
1458impl From<OsString> for Rc<OsStr> {
1459 /// Converts an [`OsString`] into an <code>[Rc]<[OsStr]></code> by moving the [`OsString`]
1460 /// data into a new [`Rc`] buffer.
1461 #[inline]
1462 fn from(s: OsString) -> Rc<OsStr> {
1463 let rc = s.inner.into_rc();
1464 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1465 }
1466}
1467
1468#[stable(feature = "shared_from_slice2", since = "1.24.0")]
1469impl From<&OsStr> for Rc<OsStr> {
1470 /// Copies the string into a newly allocated <code>[Rc]<[OsStr]></code>.
1471 #[inline]
1472 fn from(s: &OsStr) -> Rc<OsStr> {
1473 let rc = s.inner.into_rc();
1474 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
1475 }
1476}
1477
1478#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
1479impl From<&mut OsStr> for Rc<OsStr> {
1480 /// Copies the string into a newly allocated <code>[Rc]<[OsStr]></code>.
1481 #[inline]
1482 fn from(s: &mut OsStr) -> Rc<OsStr> {
1483 Rc::from(&*s)
1484 }
1485}
1486
1487#[stable(feature = "cow_from_osstr", since = "1.28.0")]
1488impl<'a> From<OsString> for Cow<'a, OsStr> {
1489 /// Moves the string into a [`Cow::Owned`].
1490 #[inline]
1491 fn from(s: OsString) -> Cow<'a, OsStr> {
1492 Cow::Owned(s)
1493 }
1494}
1495
1496#[stable(feature = "cow_from_osstr", since = "1.28.0")]
1497impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
1498 /// Converts the string reference into a [`Cow::Borrowed`].
1499 #[inline]
1500 fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
1501 Cow::Borrowed(s)
1502 }
1503}
1504
1505#[stable(feature = "cow_from_osstr", since = "1.28.0")]
1506impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
1507 /// Converts the string reference into a [`Cow::Borrowed`].
1508 #[inline]
1509 fn from(s: &'a OsString) -> Cow<'a, OsStr> {
1510 Cow::Borrowed(s.as_os_str())
1511 }
1512}
1513
1514#[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
1515impl<'a> From<Cow<'a, OsStr>> for OsString {
1516 /// Converts a `Cow<'a, OsStr>` into an [`OsString`],
1517 /// by copying the contents if they are borrowed.
1518 #[inline]
1519 fn from(s: Cow<'a, OsStr>) -> Self {
1520 s.into_owned()
1521 }
1522}
1523
1524#[stable(feature = "str_tryfrom_osstr_impl", since = "1.72.0")]
1525impl<'a> TryFrom<&'a OsStr> for &'a str {
1526 type Error = crate::str::Utf8Error;
1527
1528 /// Tries to convert an `&OsStr` to a `&str`.
1529 ///
1530 /// ```
1531 /// use std::ffi::OsStr;
1532 ///
1533 /// let os_str = OsStr::new("foo");
1534 /// let as_str = <&str>::try_from(os_str).unwrap();
1535 /// assert_eq!(as_str, "foo");
1536 /// ```
1537 fn try_from(value: &'a OsStr) -> Result<Self, Self::Error> {
1538 value.inner.to_str()
1539 }
1540}
1541
1542#[stable(feature = "box_default_extra", since = "1.17.0")]
1543impl Default for Box<OsStr> {
1544 #[inline]
1545 fn default() -> Box<OsStr> {
1546 let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
1547 unsafe { Box::from_raw(rw) }
1548 }
1549}
1550
1551#[stable(feature = "osstring_default", since = "1.9.0")]
1552impl Default for &OsStr {
1553 /// Creates an empty `OsStr`.
1554 #[inline]
1555 fn default() -> Self {
1556 OsStr::new("")
1557 }
1558}
1559
1560#[stable(feature = "rust1", since = "1.0.0")]
1561impl PartialEq for OsStr {
1562 #[inline]
1563 fn eq(&self, other: &OsStr) -> bool {
1564 self.as_encoded_bytes().eq(other.as_encoded_bytes())
1565 }
1566}
1567
1568#[stable(feature = "rust1", since = "1.0.0")]
1569impl PartialEq<str> for OsStr {
1570 #[inline]
1571 fn eq(&self, other: &str) -> bool {
1572 *self == *OsStr::new(other)
1573 }
1574}
1575
1576#[stable(feature = "rust1", since = "1.0.0")]
1577impl PartialEq<OsStr> for str {
1578 #[inline]
1579 fn eq(&self, other: &OsStr) -> bool {
1580 *other == *OsStr::new(self)
1581 }
1582}
1583
1584#[stable(feature = "rust1", since = "1.0.0")]
1585impl Eq for OsStr {}
1586
1587#[stable(feature = "rust1", since = "1.0.0")]
1588impl PartialOrd for OsStr {
1589 #[inline]
1590 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1591 self.as_encoded_bytes().partial_cmp(other.as_encoded_bytes())
1592 }
1593 #[inline]
1594 fn lt(&self, other: &OsStr) -> bool {
1595 self.as_encoded_bytes().lt(other.as_encoded_bytes())
1596 }
1597 #[inline]
1598 fn le(&self, other: &OsStr) -> bool {
1599 self.as_encoded_bytes().le(other.as_encoded_bytes())
1600 }
1601 #[inline]
1602 fn gt(&self, other: &OsStr) -> bool {
1603 self.as_encoded_bytes().gt(other.as_encoded_bytes())
1604 }
1605 #[inline]
1606 fn ge(&self, other: &OsStr) -> bool {
1607 self.as_encoded_bytes().ge(other.as_encoded_bytes())
1608 }
1609}
1610
1611#[stable(feature = "rust1", since = "1.0.0")]
1612impl PartialOrd<str> for OsStr {
1613 #[inline]
1614 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1615 self.partial_cmp(OsStr::new(other))
1616 }
1617}
1618
1619// FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1620// have more flexible coherence rules.
1621
1622#[stable(feature = "rust1", since = "1.0.0")]
1623impl Ord for OsStr {
1624 #[inline]
1625 fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1626 self.as_encoded_bytes().cmp(other.as_encoded_bytes())
1627 }
1628}
1629
1630macro_rules! impl_cmp {
1631 ($lhs:ty, $rhs: ty) => {
1632 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1633 impl PartialEq<$rhs> for $lhs {
1634 #[inline]
1635 fn eq(&self, other: &$rhs) -> bool {
1636 <OsStr as PartialEq>::eq(self, other)
1637 }
1638 }
1639
1640 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1641 impl PartialEq<$lhs> for $rhs {
1642 #[inline]
1643 fn eq(&self, other: &$lhs) -> bool {
1644 <OsStr as PartialEq>::eq(self, other)
1645 }
1646 }
1647
1648 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1649 impl PartialOrd<$rhs> for $lhs {
1650 #[inline]
1651 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1652 <OsStr as PartialOrd>::partial_cmp(self, other)
1653 }
1654 }
1655
1656 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1657 impl PartialOrd<$lhs> for $rhs {
1658 #[inline]
1659 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1660 <OsStr as PartialOrd>::partial_cmp(self, other)
1661 }
1662 }
1663 };
1664}
1665
1666impl_cmp!(OsString, OsStr);
1667impl_cmp!(OsString, &OsStr);
1668impl_cmp!(Cow<'_, OsStr>, OsStr);
1669impl_cmp!(Cow<'_, OsStr>, &OsStr);
1670impl_cmp!(Cow<'_, OsStr>, OsString);
1671
1672#[stable(feature = "rust1", since = "1.0.0")]
1673impl Hash for OsStr {
1674 #[inline]
1675 fn hash<H: Hasher>(&self, state: &mut H) {
1676 self.as_encoded_bytes().hash(state)
1677 }
1678}
1679
1680#[stable(feature = "rust1", since = "1.0.0")]
1681impl fmt::Debug for OsStr {
1682 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1683 fmt::Debug::fmt(&self.inner, formatter)
1684 }
1685}
1686
1687/// Helper struct for safely printing an [`OsStr`] with [`format!`] and `{}`.
1688///
1689/// An [`OsStr`] might contain non-Unicode data. This `struct` implements the
1690/// [`Display`] trait in a way that mitigates that. It is created by the
1691/// [`display`](OsStr::display) method on [`OsStr`]. This may perform lossy
1692/// conversion, depending on the platform. If you would like an implementation
1693/// which escapes the [`OsStr`] please use [`Debug`] instead.
1694///
1695/// # Examples
1696///
1697/// ```
1698/// use std::ffi::OsStr;
1699///
1700/// let s = OsStr::new("Hello, world!");
1701/// println!("{}", s.display());
1702/// ```
1703///
1704/// [`Display`]: fmt::Display
1705/// [`format!`]: crate::format
1706#[stable(feature = "os_str_display", since = "1.87.0")]
1707pub struct Display<'a> {
1708 os_str: &'a OsStr,
1709}
1710
1711#[stable(feature = "os_str_display", since = "1.87.0")]
1712impl fmt::Debug for Display<'_> {
1713 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1714 fmt::Debug::fmt(&self.os_str, f)
1715 }
1716}
1717
1718#[stable(feature = "os_str_display", since = "1.87.0")]
1719impl fmt::Display for Display<'_> {
1720 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1721 fmt::Display::fmt(&self.os_str.inner, f)
1722 }
1723}
1724
1725#[unstable(feature = "slice_concat_ext", issue = "none", reason = "implementation detail")]
1726impl<S: Borrow<OsStr>> alloc::slice::Join<&OsStr> for [S] {
1727 type Output = OsString;
1728
1729 fn join(slice: &Self, sep: &OsStr) -> OsString {
1730 let Some((first, suffix)) = slice.split_first() else {
1731 return OsString::new();
1732 };
1733 let first_owned = first.borrow().to_owned();
1734 suffix.iter().fold(first_owned, |mut a, b| {
1735 a.push(sep);
1736 a.push(b.borrow());
1737 a
1738 })
1739 }
1740}
1741
1742#[stable(feature = "rust1", since = "1.0.0")]
1743impl Borrow<OsStr> for OsString {
1744 #[inline]
1745 fn borrow(&self) -> &OsStr {
1746 &self[..]
1747 }
1748}
1749
1750#[stable(feature = "rust1", since = "1.0.0")]
1751impl ToOwned for OsStr {
1752 type Owned = OsString;
1753 #[inline]
1754 fn to_owned(&self) -> OsString {
1755 self.to_os_string()
1756 }
1757 #[inline]
1758 fn clone_into(&self, target: &mut OsString) {
1759 self.inner.clone_into(&mut target.inner)
1760 }
1761}
1762
1763#[stable(feature = "rust1", since = "1.0.0")]
1764#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1765const impl AsRef<OsStr> for OsStr {
1766 #[inline]
1767 fn as_ref(&self) -> &OsStr {
1768 self
1769 }
1770}
1771
1772#[stable(feature = "rust1", since = "1.0.0")]
1773impl AsRef<OsStr> for OsString {
1774 #[inline]
1775 fn as_ref(&self) -> &OsStr {
1776 self
1777 }
1778}
1779
1780#[stable(feature = "rust1", since = "1.0.0")]
1781impl AsRef<OsStr> for str {
1782 #[inline]
1783 fn as_ref(&self) -> &OsStr {
1784 OsStr::from_inner(Slice::from_str(self))
1785 }
1786}
1787
1788#[stable(feature = "rust1", since = "1.0.0")]
1789impl AsRef<OsStr> for String {
1790 #[inline]
1791 fn as_ref(&self) -> &OsStr {
1792 (**self).as_ref()
1793 }
1794}
1795
1796impl FromInner<Buf> for OsString {
1797 #[inline]
1798 fn from_inner(buf: Buf) -> OsString {
1799 OsString { inner: buf }
1800 }
1801}
1802
1803impl IntoInner<Buf> for OsString {
1804 #[inline]
1805 fn into_inner(self) -> Buf {
1806 self.inner
1807 }
1808}
1809
1810impl AsInner<Slice> for OsStr {
1811 #[inline]
1812 fn as_inner(&self) -> &Slice {
1813 &self.inner
1814 }
1815}
1816
1817#[stable(feature = "osstring_from_str", since = "1.45.0")]
1818impl FromStr for OsString {
1819 type Err = !;
1820
1821 #[inline]
1822 fn from_str(s: &str) -> Result<Self, !> {
1823 Ok(OsString::from(s))
1824 }
1825}
1826
1827#[stable(feature = "osstring_extend", since = "1.52.0")]
1828impl Extend<OsString> for OsString {
1829 #[inline]
1830 fn extend<I: IntoIterator<Item = OsString>>(&mut self, iter: I) {
1831 for s in iter {
1832 self.push(&s);
1833 }
1834 }
1835}
1836
1837#[stable(feature = "osstring_extend", since = "1.52.0")]
1838impl<'a> Extend<&'a OsStr> for OsString {
1839 #[inline]
1840 fn extend<I: IntoIterator<Item = &'a OsStr>>(&mut self, iter: I) {
1841 for s in iter {
1842 self.push(s);
1843 }
1844 }
1845}
1846
1847#[stable(feature = "osstring_extend", since = "1.52.0")]
1848impl<'a> Extend<Cow<'a, OsStr>> for OsString {
1849 #[inline]
1850 fn extend<I: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: I) {
1851 for s in iter {
1852 self.push(&s);
1853 }
1854 }
1855}
1856
1857#[stable(feature = "osstring_extend", since = "1.52.0")]
1858impl FromIterator<OsString> for OsString {
1859 #[inline]
1860 fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1861 let mut iterator = iter.into_iter();
1862
1863 // Because we're iterating over `OsString`s, we can avoid at least
1864 // one allocation by getting the first string from the iterator
1865 // and appending to it all the subsequent strings.
1866 match iterator.next() {
1867 None => OsString::new(),
1868 Some(mut buf) => {
1869 buf.extend(iterator);
1870 buf
1871 }
1872 }
1873 }
1874}
1875
1876#[stable(feature = "osstring_extend", since = "1.52.0")]
1877impl<'a> FromIterator<&'a OsStr> for OsString {
1878 #[inline]
1879 fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self {
1880 let mut buf = Self::new();
1881 for s in iter {
1882 buf.push(s);
1883 }
1884 buf
1885 }
1886}
1887
1888#[stable(feature = "osstring_extend", since = "1.52.0")]
1889impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
1890 #[inline]
1891 fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
1892 let mut iterator = iter.into_iter();
1893
1894 // Because we're iterating over `OsString`s, we can avoid at least
1895 // one allocation by getting the first owned string from the iterator
1896 // and appending to it all the subsequent strings.
1897 match iterator.next() {
1898 None => OsString::new(),
1899 Some(Cow::Owned(mut buf)) => {
1900 buf.extend(iterator);
1901 buf
1902 }
1903 Some(Cow::Borrowed(buf)) => {
1904 let mut buf = OsString::from(buf);
1905 buf.extend(iterator);
1906 buf
1907 }
1908 }
1909 }
1910}