]> git.proxmox.com Git - rustc.git/blob - library/std/src/ffi/os_str.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / library / std / src / ffi / os_str.rs
1 #[cfg(test)]
2 mod tests;
3
4 use crate::borrow::{Borrow, Cow};
5 use crate::cmp;
6 use crate::fmt;
7 use crate::hash::{Hash, Hasher};
8 use crate::iter::{Extend, FromIterator};
9 use crate::ops;
10 use crate::rc::Rc;
11 use crate::str::FromStr;
12 use crate::sync::Arc;
13
14 use crate::sys::os_str::{Buf, Slice};
15 use crate::sys_common::{AsInner, FromInner, IntoInner};
16
17 /// A type that can represent owned, mutable platform-native strings, but is
18 /// cheaply inter-convertible with Rust strings.
19 ///
20 /// The need for this type arises from the fact that:
21 ///
22 /// * On Unix systems, strings are often arbitrary sequences of non-zero
23 /// bytes, in many cases interpreted as UTF-8.
24 ///
25 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
26 /// values, interpreted as UTF-16 when it is valid to do so.
27 ///
28 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
29 ///
30 /// `OsString` and [`OsStr`] bridge this gap by simultaneously representing Rust
31 /// and platform-native string values, and in particular allowing a Rust string
32 /// to be converted into an "OS" string with no cost if possible. A consequence
33 /// of this is that `OsString` instances are *not* `NUL` terminated; in order
34 /// to pass to e.g., Unix system call, you should create a [`CStr`].
35 ///
36 /// `OsString` is to [`&OsStr`] as [`String`] is to [`&str`]: the former
37 /// in each pair are owned strings; the latter are borrowed
38 /// references.
39 ///
40 /// Note, `OsString` and [`OsStr`] internally do not necessarily hold strings in
41 /// the form native to the platform; While on Unix, strings are stored as a
42 /// sequence of 8-bit values, on Windows, where strings are 16-bit value based
43 /// as just discussed, strings are also actually stored as a sequence of 8-bit
44 /// values, encoded in a less-strict variant of UTF-8. This is useful to
45 /// understand when handling capacity and length values.
46 ///
47 /// # Creating an `OsString`
48 ///
49 /// **From a Rust string**: `OsString` implements
50 /// [`From`]`<`[`String`]`>`, so you can use `my_string.from` to
51 /// create an `OsString` from a normal Rust string.
52 ///
53 /// **From slices:** Just like you can start with an empty Rust
54 /// [`String`] and then [`String::push_str`] `&str`
55 /// sub-string slices into it, you can create an empty `OsString` with
56 /// the [`OsString::new`] method and then push string slices into it with the
57 /// [`OsString::push`] method.
58 ///
59 /// # Extracting a borrowed reference to the whole OS string
60 ///
61 /// You can use the [`OsString::as_os_str`] method to get an `&`[`OsStr`] from
62 /// an `OsString`; this is effectively a borrowed reference to the
63 /// whole string.
64 ///
65 /// # Conversions
66 ///
67 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
68 /// the traits which `OsString` implements for [conversions] from/to native representations.
69 ///
70 /// [`&OsStr`]: OsStr
71 /// [`&str`]: str
72 /// [`CStr`]: crate::ffi::CStr
73 /// [conversions]: super#conversions
74 #[derive(Clone)]
75 #[cfg_attr(not(test), rustc_diagnostic_item = "OsString")]
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct OsString {
78 inner: Buf,
79 }
80
81 /// Allows extension traits within `std`.
82 #[unstable(feature = "sealed", issue = "none")]
83 impl crate::sealed::Sealed for OsString {}
84
85 /// Borrowed reference to an OS string (see [`OsString`]).
86 ///
87 /// This type represents a borrowed reference to a string in the operating system's preferred
88 /// representation.
89 ///
90 /// `&OsStr` is to [`OsString`] as [`&str`] is to [`String`]: the former in each pair are borrowed
91 /// references; the latter are owned strings.
92 ///
93 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
94 /// the traits which `OsStr` implements for [conversions] from/to native representations.
95 ///
96 /// [`&str`]: str
97 /// [conversions]: super#conversions
98 #[cfg_attr(not(test), rustc_diagnostic_item = "OsStr")]
99 #[stable(feature = "rust1", since = "1.0.0")]
100 // FIXME:
101 // `OsStr::from_inner` current implementation relies
102 // on `OsStr` being layout-compatible with `Slice`.
103 // When attribute privacy is implemented, `OsStr` should be annotated as `#[repr(transparent)]`.
104 // Anyway, `OsStr` representation and layout are considered implementation details, are
105 // not documented and must not be relied upon.
106 pub struct OsStr {
107 inner: Slice,
108 }
109
110 /// Allows extension traits within `std`.
111 #[unstable(feature = "sealed", issue = "none")]
112 impl crate::sealed::Sealed for OsStr {}
113
114 impl OsString {
115 /// Constructs a new empty `OsString`.
116 ///
117 /// # Examples
118 ///
119 /// ```
120 /// use std::ffi::OsString;
121 ///
122 /// let os_string = OsString::new();
123 /// ```
124 #[stable(feature = "rust1", since = "1.0.0")]
125 #[inline]
126 pub fn new() -> OsString {
127 OsString { inner: Buf::from_string(String::new()) }
128 }
129
130 /// Converts to an [`OsStr`] slice.
131 ///
132 /// # Examples
133 ///
134 /// ```
135 /// use std::ffi::{OsString, OsStr};
136 ///
137 /// let os_string = OsString::from("foo");
138 /// let os_str = OsStr::new("foo");
139 /// assert_eq!(os_string.as_os_str(), os_str);
140 /// ```
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[inline]
143 pub fn as_os_str(&self) -> &OsStr {
144 self
145 }
146
147 /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
148 ///
149 /// On failure, ownership of the original `OsString` is returned.
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// use std::ffi::OsString;
155 ///
156 /// let os_string = OsString::from("foo");
157 /// let string = os_string.into_string();
158 /// assert_eq!(string, Ok(String::from("foo")));
159 /// ```
160 #[stable(feature = "rust1", since = "1.0.0")]
161 #[inline]
162 pub fn into_string(self) -> Result<String, OsString> {
163 self.inner.into_string().map_err(|buf| OsString { inner: buf })
164 }
165
166 /// Extends the string with the given [`&OsStr`] slice.
167 ///
168 /// [`&OsStr`]: OsStr
169 ///
170 /// # Examples
171 ///
172 /// ```
173 /// use std::ffi::OsString;
174 ///
175 /// let mut os_string = OsString::from("foo");
176 /// os_string.push("bar");
177 /// assert_eq!(&os_string, "foobar");
178 /// ```
179 #[stable(feature = "rust1", since = "1.0.0")]
180 #[inline]
181 pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
182 self.inner.push_slice(&s.as_ref().inner)
183 }
184
185 /// Creates a new `OsString` with the given capacity.
186 ///
187 /// The string will be able to hold exactly `capacity` length units of other
188 /// OS strings without reallocating. If `capacity` is 0, the string will not
189 /// allocate.
190 ///
191 /// See main `OsString` documentation information about encoding.
192 ///
193 /// # Examples
194 ///
195 /// ```
196 /// use std::ffi::OsString;
197 ///
198 /// let mut os_string = OsString::with_capacity(10);
199 /// let capacity = os_string.capacity();
200 ///
201 /// // This push is done without reallocating
202 /// os_string.push("foo");
203 ///
204 /// assert_eq!(capacity, os_string.capacity());
205 /// ```
206 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
207 #[inline]
208 pub fn with_capacity(capacity: usize) -> OsString {
209 OsString { inner: Buf::with_capacity(capacity) }
210 }
211
212 /// Truncates the `OsString` to zero length.
213 ///
214 /// # Examples
215 ///
216 /// ```
217 /// use std::ffi::OsString;
218 ///
219 /// let mut os_string = OsString::from("foo");
220 /// assert_eq!(&os_string, "foo");
221 ///
222 /// os_string.clear();
223 /// assert_eq!(&os_string, "");
224 /// ```
225 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
226 #[inline]
227 pub fn clear(&mut self) {
228 self.inner.clear()
229 }
230
231 /// Returns the capacity this `OsString` can hold without reallocating.
232 ///
233 /// See `OsString` introduction for information about encoding.
234 ///
235 /// # Examples
236 ///
237 /// ```
238 /// use std::ffi::OsString;
239 ///
240 /// let os_string = OsString::with_capacity(10);
241 /// assert!(os_string.capacity() >= 10);
242 /// ```
243 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
244 #[inline]
245 pub fn capacity(&self) -> usize {
246 self.inner.capacity()
247 }
248
249 /// Reserves capacity for at least `additional` more capacity to be inserted
250 /// in the given `OsString`.
251 ///
252 /// The collection may reserve more space to avoid frequent reallocations.
253 ///
254 /// # Examples
255 ///
256 /// ```
257 /// use std::ffi::OsString;
258 ///
259 /// let mut s = OsString::new();
260 /// s.reserve(10);
261 /// assert!(s.capacity() >= 10);
262 /// ```
263 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
264 #[inline]
265 pub fn reserve(&mut self, additional: usize) {
266 self.inner.reserve(additional)
267 }
268
269 /// Reserves the minimum capacity for exactly `additional` more capacity to
270 /// be inserted in the given `OsString`. Does nothing if the capacity is
271 /// already sufficient.
272 ///
273 /// Note that the allocator may give the collection more space than it
274 /// requests. Therefore, capacity can not be relied upon to be precisely
275 /// minimal. Prefer reserve if future insertions are expected.
276 ///
277 /// # Examples
278 ///
279 /// ```
280 /// use std::ffi::OsString;
281 ///
282 /// let mut s = OsString::new();
283 /// s.reserve_exact(10);
284 /// assert!(s.capacity() >= 10);
285 /// ```
286 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
287 #[inline]
288 pub fn reserve_exact(&mut self, additional: usize) {
289 self.inner.reserve_exact(additional)
290 }
291
292 /// Shrinks the capacity of the `OsString` to match its length.
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// use std::ffi::OsString;
298 ///
299 /// let mut s = OsString::from("foo");
300 ///
301 /// s.reserve(100);
302 /// assert!(s.capacity() >= 100);
303 ///
304 /// s.shrink_to_fit();
305 /// assert_eq!(3, s.capacity());
306 /// ```
307 #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
308 #[inline]
309 pub fn shrink_to_fit(&mut self) {
310 self.inner.shrink_to_fit()
311 }
312
313 /// Shrinks the capacity of the `OsString` with a lower bound.
314 ///
315 /// The capacity will remain at least as large as both the length
316 /// and the supplied value.
317 ///
318 /// If the current capacity is less than the lower limit, this is a no-op.
319 ///
320 /// # Examples
321 ///
322 /// ```
323 /// #![feature(shrink_to)]
324 /// use std::ffi::OsString;
325 ///
326 /// let mut s = OsString::from("foo");
327 ///
328 /// s.reserve(100);
329 /// assert!(s.capacity() >= 100);
330 ///
331 /// s.shrink_to(10);
332 /// assert!(s.capacity() >= 10);
333 /// s.shrink_to(0);
334 /// assert!(s.capacity() >= 3);
335 /// ```
336 #[inline]
337 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
338 pub fn shrink_to(&mut self, min_capacity: usize) {
339 self.inner.shrink_to(min_capacity)
340 }
341
342 /// Converts this `OsString` into a boxed [`OsStr`].
343 ///
344 /// # Examples
345 ///
346 /// ```
347 /// use std::ffi::{OsString, OsStr};
348 ///
349 /// let s = OsString::from("hello");
350 ///
351 /// let b: Box<OsStr> = s.into_boxed_os_str();
352 /// ```
353 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
354 pub fn into_boxed_os_str(self) -> Box<OsStr> {
355 let rw = Box::into_raw(self.inner.into_box()) as *mut OsStr;
356 unsafe { Box::from_raw(rw) }
357 }
358 }
359
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl From<String> for OsString {
362 /// Converts a [`String`] into a [`OsString`].
363 ///
364 /// The conversion copies the data, and includes an allocation on the heap.
365 #[inline]
366 fn from(s: String) -> OsString {
367 OsString { inner: Buf::from_string(s) }
368 }
369 }
370
371 #[stable(feature = "rust1", since = "1.0.0")]
372 impl<T: ?Sized + AsRef<OsStr>> From<&T> for OsString {
373 fn from(s: &T) -> OsString {
374 s.as_ref().to_os_string()
375 }
376 }
377
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl ops::Index<ops::RangeFull> for OsString {
380 type Output = OsStr;
381
382 #[inline]
383 fn index(&self, _index: ops::RangeFull) -> &OsStr {
384 OsStr::from_inner(self.inner.as_slice())
385 }
386 }
387
388 #[stable(feature = "mut_osstr", since = "1.44.0")]
389 impl ops::IndexMut<ops::RangeFull> for OsString {
390 #[inline]
391 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut OsStr {
392 OsStr::from_inner_mut(self.inner.as_mut_slice())
393 }
394 }
395
396 #[stable(feature = "rust1", since = "1.0.0")]
397 impl ops::Deref for OsString {
398 type Target = OsStr;
399
400 #[inline]
401 fn deref(&self) -> &OsStr {
402 &self[..]
403 }
404 }
405
406 #[stable(feature = "mut_osstr", since = "1.44.0")]
407 impl ops::DerefMut for OsString {
408 #[inline]
409 fn deref_mut(&mut self) -> &mut OsStr {
410 &mut self[..]
411 }
412 }
413
414 #[stable(feature = "osstring_default", since = "1.9.0")]
415 impl Default for OsString {
416 /// Constructs an empty `OsString`.
417 #[inline]
418 fn default() -> OsString {
419 OsString::new()
420 }
421 }
422
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl fmt::Debug for OsString {
425 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
426 fmt::Debug::fmt(&**self, formatter)
427 }
428 }
429
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl PartialEq for OsString {
432 #[inline]
433 fn eq(&self, other: &OsString) -> bool {
434 &**self == &**other
435 }
436 }
437
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl PartialEq<str> for OsString {
440 #[inline]
441 fn eq(&self, other: &str) -> bool {
442 &**self == other
443 }
444 }
445
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl PartialEq<OsString> for str {
448 #[inline]
449 fn eq(&self, other: &OsString) -> bool {
450 &**other == self
451 }
452 }
453
454 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
455 impl PartialEq<&str> for OsString {
456 #[inline]
457 fn eq(&self, other: &&str) -> bool {
458 **self == **other
459 }
460 }
461
462 #[stable(feature = "os_str_str_ref_eq", since = "1.29.0")]
463 impl<'a> PartialEq<OsString> for &'a str {
464 #[inline]
465 fn eq(&self, other: &OsString) -> bool {
466 **other == **self
467 }
468 }
469
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl Eq for OsString {}
472
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl PartialOrd for OsString {
475 #[inline]
476 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
477 (&**self).partial_cmp(&**other)
478 }
479 #[inline]
480 fn lt(&self, other: &OsString) -> bool {
481 &**self < &**other
482 }
483 #[inline]
484 fn le(&self, other: &OsString) -> bool {
485 &**self <= &**other
486 }
487 #[inline]
488 fn gt(&self, other: &OsString) -> bool {
489 &**self > &**other
490 }
491 #[inline]
492 fn ge(&self, other: &OsString) -> bool {
493 &**self >= &**other
494 }
495 }
496
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl PartialOrd<str> for OsString {
499 #[inline]
500 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
501 (&**self).partial_cmp(other)
502 }
503 }
504
505 #[stable(feature = "rust1", since = "1.0.0")]
506 impl Ord for OsString {
507 #[inline]
508 fn cmp(&self, other: &OsString) -> cmp::Ordering {
509 (&**self).cmp(&**other)
510 }
511 }
512
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl Hash for OsString {
515 #[inline]
516 fn hash<H: Hasher>(&self, state: &mut H) {
517 (&**self).hash(state)
518 }
519 }
520
521 impl OsStr {
522 /// Coerces into an `OsStr` slice.
523 ///
524 /// # Examples
525 ///
526 /// ```
527 /// use std::ffi::OsStr;
528 ///
529 /// let os_str = OsStr::new("foo");
530 /// ```
531 #[inline]
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
534 s.as_ref()
535 }
536
537 #[inline]
538 fn from_inner(inner: &Slice) -> &OsStr {
539 // SAFETY: OsStr is just a wrapper of Slice,
540 // therefore converting &Slice to &OsStr is safe.
541 unsafe { &*(inner as *const Slice as *const OsStr) }
542 }
543
544 #[inline]
545 fn from_inner_mut(inner: &mut Slice) -> &mut OsStr {
546 // SAFETY: OsStr is just a wrapper of Slice,
547 // therefore converting &mut Slice to &mut OsStr is safe.
548 // Any method that mutates OsStr must be careful not to
549 // break platform-specific encoding, in particular Wtf8 on Windows.
550 unsafe { &mut *(inner as *mut Slice as *mut OsStr) }
551 }
552
553 /// Yields a [`&str`] slice if the `OsStr` is valid Unicode.
554 ///
555 /// This conversion may entail doing a check for UTF-8 validity.
556 ///
557 /// [`&str`]: str
558 ///
559 /// # Examples
560 ///
561 /// ```
562 /// use std::ffi::OsStr;
563 ///
564 /// let os_str = OsStr::new("foo");
565 /// assert_eq!(os_str.to_str(), Some("foo"));
566 /// ```
567 #[stable(feature = "rust1", since = "1.0.0")]
568 #[inline]
569 pub fn to_str(&self) -> Option<&str> {
570 self.inner.to_str()
571 }
572
573 /// Converts an `OsStr` to a [`Cow`]`<`[`str`]`>`.
574 ///
575 /// Any non-Unicode sequences are replaced with
576 /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
577 ///
578 /// [U+FFFD]: crate::char::REPLACEMENT_CHARACTER
579 ///
580 /// # Examples
581 ///
582 /// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
583 ///
584 /// ```
585 /// // Note, due to differences in how Unix and Windows represent strings,
586 /// // we are forced to complicate this example, setting up example `OsStr`s
587 /// // with different source data and via different platform extensions.
588 /// // Understand that in reality you could end up with such example invalid
589 /// // sequences simply through collecting user command line arguments, for
590 /// // example.
591 ///
592 /// #[cfg(any(unix, target_os = "redox"))] {
593 /// use std::ffi::OsStr;
594 /// use std::os::unix::ffi::OsStrExt;
595 ///
596 /// // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
597 /// // respectively. The value 0x80 is a lone continuation byte, invalid
598 /// // in a UTF-8 sequence.
599 /// let source = [0x66, 0x6f, 0x80, 0x6f];
600 /// let os_str = OsStr::from_bytes(&source[..]);
601 ///
602 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
603 /// }
604 /// #[cfg(windows)] {
605 /// use std::ffi::OsString;
606 /// use std::os::windows::prelude::*;
607 ///
608 /// // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
609 /// // respectively. The value 0xD800 is a lone surrogate half, invalid
610 /// // in a UTF-16 sequence.
611 /// let source = [0x0066, 0x006f, 0xD800, 0x006f];
612 /// let os_string = OsString::from_wide(&source[..]);
613 /// let os_str = os_string.as_os_str();
614 ///
615 /// assert_eq!(os_str.to_string_lossy(), "fo�o");
616 /// }
617 /// ```
618 #[stable(feature = "rust1", since = "1.0.0")]
619 #[inline]
620 pub fn to_string_lossy(&self) -> Cow<'_, str> {
621 self.inner.to_string_lossy()
622 }
623
624 /// Copies the slice into an owned [`OsString`].
625 ///
626 /// # Examples
627 ///
628 /// ```
629 /// use std::ffi::{OsStr, OsString};
630 ///
631 /// let os_str = OsStr::new("foo");
632 /// let os_string = os_str.to_os_string();
633 /// assert_eq!(os_string, OsString::from("foo"));
634 /// ```
635 #[stable(feature = "rust1", since = "1.0.0")]
636 #[inline]
637 pub fn to_os_string(&self) -> OsString {
638 OsString { inner: self.inner.to_owned() }
639 }
640
641 /// Checks whether the `OsStr` is empty.
642 ///
643 /// # Examples
644 ///
645 /// ```
646 /// use std::ffi::OsStr;
647 ///
648 /// let os_str = OsStr::new("");
649 /// assert!(os_str.is_empty());
650 ///
651 /// let os_str = OsStr::new("foo");
652 /// assert!(!os_str.is_empty());
653 /// ```
654 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
655 #[inline]
656 pub fn is_empty(&self) -> bool {
657 self.inner.inner.is_empty()
658 }
659
660 /// Returns the length of this `OsStr`.
661 ///
662 /// Note that this does **not** return the number of bytes in the string in
663 /// OS string form.
664 ///
665 /// The length returned is that of the underlying storage used by `OsStr`.
666 /// As discussed in the [`OsString`] introduction, [`OsString`] and `OsStr`
667 /// store strings in a form best suited for cheap inter-conversion between
668 /// native-platform and Rust string forms, which may differ significantly
669 /// from both of them, including in storage size and encoding.
670 ///
671 /// This number is simply useful for passing to other methods, like
672 /// [`OsString::with_capacity`] to avoid reallocations.
673 ///
674 /// # Examples
675 ///
676 /// ```
677 /// use std::ffi::OsStr;
678 ///
679 /// let os_str = OsStr::new("");
680 /// assert_eq!(os_str.len(), 0);
681 ///
682 /// let os_str = OsStr::new("foo");
683 /// assert_eq!(os_str.len(), 3);
684 /// ```
685 #[doc(alias = "length")]
686 #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
687 #[inline]
688 pub fn len(&self) -> usize {
689 self.inner.inner.len()
690 }
691
692 /// Converts a [`Box`]`<OsStr>` into an [`OsString`] without copying or allocating.
693 #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
694 pub fn into_os_string(self: Box<OsStr>) -> OsString {
695 let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
696 OsString { inner: Buf::from_box(boxed) }
697 }
698
699 /// Gets the underlying byte representation.
700 ///
701 /// Note: it is *crucial* that this API is not externally public, to avoid
702 /// revealing the internal, platform-specific encodings.
703 #[inline]
704 pub(crate) fn bytes(&self) -> &[u8] {
705 unsafe { &*(&self.inner as *const _ as *const [u8]) }
706 }
707
708 /// Converts this string to its ASCII lower case equivalent in-place.
709 ///
710 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
711 /// but non-ASCII letters are unchanged.
712 ///
713 /// To return a new lowercased value without modifying the existing one, use
714 /// [`OsStr::to_ascii_lowercase`].
715 ///
716 /// # Examples
717 ///
718 /// ```
719 /// #![feature(osstring_ascii)]
720 /// use std::ffi::OsString;
721 ///
722 /// let mut s = OsString::from("GRÜßE, JÜRGEN ❤");
723 ///
724 /// s.make_ascii_lowercase();
725 ///
726 /// assert_eq!("grÜße, jÜrgen ❤", s);
727 /// ```
728 #[unstable(feature = "osstring_ascii", issue = "70516")]
729 #[inline]
730 pub fn make_ascii_lowercase(&mut self) {
731 self.inner.make_ascii_lowercase()
732 }
733
734 /// Converts this string to its ASCII upper case equivalent in-place.
735 ///
736 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
737 /// but non-ASCII letters are unchanged.
738 ///
739 /// To return a new uppercased value without modifying the existing one, use
740 /// [`OsStr::to_ascii_uppercase`].
741 ///
742 /// # Examples
743 ///
744 /// ```
745 /// #![feature(osstring_ascii)]
746 /// use std::ffi::OsString;
747 ///
748 /// let mut s = OsString::from("Grüße, Jürgen ❤");
749 ///
750 /// s.make_ascii_uppercase();
751 ///
752 /// assert_eq!("GRüßE, JüRGEN ❤", s);
753 /// ```
754 #[unstable(feature = "osstring_ascii", issue = "70516")]
755 #[inline]
756 pub fn make_ascii_uppercase(&mut self) {
757 self.inner.make_ascii_uppercase()
758 }
759
760 /// Returns a copy of this string where each character is mapped to its
761 /// ASCII lower case equivalent.
762 ///
763 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
764 /// but non-ASCII letters are unchanged.
765 ///
766 /// To lowercase the value in-place, use [`OsStr::make_ascii_lowercase`].
767 ///
768 /// # Examples
769 ///
770 /// ```
771 /// #![feature(osstring_ascii)]
772 /// use std::ffi::OsString;
773 /// let s = OsString::from("Grüße, Jürgen ❤");
774 ///
775 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
776 /// ```
777 #[unstable(feature = "osstring_ascii", issue = "70516")]
778 pub fn to_ascii_lowercase(&self) -> OsString {
779 OsString::from_inner(self.inner.to_ascii_lowercase())
780 }
781
782 /// Returns a copy of this string where each character is mapped to its
783 /// ASCII upper case equivalent.
784 ///
785 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
786 /// but non-ASCII letters are unchanged.
787 ///
788 /// To uppercase the value in-place, use [`OsStr::make_ascii_uppercase`].
789 ///
790 /// # Examples
791 ///
792 /// ```
793 /// #![feature(osstring_ascii)]
794 /// use std::ffi::OsString;
795 /// let s = OsString::from("Grüße, Jürgen ❤");
796 ///
797 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
798 /// ```
799 #[unstable(feature = "osstring_ascii", issue = "70516")]
800 pub fn to_ascii_uppercase(&self) -> OsString {
801 OsString::from_inner(self.inner.to_ascii_uppercase())
802 }
803
804 /// Checks if all characters in this string are within the ASCII range.
805 ///
806 /// # Examples
807 ///
808 /// ```
809 /// #![feature(osstring_ascii)]
810 /// use std::ffi::OsString;
811 ///
812 /// let ascii = OsString::from("hello!\n");
813 /// let non_ascii = OsString::from("Grüße, Jürgen ❤");
814 ///
815 /// assert!(ascii.is_ascii());
816 /// assert!(!non_ascii.is_ascii());
817 /// ```
818 #[unstable(feature = "osstring_ascii", issue = "70516")]
819 #[inline]
820 pub fn is_ascii(&self) -> bool {
821 self.inner.is_ascii()
822 }
823
824 /// Checks that two strings are an ASCII case-insensitive match.
825 ///
826 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
827 /// but without allocating and copying temporaries.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// #![feature(osstring_ascii)]
833 /// use std::ffi::OsString;
834 ///
835 /// assert!(OsString::from("Ferris").eq_ignore_ascii_case("FERRIS"));
836 /// assert!(OsString::from("Ferrös").eq_ignore_ascii_case("FERRöS"));
837 /// assert!(!OsString::from("Ferrös").eq_ignore_ascii_case("FERRÖS"));
838 /// ```
839 #[unstable(feature = "osstring_ascii", issue = "70516")]
840 pub fn eq_ignore_ascii_case<S: AsRef<OsStr>>(&self, other: S) -> bool {
841 self.inner.eq_ignore_ascii_case(&other.as_ref().inner)
842 }
843 }
844
845 #[stable(feature = "box_from_os_str", since = "1.17.0")]
846 impl From<&OsStr> for Box<OsStr> {
847 #[inline]
848 fn from(s: &OsStr) -> Box<OsStr> {
849 let rw = Box::into_raw(s.inner.into_box()) as *mut OsStr;
850 unsafe { Box::from_raw(rw) }
851 }
852 }
853
854 #[stable(feature = "box_from_cow", since = "1.45.0")]
855 impl From<Cow<'_, OsStr>> for Box<OsStr> {
856 #[inline]
857 fn from(cow: Cow<'_, OsStr>) -> Box<OsStr> {
858 match cow {
859 Cow::Borrowed(s) => Box::from(s),
860 Cow::Owned(s) => Box::from(s),
861 }
862 }
863 }
864
865 #[stable(feature = "os_string_from_box", since = "1.18.0")]
866 impl From<Box<OsStr>> for OsString {
867 /// Converts a [`Box`]`<`[`OsStr`]`>` into a `OsString` without copying or
868 /// allocating.
869 #[inline]
870 fn from(boxed: Box<OsStr>) -> OsString {
871 boxed.into_os_string()
872 }
873 }
874
875 #[stable(feature = "box_from_os_string", since = "1.20.0")]
876 impl From<OsString> for Box<OsStr> {
877 /// Converts a [`OsString`] into a [`Box`]`<OsStr>` without copying or allocating.
878 #[inline]
879 fn from(s: OsString) -> Box<OsStr> {
880 s.into_boxed_os_str()
881 }
882 }
883
884 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
885 impl Clone for Box<OsStr> {
886 #[inline]
887 fn clone(&self) -> Self {
888 self.to_os_string().into_boxed_os_str()
889 }
890 }
891
892 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
893 impl From<OsString> for Arc<OsStr> {
894 /// Converts a [`OsString`] into a [`Arc`]`<OsStr>` without copying or allocating.
895 #[inline]
896 fn from(s: OsString) -> Arc<OsStr> {
897 let arc = s.inner.into_arc();
898 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
899 }
900 }
901
902 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
903 impl From<&OsStr> for Arc<OsStr> {
904 #[inline]
905 fn from(s: &OsStr) -> Arc<OsStr> {
906 let arc = s.inner.into_arc();
907 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
908 }
909 }
910
911 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
912 impl From<OsString> for Rc<OsStr> {
913 /// Converts a [`OsString`] into a [`Rc`]`<OsStr>` without copying or allocating.
914 #[inline]
915 fn from(s: OsString) -> Rc<OsStr> {
916 let rc = s.inner.into_rc();
917 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
918 }
919 }
920
921 #[stable(feature = "shared_from_slice2", since = "1.24.0")]
922 impl From<&OsStr> for Rc<OsStr> {
923 #[inline]
924 fn from(s: &OsStr) -> Rc<OsStr> {
925 let rc = s.inner.into_rc();
926 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
927 }
928 }
929
930 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
931 impl<'a> From<OsString> for Cow<'a, OsStr> {
932 #[inline]
933 fn from(s: OsString) -> Cow<'a, OsStr> {
934 Cow::Owned(s)
935 }
936 }
937
938 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
939 impl<'a> From<&'a OsStr> for Cow<'a, OsStr> {
940 #[inline]
941 fn from(s: &'a OsStr) -> Cow<'a, OsStr> {
942 Cow::Borrowed(s)
943 }
944 }
945
946 #[stable(feature = "cow_from_osstr", since = "1.28.0")]
947 impl<'a> From<&'a OsString> for Cow<'a, OsStr> {
948 #[inline]
949 fn from(s: &'a OsString) -> Cow<'a, OsStr> {
950 Cow::Borrowed(s.as_os_str())
951 }
952 }
953
954 #[stable(feature = "osstring_from_cow_osstr", since = "1.28.0")]
955 impl<'a> From<Cow<'a, OsStr>> for OsString {
956 #[inline]
957 fn from(s: Cow<'a, OsStr>) -> Self {
958 s.into_owned()
959 }
960 }
961
962 #[stable(feature = "box_default_extra", since = "1.17.0")]
963 impl Default for Box<OsStr> {
964 #[inline]
965 fn default() -> Box<OsStr> {
966 let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
967 unsafe { Box::from_raw(rw) }
968 }
969 }
970
971 #[stable(feature = "osstring_default", since = "1.9.0")]
972 impl Default for &OsStr {
973 /// Creates an empty `OsStr`.
974 #[inline]
975 fn default() -> Self {
976 OsStr::new("")
977 }
978 }
979
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl PartialEq for OsStr {
982 #[inline]
983 fn eq(&self, other: &OsStr) -> bool {
984 self.bytes().eq(other.bytes())
985 }
986 }
987
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl PartialEq<str> for OsStr {
990 #[inline]
991 fn eq(&self, other: &str) -> bool {
992 *self == *OsStr::new(other)
993 }
994 }
995
996 #[stable(feature = "rust1", since = "1.0.0")]
997 impl PartialEq<OsStr> for str {
998 #[inline]
999 fn eq(&self, other: &OsStr) -> bool {
1000 *other == *OsStr::new(self)
1001 }
1002 }
1003
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl Eq for OsStr {}
1006
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl PartialOrd for OsStr {
1009 #[inline]
1010 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
1011 self.bytes().partial_cmp(other.bytes())
1012 }
1013 #[inline]
1014 fn lt(&self, other: &OsStr) -> bool {
1015 self.bytes().lt(other.bytes())
1016 }
1017 #[inline]
1018 fn le(&self, other: &OsStr) -> bool {
1019 self.bytes().le(other.bytes())
1020 }
1021 #[inline]
1022 fn gt(&self, other: &OsStr) -> bool {
1023 self.bytes().gt(other.bytes())
1024 }
1025 #[inline]
1026 fn ge(&self, other: &OsStr) -> bool {
1027 self.bytes().ge(other.bytes())
1028 }
1029 }
1030
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 impl PartialOrd<str> for OsStr {
1033 #[inline]
1034 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
1035 self.partial_cmp(OsStr::new(other))
1036 }
1037 }
1038
1039 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
1040 // have more flexible coherence rules.
1041
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl Ord for OsStr {
1044 #[inline]
1045 fn cmp(&self, other: &OsStr) -> cmp::Ordering {
1046 self.bytes().cmp(other.bytes())
1047 }
1048 }
1049
1050 macro_rules! impl_cmp {
1051 ($lhs:ty, $rhs: ty) => {
1052 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1053 impl<'a, 'b> PartialEq<$rhs> for $lhs {
1054 #[inline]
1055 fn eq(&self, other: &$rhs) -> bool {
1056 <OsStr as PartialEq>::eq(self, other)
1057 }
1058 }
1059
1060 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1061 impl<'a, 'b> PartialEq<$lhs> for $rhs {
1062 #[inline]
1063 fn eq(&self, other: &$lhs) -> bool {
1064 <OsStr as PartialEq>::eq(self, other)
1065 }
1066 }
1067
1068 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1069 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
1070 #[inline]
1071 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
1072 <OsStr as PartialOrd>::partial_cmp(self, other)
1073 }
1074 }
1075
1076 #[stable(feature = "cmp_os_str", since = "1.8.0")]
1077 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
1078 #[inline]
1079 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
1080 <OsStr as PartialOrd>::partial_cmp(self, other)
1081 }
1082 }
1083 };
1084 }
1085
1086 impl_cmp!(OsString, OsStr);
1087 impl_cmp!(OsString, &'a OsStr);
1088 impl_cmp!(Cow<'a, OsStr>, OsStr);
1089 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
1090 impl_cmp!(Cow<'a, OsStr>, OsString);
1091
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 impl Hash for OsStr {
1094 #[inline]
1095 fn hash<H: Hasher>(&self, state: &mut H) {
1096 self.bytes().hash(state)
1097 }
1098 }
1099
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl fmt::Debug for OsStr {
1102 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1103 fmt::Debug::fmt(&self.inner, formatter)
1104 }
1105 }
1106
1107 impl OsStr {
1108 pub(crate) fn display(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 fmt::Display::fmt(&self.inner, formatter)
1110 }
1111 }
1112
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl Borrow<OsStr> for OsString {
1115 #[inline]
1116 fn borrow(&self) -> &OsStr {
1117 &self[..]
1118 }
1119 }
1120
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 impl ToOwned for OsStr {
1123 type Owned = OsString;
1124 #[inline]
1125 fn to_owned(&self) -> OsString {
1126 self.to_os_string()
1127 }
1128 #[inline]
1129 fn clone_into(&self, target: &mut OsString) {
1130 self.inner.clone_into(&mut target.inner)
1131 }
1132 }
1133
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 impl AsRef<OsStr> for OsStr {
1136 #[inline]
1137 fn as_ref(&self) -> &OsStr {
1138 self
1139 }
1140 }
1141
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 impl AsRef<OsStr> for OsString {
1144 #[inline]
1145 fn as_ref(&self) -> &OsStr {
1146 self
1147 }
1148 }
1149
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 impl AsRef<OsStr> for str {
1152 #[inline]
1153 fn as_ref(&self) -> &OsStr {
1154 OsStr::from_inner(Slice::from_str(self))
1155 }
1156 }
1157
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl AsRef<OsStr> for String {
1160 #[inline]
1161 fn as_ref(&self) -> &OsStr {
1162 (&**self).as_ref()
1163 }
1164 }
1165
1166 impl FromInner<Buf> for OsString {
1167 #[inline]
1168 fn from_inner(buf: Buf) -> OsString {
1169 OsString { inner: buf }
1170 }
1171 }
1172
1173 impl IntoInner<Buf> for OsString {
1174 #[inline]
1175 fn into_inner(self) -> Buf {
1176 self.inner
1177 }
1178 }
1179
1180 impl AsInner<Slice> for OsStr {
1181 #[inline]
1182 fn as_inner(&self) -> &Slice {
1183 &self.inner
1184 }
1185 }
1186
1187 #[stable(feature = "osstring_from_str", since = "1.45.0")]
1188 impl FromStr for OsString {
1189 type Err = core::convert::Infallible;
1190
1191 #[inline]
1192 fn from_str(s: &str) -> Result<Self, Self::Err> {
1193 Ok(OsString::from(s))
1194 }
1195 }
1196
1197 #[stable(feature = "osstring_extend", since = "1.52.0")]
1198 impl Extend<OsString> for OsString {
1199 #[inline]
1200 fn extend<T: IntoIterator<Item = OsString>>(&mut self, iter: T) {
1201 for s in iter {
1202 self.push(&s);
1203 }
1204 }
1205 }
1206
1207 #[stable(feature = "osstring_extend", since = "1.52.0")]
1208 impl<'a> Extend<&'a OsStr> for OsString {
1209 #[inline]
1210 fn extend<T: IntoIterator<Item = &'a OsStr>>(&mut self, iter: T) {
1211 for s in iter {
1212 self.push(s);
1213 }
1214 }
1215 }
1216
1217 #[stable(feature = "osstring_extend", since = "1.52.0")]
1218 impl<'a> Extend<Cow<'a, OsStr>> for OsString {
1219 #[inline]
1220 fn extend<T: IntoIterator<Item = Cow<'a, OsStr>>>(&mut self, iter: T) {
1221 for s in iter {
1222 self.push(&s);
1223 }
1224 }
1225 }
1226
1227 #[stable(feature = "osstring_extend", since = "1.52.0")]
1228 impl FromIterator<OsString> for OsString {
1229 #[inline]
1230 fn from_iter<I: IntoIterator<Item = OsString>>(iter: I) -> Self {
1231 let mut iterator = iter.into_iter();
1232
1233 // Because we're iterating over `OsString`s, we can avoid at least
1234 // one allocation by getting the first string from the iterator
1235 // and appending to it all the subsequent strings.
1236 match iterator.next() {
1237 None => OsString::new(),
1238 Some(mut buf) => {
1239 buf.extend(iterator);
1240 buf
1241 }
1242 }
1243 }
1244 }
1245
1246 #[stable(feature = "osstring_extend", since = "1.52.0")]
1247 impl<'a> FromIterator<&'a OsStr> for OsString {
1248 #[inline]
1249 fn from_iter<I: IntoIterator<Item = &'a OsStr>>(iter: I) -> Self {
1250 let mut buf = Self::new();
1251 for s in iter {
1252 buf.push(s);
1253 }
1254 buf
1255 }
1256 }
1257
1258 #[stable(feature = "osstring_extend", since = "1.52.0")]
1259 impl<'a> FromIterator<Cow<'a, OsStr>> for OsString {
1260 #[inline]
1261 fn from_iter<I: IntoIterator<Item = Cow<'a, OsStr>>>(iter: I) -> Self {
1262 let mut iterator = iter.into_iter();
1263
1264 // Because we're iterating over `OsString`s, we can avoid at least
1265 // one allocation by getting the first owned string from the iterator
1266 // and appending to it all the subsequent strings.
1267 match iterator.next() {
1268 None => OsString::new(),
1269 Some(Cow::Owned(mut buf)) => {
1270 buf.extend(iterator);
1271 buf
1272 }
1273 Some(Cow::Borrowed(buf)) => {
1274 let mut buf = OsString::from(buf);
1275 buf.extend(iterator);
1276 buf
1277 }
1278 }
1279 }
1280 }