]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/os_str.rs
cb902461f39fd1b148c1b3e7ad4a08f51998ff4d
[rust.git] / src / libstd / ffi / os_str.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use borrow::{Borrow, Cow};
12 use fmt;
13 use ops;
14 use cmp;
15 use hash::{Hash, Hasher};
16 use rc::Rc;
17 use sync::Arc;
18
19 use sys::os_str::{Buf, Slice};
20 use sys_common::{AsInner, IntoInner, FromInner};
21
22 /// A type that can represent owned, mutable platform-native strings, but is
23 /// cheaply inter-convertible with Rust strings.
24 ///
25 /// The need for this type arises from the fact that:
26 ///
27 /// * On Unix systems, strings are often arbitrary sequences of non-zero
28 ///   bytes, in many cases interpreted as UTF-8.
29 ///
30 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
31 ///   values, interpreted as UTF-16 when it is valid to do so.
32 ///
33 /// * In Rust, strings are always valid UTF-8, which may contain zeros.
34 ///
35 /// `OsString` and [`OsStr`] bridge this gap by simultaneously representing Rust
36 /// and platform-native string values, and in particular allowing a Rust string
37 /// to be converted into an "OS" string with no cost if possible.
38 ///
39 /// `OsString` is to [`OsStr`] as [`String`] is to [`&str`]: the former
40 /// in each pair are owned strings; the latter are borrowed
41 /// references.
42 ///
43 /// # Creating an `OsString`
44 ///
45 /// **From a Rust string**: `OsString` implements
46 /// [`From`]`<`[`String`]`>`, so you can use `my_string.from` to
47 /// create an `OsString` from a normal Rust string.
48 ///
49 /// **From slices:** Just like you can start with an empty Rust
50 /// [`String`] and then [`push_str`][String.push_str] `&str`
51 /// sub-string slices into it, you can create an empty `OsString` with
52 /// the [`new`] method and then push string slices into it with the
53 /// [`push`] method.
54 ///
55 /// # Extracting a borrowed reference to the whole OS string
56 ///
57 /// You can use the [`as_os_str`] method to get an `&`[`OsStr`] from
58 /// an `OsString`; this is effectively a borrowed reference to the
59 /// whole string.
60 ///
61 /// # Conversions
62 ///
63 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
64 /// the traits which `OsString` implements for conversions from/to native representations.
65 ///
66 /// [`OsStr`]: struct.OsStr.html
67 /// [`From`]: ../convert/trait.From.html
68 /// [`String`]: ../string/struct.String.html
69 /// [`&str`]: ../primitive.str.html
70 /// [`u8`]: ../primitive.u8.html
71 /// [`u16`]: ../primitive.u16.html
72 /// [String.push_str]: ../string/struct.String.html#method.push_str
73 /// [`new`]: #method.new
74 /// [`push`]: #method.push
75 /// [`as_os_str`]: #method.as_os_str
76 #[derive(Clone)]
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct OsString {
79     inner: Buf
80 }
81
82 /// Borrowed reference to an OS string (see [`OsString`]).
83 ///
84 /// This type represents a borrowed reference to a string in the operating system's preferred
85 /// representation.
86 ///
87 /// `OsStr` is to [`OsString`] as [`String`] is to [`&str`]: the former in each pair are borrowed
88 /// references; the latter are owned strings.
89 ///
90 /// See the [module's toplevel documentation about conversions][conversions] for a discussion on
91 /// the traits which `OsStr` implements for conversions from/to native representations.
92 ///
93 /// [`OsString`]: struct.OsString.html
94 /// [conversions]: index.html#conversions
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct OsStr {
97     inner: Slice
98 }
99
100 impl OsString {
101     /// Constructs a new empty `OsString`.
102     ///
103     /// # Examples
104     ///
105     /// ```
106     /// use std::ffi::OsString;
107     ///
108     /// let os_string = OsString::new();
109     /// ```
110     #[stable(feature = "rust1", since = "1.0.0")]
111     pub fn new() -> OsString {
112         OsString { inner: Buf::from_string(String::new()) }
113     }
114
115     /// Converts to an [`OsStr`] slice.
116     ///
117     /// [`OsStr`]: struct.OsStr.html
118     ///
119     /// # Examples
120     ///
121     /// ```
122     /// use std::ffi::{OsString, OsStr};
123     ///
124     /// let os_string = OsString::from("foo");
125     /// let os_str = OsStr::new("foo");
126     /// assert_eq!(os_string.as_os_str(), os_str);
127     /// ```
128     #[stable(feature = "rust1", since = "1.0.0")]
129     pub fn as_os_str(&self) -> &OsStr {
130         self
131     }
132
133     /// Converts the `OsString` into a [`String`] if it contains valid Unicode data.
134     ///
135     /// On failure, ownership of the original `OsString` is returned.
136     ///
137     /// [`String`]: ../../std/string/struct.String.html
138     ///
139     /// # Examples
140     ///
141     /// ```
142     /// use std::ffi::OsString;
143     ///
144     /// let os_string = OsString::from("foo");
145     /// let string = os_string.into_string();
146     /// assert_eq!(string, Ok(String::from("foo")));
147     /// ```
148     #[stable(feature = "rust1", since = "1.0.0")]
149     pub fn into_string(self) -> Result<String, OsString> {
150         self.inner.into_string().map_err(|buf| OsString { inner: buf} )
151     }
152
153     /// Extends the string with the given [`&OsStr`] slice.
154     ///
155     /// [`&OsStr`]: struct.OsStr.html
156     ///
157     /// # Examples
158     ///
159     /// ```
160     /// use std::ffi::OsString;
161     ///
162     /// let mut os_string = OsString::from("foo");
163     /// os_string.push("bar");
164     /// assert_eq!(&os_string, "foobar");
165     /// ```
166     #[stable(feature = "rust1", since = "1.0.0")]
167     pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
168         self.inner.push_slice(&s.as_ref().inner)
169     }
170
171     /// Creates a new `OsString` with the given capacity.
172     ///
173     /// The string will be able to hold exactly `capacity` length units of other
174     /// OS strings without reallocating. If `capacity` is 0, the string will not
175     /// allocate.
176     ///
177     /// See main `OsString` documentation information about encoding.
178     ///
179     /// # Examples
180     ///
181     /// ```
182     /// use std::ffi::OsString;
183     ///
184     /// let mut os_string = OsString::with_capacity(10);
185     /// let capacity = os_string.capacity();
186     ///
187     /// // This push is done without reallocating
188     /// os_string.push("foo");
189     ///
190     /// assert_eq!(capacity, os_string.capacity());
191     /// ```
192     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
193     pub fn with_capacity(capacity: usize) -> OsString {
194         OsString {
195             inner: Buf::with_capacity(capacity)
196         }
197     }
198
199     /// Truncates the `OsString` to zero length.
200     ///
201     /// # Examples
202     ///
203     /// ```
204     /// use std::ffi::OsString;
205     ///
206     /// let mut os_string = OsString::from("foo");
207     /// assert_eq!(&os_string, "foo");
208     ///
209     /// os_string.clear();
210     /// assert_eq!(&os_string, "");
211     /// ```
212     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
213     pub fn clear(&mut self) {
214         self.inner.clear()
215     }
216
217     /// Returns the capacity this `OsString` can hold without reallocating.
218     ///
219     /// See `OsString` introduction for information about encoding.
220     ///
221     /// # Examples
222     ///
223     /// ```
224     /// use std::ffi::OsString;
225     ///
226     /// let mut os_string = OsString::with_capacity(10);
227     /// assert!(os_string.capacity() >= 10);
228     /// ```
229     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
230     pub fn capacity(&self) -> usize {
231         self.inner.capacity()
232     }
233
234     /// Reserves capacity for at least `additional` more capacity to be inserted
235     /// in the given `OsString`.
236     ///
237     /// The collection may reserve more space to avoid frequent reallocations.
238     ///
239     /// # Examples
240     ///
241     /// ```
242     /// use std::ffi::OsString;
243     ///
244     /// let mut s = OsString::new();
245     /// s.reserve(10);
246     /// assert!(s.capacity() >= 10);
247     /// ```
248     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
249     pub fn reserve(&mut self, additional: usize) {
250         self.inner.reserve(additional)
251     }
252
253     /// Reserves the minimum capacity for exactly `additional` more capacity to
254     /// be inserted in the given `OsString`. Does nothing if the capacity is
255     /// already sufficient.
256     ///
257     /// Note that the allocator may give the collection more space than it
258     /// requests. Therefore capacity can not be relied upon to be precisely
259     /// minimal. Prefer reserve if future insertions are expected.
260     ///
261     /// # Examples
262     ///
263     /// ```
264     /// use std::ffi::OsString;
265     ///
266     /// let mut s = OsString::new();
267     /// s.reserve_exact(10);
268     /// assert!(s.capacity() >= 10);
269     /// ```
270     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
271     pub fn reserve_exact(&mut self, additional: usize) {
272         self.inner.reserve_exact(additional)
273     }
274
275     /// Shrinks the capacity of the `OsString` to match its length.
276     ///
277     /// # Examples
278     ///
279     /// ```
280     /// use std::ffi::OsString;
281     ///
282     /// let mut s = OsString::from("foo");
283     ///
284     /// s.reserve(100);
285     /// assert!(s.capacity() >= 100);
286     ///
287     /// s.shrink_to_fit();
288     /// assert_eq!(3, s.capacity());
289     /// ```
290     #[stable(feature = "osstring_shrink_to_fit", since = "1.19.0")]
291     pub fn shrink_to_fit(&mut self) {
292         self.inner.shrink_to_fit()
293     }
294
295     /// Converts this `OsString` into a boxed [`OsStr`].
296     ///
297     /// [`OsStr`]: struct.OsStr.html
298     ///
299     /// # Examples
300     ///
301     /// ```
302     /// use std::ffi::{OsString, OsStr};
303     ///
304     /// let s = OsString::from("hello");
305     ///
306     /// let b: Box<OsStr> = s.into_boxed_os_str();
307     /// ```
308     #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
309     pub fn into_boxed_os_str(self) -> Box<OsStr> {
310         let rw = Box::into_raw(self.inner.into_box()) as *mut OsStr;
311         unsafe { Box::from_raw(rw) }
312     }
313 }
314
315 #[stable(feature = "rust1", since = "1.0.0")]
316 impl From<String> for OsString {
317     fn from(s: String) -> OsString {
318         OsString { inner: Buf::from_string(s) }
319     }
320 }
321
322 #[stable(feature = "rust1", since = "1.0.0")]
323 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for OsString {
324     fn from(s: &'a T) -> OsString {
325         s.as_ref().to_os_string()
326     }
327 }
328
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl ops::Index<ops::RangeFull> for OsString {
331     type Output = OsStr;
332
333     #[inline]
334     fn index(&self, _index: ops::RangeFull) -> &OsStr {
335         OsStr::from_inner(self.inner.as_slice())
336     }
337 }
338
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl ops::Deref for OsString {
341     type Target = OsStr;
342
343     #[inline]
344     fn deref(&self) -> &OsStr {
345         &self[..]
346     }
347 }
348
349 #[stable(feature = "osstring_default", since = "1.9.0")]
350 impl Default for OsString {
351     /// Constructs an empty `OsString`.
352     #[inline]
353     fn default() -> OsString {
354         OsString::new()
355     }
356 }
357
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl fmt::Debug for OsString {
360     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
361         fmt::Debug::fmt(&**self, formatter)
362     }
363 }
364
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl PartialEq for OsString {
367     fn eq(&self, other: &OsString) -> bool {
368         &**self == &**other
369     }
370 }
371
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl PartialEq<str> for OsString {
374     fn eq(&self, other: &str) -> bool {
375         &**self == other
376     }
377 }
378
379 #[stable(feature = "rust1", since = "1.0.0")]
380 impl PartialEq<OsString> for str {
381     fn eq(&self, other: &OsString) -> bool {
382         &**other == self
383     }
384 }
385
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl Eq for OsString {}
388
389 #[stable(feature = "rust1", since = "1.0.0")]
390 impl PartialOrd for OsString {
391     #[inline]
392     fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
393         (&**self).partial_cmp(&**other)
394     }
395     #[inline]
396     fn lt(&self, other: &OsString) -> bool { &**self < &**other }
397     #[inline]
398     fn le(&self, other: &OsString) -> bool { &**self <= &**other }
399     #[inline]
400     fn gt(&self, other: &OsString) -> bool { &**self > &**other }
401     #[inline]
402     fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
403 }
404
405 #[stable(feature = "rust1", since = "1.0.0")]
406 impl PartialOrd<str> for OsString {
407     #[inline]
408     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
409         (&**self).partial_cmp(other)
410     }
411 }
412
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl Ord for OsString {
415     #[inline]
416     fn cmp(&self, other: &OsString) -> cmp::Ordering {
417         (&**self).cmp(&**other)
418     }
419 }
420
421 #[stable(feature = "rust1", since = "1.0.0")]
422 impl Hash for OsString {
423     #[inline]
424     fn hash<H: Hasher>(&self, state: &mut H) {
425         (&**self).hash(state)
426     }
427 }
428
429 impl OsStr {
430     /// Coerces into an `OsStr` slice.
431     ///
432     /// # Examples
433     ///
434     /// ```
435     /// use std::ffi::OsStr;
436     ///
437     /// let os_str = OsStr::new("foo");
438     /// ```
439     #[stable(feature = "rust1", since = "1.0.0")]
440     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
441         s.as_ref()
442     }
443
444     fn from_inner(inner: &Slice) -> &OsStr {
445         unsafe { &*(inner as *const Slice as *const OsStr) }
446     }
447
448     /// Yields a [`&str`] slice if the `OsStr` is valid Unicode.
449     ///
450     /// This conversion may entail doing a check for UTF-8 validity.
451     ///
452     /// [`&str`]: ../../std/primitive.str.html
453     ///
454     /// # Examples
455     ///
456     /// ```
457     /// use std::ffi::OsStr;
458     ///
459     /// let os_str = OsStr::new("foo");
460     /// assert_eq!(os_str.to_str(), Some("foo"));
461     /// ```
462     #[stable(feature = "rust1", since = "1.0.0")]
463     pub fn to_str(&self) -> Option<&str> {
464         self.inner.to_str()
465     }
466
467     /// Converts an `OsStr` to a [`Cow`]`<`[`str`]`>`.
468     ///
469     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
470     ///
471     /// [`Cow`]: ../../std/borrow/enum.Cow.html
472     /// [`str`]: ../../std/primitive.str.html
473     ///
474     /// # Examples
475     ///
476     /// Calling `to_string_lossy` on an `OsStr` with valid unicode:
477     ///
478     /// ```
479     /// use std::ffi::OsStr;
480     ///
481     /// let os_str = OsStr::new("foo");
482     /// assert_eq!(os_str.to_string_lossy(), "foo");
483     /// ```
484     ///
485     /// Had `os_str` contained invalid unicode, the `to_string_lossy` call might
486     /// have returned `"fo�"`.
487     #[stable(feature = "rust1", since = "1.0.0")]
488     pub fn to_string_lossy(&self) -> Cow<str> {
489         self.inner.to_string_lossy()
490     }
491
492     /// Copies the slice into an owned [`OsString`].
493     ///
494     /// [`OsString`]: struct.OsString.html
495     ///
496     /// # Examples
497     ///
498     /// ```
499     /// use std::ffi::{OsStr, OsString};
500     ///
501     /// let os_str = OsStr::new("foo");
502     /// let os_string = os_str.to_os_string();
503     /// assert_eq!(os_string, OsString::from("foo"));
504     /// ```
505     #[stable(feature = "rust1", since = "1.0.0")]
506     pub fn to_os_string(&self) -> OsString {
507         OsString { inner: self.inner.to_owned() }
508     }
509
510     /// Checks whether the `OsStr` is empty.
511     ///
512     /// # Examples
513     ///
514     /// ```
515     /// use std::ffi::OsStr;
516     ///
517     /// let os_str = OsStr::new("");
518     /// assert!(os_str.is_empty());
519     ///
520     /// let os_str = OsStr::new("foo");
521     /// assert!(!os_str.is_empty());
522     /// ```
523     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
524     pub fn is_empty(&self) -> bool {
525         self.inner.inner.is_empty()
526     }
527
528     /// Returns the length of this `OsStr`.
529     ///
530     /// Note that this does **not** return the number of bytes in this string
531     /// as, for example, OS strings on Windows are encoded as a list of [`u16`]
532     /// rather than a list of bytes. This number is simply useful for passing to
533     /// other methods like [`OsString::with_capacity`] to avoid reallocations.
534     ///
535     /// See `OsStr` introduction for more information about encoding.
536     ///
537     /// [`u16`]: ../primitive.u16.html
538     /// [`OsString::with_capacity`]: struct.OsString.html#method.with_capacity
539     ///
540     /// # Examples
541     ///
542     /// ```
543     /// use std::ffi::OsStr;
544     ///
545     /// let os_str = OsStr::new("");
546     /// assert_eq!(os_str.len(), 0);
547     ///
548     /// let os_str = OsStr::new("foo");
549     /// assert_eq!(os_str.len(), 3);
550     /// ```
551     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
552     pub fn len(&self) -> usize {
553         self.inner.inner.len()
554     }
555
556     /// Converts a [`Box`]`<OsStr>` into an [`OsString`] without copying or allocating.
557     ///
558     /// [`Box`]: ../boxed/struct.Box.html
559     /// [`OsString`]: struct.OsString.html
560     #[stable(feature = "into_boxed_os_str", since = "1.20.0")]
561     pub fn into_os_string(self: Box<OsStr>) -> OsString {
562         let boxed = unsafe { Box::from_raw(Box::into_raw(self) as *mut Slice) };
563         OsString { inner: Buf::from_box(boxed) }
564     }
565
566     /// Gets the underlying byte representation.
567     ///
568     /// Note: it is *crucial* that this API is private, to avoid
569     /// revealing the internal, platform-specific encodings.
570     fn bytes(&self) -> &[u8] {
571         unsafe { &*(&self.inner as *const _ as *const [u8]) }
572     }
573 }
574
575 #[stable(feature = "box_from_os_str", since = "1.17.0")]
576 impl<'a> From<&'a OsStr> for Box<OsStr> {
577     fn from(s: &'a OsStr) -> Box<OsStr> {
578         let rw = Box::into_raw(s.inner.into_box()) as *mut OsStr;
579         unsafe { Box::from_raw(rw) }
580     }
581 }
582
583 #[stable(feature = "os_string_from_box", since = "1.18.0")]
584 impl From<Box<OsStr>> for OsString {
585     fn from(boxed: Box<OsStr>) -> OsString {
586         boxed.into_os_string()
587     }
588 }
589
590 #[stable(feature = "box_from_os_string", since = "1.20.0")]
591 impl From<OsString> for Box<OsStr> {
592     fn from(s: OsString) -> Box<OsStr> {
593         s.into_boxed_os_str()
594     }
595 }
596
597 #[stable(feature = "shared_from_slice2", since = "1.23.0")]
598 impl From<OsString> for Arc<OsStr> {
599     #[inline]
600     fn from(s: OsString) -> Arc<OsStr> {
601         let arc = s.inner.into_arc();
602         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
603     }
604 }
605
606 #[stable(feature = "shared_from_slice2", since = "1.23.0")]
607 impl<'a> From<&'a OsStr> for Arc<OsStr> {
608     #[inline]
609     fn from(s: &OsStr) -> Arc<OsStr> {
610         let arc = s.inner.into_arc();
611         unsafe { Arc::from_raw(Arc::into_raw(arc) as *const OsStr) }
612     }
613 }
614
615 #[stable(feature = "shared_from_slice2", since = "1.23.0")]
616 impl From<OsString> for Rc<OsStr> {
617     #[inline]
618     fn from(s: OsString) -> Rc<OsStr> {
619         let rc = s.inner.into_rc();
620         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
621     }
622 }
623
624 #[stable(feature = "shared_from_slice2", since = "1.23.0")]
625 impl<'a> From<&'a OsStr> for Rc<OsStr> {
626     #[inline]
627     fn from(s: &OsStr) -> Rc<OsStr> {
628         let rc = s.inner.into_rc();
629         unsafe { Rc::from_raw(Rc::into_raw(rc) as *const OsStr) }
630     }
631 }
632
633 #[stable(feature = "box_default_extra", since = "1.17.0")]
634 impl Default for Box<OsStr> {
635     fn default() -> Box<OsStr> {
636         let rw = Box::into_raw(Slice::empty_box()) as *mut OsStr;
637         unsafe { Box::from_raw(rw) }
638     }
639 }
640
641 #[stable(feature = "osstring_default", since = "1.9.0")]
642 impl<'a> Default for &'a OsStr {
643     /// Creates an empty `OsStr`.
644     #[inline]
645     fn default() -> &'a OsStr {
646         OsStr::new("")
647     }
648 }
649
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl PartialEq for OsStr {
652     fn eq(&self, other: &OsStr) -> bool {
653         self.bytes().eq(other.bytes())
654     }
655 }
656
657 #[stable(feature = "rust1", since = "1.0.0")]
658 impl PartialEq<str> for OsStr {
659     fn eq(&self, other: &str) -> bool {
660         *self == *OsStr::new(other)
661     }
662 }
663
664 #[stable(feature = "rust1", since = "1.0.0")]
665 impl PartialEq<OsStr> for str {
666     fn eq(&self, other: &OsStr) -> bool {
667         *other == *OsStr::new(self)
668     }
669 }
670
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl Eq for OsStr {}
673
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl PartialOrd for OsStr {
676     #[inline]
677     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
678         self.bytes().partial_cmp(other.bytes())
679     }
680     #[inline]
681     fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
682     #[inline]
683     fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
684     #[inline]
685     fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
686     #[inline]
687     fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
688 }
689
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl PartialOrd<str> for OsStr {
692     #[inline]
693     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
694         self.partial_cmp(OsStr::new(other))
695     }
696 }
697
698 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
699 // have more flexible coherence rules.
700
701 #[stable(feature = "rust1", since = "1.0.0")]
702 impl Ord for OsStr {
703     #[inline]
704     fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
705 }
706
707 macro_rules! impl_cmp {
708     ($lhs:ty, $rhs: ty) => {
709         #[stable(feature = "cmp_os_str", since = "1.8.0")]
710         impl<'a, 'b> PartialEq<$rhs> for $lhs {
711             #[inline]
712             fn eq(&self, other: &$rhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
713         }
714
715         #[stable(feature = "cmp_os_str", since = "1.8.0")]
716         impl<'a, 'b> PartialEq<$lhs> for $rhs {
717             #[inline]
718             fn eq(&self, other: &$lhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
719         }
720
721         #[stable(feature = "cmp_os_str", since = "1.8.0")]
722         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
723             #[inline]
724             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
725                 <OsStr as PartialOrd>::partial_cmp(self, other)
726             }
727         }
728
729         #[stable(feature = "cmp_os_str", since = "1.8.0")]
730         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
731             #[inline]
732             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
733                 <OsStr as PartialOrd>::partial_cmp(self, other)
734             }
735         }
736     }
737 }
738
739 impl_cmp!(OsString, OsStr);
740 impl_cmp!(OsString, &'a OsStr);
741 impl_cmp!(Cow<'a, OsStr>, OsStr);
742 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
743 impl_cmp!(Cow<'a, OsStr>, OsString);
744
745 #[stable(feature = "rust1", since = "1.0.0")]
746 impl Hash for OsStr {
747     #[inline]
748     fn hash<H: Hasher>(&self, state: &mut H) {
749         self.bytes().hash(state)
750     }
751 }
752
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl fmt::Debug for OsStr {
755     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
756         fmt::Debug::fmt(&self.inner, formatter)
757     }
758 }
759
760 impl OsStr {
761     pub(crate) fn display(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
762         fmt::Display::fmt(&self.inner, formatter)
763     }
764 }
765
766 #[stable(feature = "rust1", since = "1.0.0")]
767 impl Borrow<OsStr> for OsString {
768     fn borrow(&self) -> &OsStr { &self[..] }
769 }
770
771 #[stable(feature = "rust1", since = "1.0.0")]
772 impl ToOwned for OsStr {
773     type Owned = OsString;
774     fn to_owned(&self) -> OsString {
775         self.to_os_string()
776     }
777     fn clone_into(&self, target: &mut OsString) {
778         target.clear();
779         target.push(self);
780     }
781 }
782
783 #[stable(feature = "rust1", since = "1.0.0")]
784 impl AsRef<OsStr> for OsStr {
785     fn as_ref(&self) -> &OsStr {
786         self
787     }
788 }
789
790 #[stable(feature = "rust1", since = "1.0.0")]
791 impl AsRef<OsStr> for OsString {
792     fn as_ref(&self) -> &OsStr {
793         self
794     }
795 }
796
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl AsRef<OsStr> for str {
799     fn as_ref(&self) -> &OsStr {
800         OsStr::from_inner(Slice::from_str(self))
801     }
802 }
803
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl AsRef<OsStr> for String {
806     fn as_ref(&self) -> &OsStr {
807         (&**self).as_ref()
808     }
809 }
810
811 impl FromInner<Buf> for OsString {
812     fn from_inner(buf: Buf) -> OsString {
813         OsString { inner: buf }
814     }
815 }
816
817 impl IntoInner<Buf> for OsString {
818     fn into_inner(self) -> Buf {
819         self.inner
820     }
821 }
822
823 impl AsInner<Slice> for OsStr {
824     fn as_inner(&self) -> &Slice {
825         &self.inner
826     }
827 }
828
829 #[cfg(test)]
830 mod tests {
831     use super::*;
832     use sys_common::{AsInner, IntoInner};
833
834     use rc::Rc;
835     use sync::Arc;
836
837     #[test]
838     fn test_os_string_with_capacity() {
839         let os_string = OsString::with_capacity(0);
840         assert_eq!(0, os_string.inner.into_inner().capacity());
841
842         let os_string = OsString::with_capacity(10);
843         assert_eq!(10, os_string.inner.into_inner().capacity());
844
845         let mut os_string = OsString::with_capacity(0);
846         os_string.push("abc");
847         assert!(os_string.inner.into_inner().capacity() >= 3);
848     }
849
850     #[test]
851     fn test_os_string_clear() {
852         let mut os_string = OsString::from("abc");
853         assert_eq!(3, os_string.inner.as_inner().len());
854
855         os_string.clear();
856         assert_eq!(&os_string, "");
857         assert_eq!(0, os_string.inner.as_inner().len());
858     }
859
860     #[test]
861     fn test_os_string_capacity() {
862         let os_string = OsString::with_capacity(0);
863         assert_eq!(0, os_string.capacity());
864
865         let os_string = OsString::with_capacity(10);
866         assert_eq!(10, os_string.capacity());
867
868         let mut os_string = OsString::with_capacity(0);
869         os_string.push("abc");
870         assert!(os_string.capacity() >= 3);
871     }
872
873     #[test]
874     fn test_os_string_reserve() {
875         let mut os_string = OsString::new();
876         assert_eq!(os_string.capacity(), 0);
877
878         os_string.reserve(2);
879         assert!(os_string.capacity() >= 2);
880
881         for _ in 0..16 {
882             os_string.push("a");
883         }
884
885         assert!(os_string.capacity() >= 16);
886         os_string.reserve(16);
887         assert!(os_string.capacity() >= 32);
888
889         os_string.push("a");
890
891         os_string.reserve(16);
892         assert!(os_string.capacity() >= 33)
893     }
894
895     #[test]
896     fn test_os_string_reserve_exact() {
897         let mut os_string = OsString::new();
898         assert_eq!(os_string.capacity(), 0);
899
900         os_string.reserve_exact(2);
901         assert!(os_string.capacity() >= 2);
902
903         for _ in 0..16 {
904             os_string.push("a");
905         }
906
907         assert!(os_string.capacity() >= 16);
908         os_string.reserve_exact(16);
909         assert!(os_string.capacity() >= 32);
910
911         os_string.push("a");
912
913         os_string.reserve_exact(16);
914         assert!(os_string.capacity() >= 33)
915     }
916
917     #[test]
918     fn test_os_string_default() {
919         let os_string: OsString = Default::default();
920         assert_eq!("", &os_string);
921     }
922
923     #[test]
924     fn test_os_str_is_empty() {
925         let mut os_string = OsString::new();
926         assert!(os_string.is_empty());
927
928         os_string.push("abc");
929         assert!(!os_string.is_empty());
930
931         os_string.clear();
932         assert!(os_string.is_empty());
933     }
934
935     #[test]
936     fn test_os_str_len() {
937         let mut os_string = OsString::new();
938         assert_eq!(0, os_string.len());
939
940         os_string.push("abc");
941         assert_eq!(3, os_string.len());
942
943         os_string.clear();
944         assert_eq!(0, os_string.len());
945     }
946
947     #[test]
948     fn test_os_str_default() {
949         let os_str: &OsStr = Default::default();
950         assert_eq!("", os_str);
951     }
952
953     #[test]
954     fn into_boxed() {
955         let orig = "Hello, world!";
956         let os_str = OsStr::new(orig);
957         let boxed: Box<OsStr> = Box::from(os_str);
958         let os_string = os_str.to_owned().into_boxed_os_str().into_os_string();
959         assert_eq!(os_str, &*boxed);
960         assert_eq!(&*boxed, &*os_string);
961         assert_eq!(&*os_string, os_str);
962     }
963
964     #[test]
965     fn boxed_default() {
966         let boxed = <Box<OsStr>>::default();
967         assert!(boxed.is_empty());
968     }
969
970     #[test]
971     fn test_os_str_clone_into() {
972         let mut os_string = OsString::with_capacity(123);
973         os_string.push("hello");
974         let os_str = OsStr::new("bonjour");
975         os_str.clone_into(&mut os_string);
976         assert_eq!(os_str, os_string);
977         assert!(os_string.capacity() >= 123);
978     }
979
980     #[test]
981     fn into_rc() {
982         let orig = "Hello, world!";
983         let os_str = OsStr::new(orig);
984         let rc: Rc<OsStr> = Rc::from(os_str);
985         let arc: Arc<OsStr> = Arc::from(os_str);
986
987         assert_eq!(&*rc, os_str);
988         assert_eq!(&*arc, os_str);
989
990         let rc2: Rc<OsStr> = Rc::from(os_str.to_owned());
991         let arc2: Arc<OsStr> = Arc::from(os_str.to_owned());
992
993         assert_eq!(&*rc2, os_str);
994         assert_eq!(&*arc2, os_str);
995     }
996 }