]> git.lizzy.rs Git - rust.git/blob - src/libstd/ffi/os_str.rs
Auto merge of #35585 - Kha:gdb-qualified, r=michaelwoerister
[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::{self, Debug};
13 use mem;
14 use ops;
15 use cmp;
16 use hash::{Hash, Hasher};
17
18 use sys::os_str::{Buf, Slice};
19 use sys_common::{AsInner, IntoInner, FromInner};
20
21 /// A type that can represent owned, mutable platform-native strings, but is
22 /// cheaply inter-convertible with Rust strings.
23 ///
24 /// The need for this type arises from the fact that:
25 ///
26 /// * On Unix systems, strings are often arbitrary sequences of non-zero
27 ///   bytes, in many cases interpreted as UTF-8.
28 ///
29 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
30 ///   values, interpreted as UTF-16 when it is valid to do so.
31 ///
32 /// * In Rust, strings are always valid UTF-8, but may contain zeros.
33 ///
34 /// `OsString` and `OsStr` bridge this gap by simultaneously representing Rust
35 /// and platform-native string values, and in particular allowing a Rust string
36 /// to be converted into an "OS" string with no cost.
37 #[derive(Clone)]
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub struct OsString {
40     inner: Buf
41 }
42
43 /// Slices into OS strings (see `OsString`).
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub struct OsStr {
46     inner: Slice
47 }
48
49 impl OsString {
50     /// Constructs a new empty `OsString`.
51     #[stable(feature = "rust1", since = "1.0.0")]
52     pub fn new() -> OsString {
53         OsString { inner: Buf::from_string(String::new()) }
54     }
55
56     #[cfg(unix)]
57     fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
58         use os::unix::ffi::OsStringExt;
59         Some(OsString::from_vec(vec))
60     }
61
62     #[cfg(windows)]
63     fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
64         String::from_utf8(vec).ok().map(OsString::from)
65     }
66
67     /// Converts to an `OsStr` slice.
68     #[stable(feature = "rust1", since = "1.0.0")]
69     pub fn as_os_str(&self) -> &OsStr {
70         self
71     }
72
73     /// Converts the `OsString` into a `String` if it contains valid Unicode data.
74     ///
75     /// On failure, ownership of the original `OsString` is returned.
76     #[stable(feature = "rust1", since = "1.0.0")]
77     pub fn into_string(self) -> Result<String, OsString> {
78         self.inner.into_string().map_err(|buf| OsString { inner: buf} )
79     }
80
81     /// Extends the string with the given `&OsStr` slice.
82     #[stable(feature = "rust1", since = "1.0.0")]
83     pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
84         self.inner.push_slice(&s.as_ref().inner)
85     }
86
87     /// Creates a new `OsString` with the given capacity.
88     ///
89     /// The string will be able to hold exactly `capacity` lenth units of other
90     /// OS strings without reallocating. If `capacity` is 0, the string will not
91     /// allocate.
92     ///
93     /// See main `OsString` documentation information about encoding.
94     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
95     pub fn with_capacity(capacity: usize) -> OsString {
96         OsString {
97             inner: Buf::with_capacity(capacity)
98         }
99     }
100
101     /// Truncates the `OsString` to zero length.
102     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
103     pub fn clear(&mut self) {
104         self.inner.clear()
105     }
106
107     /// Returns the capacity this `OsString` can hold without reallocating.
108     ///
109     /// See `OsString` introduction for information about encoding.
110     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
111     pub fn capacity(&self) -> usize {
112         self.inner.capacity()
113     }
114
115     /// Reserves capacity for at least `additional` more capacity to be inserted
116     /// in the given `OsString`.
117     ///
118     /// The collection may reserve more space to avoid frequent reallocations.
119     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
120     pub fn reserve(&mut self, additional: usize) {
121         self.inner.reserve(additional)
122     }
123
124     /// Reserves the minimum capacity for exactly `additional` more capacity to
125     /// be inserted in the given `OsString`. Does nothing if the capacity is
126     /// already sufficient.
127     ///
128     /// Note that the allocator may give the collection more space than it
129     /// requests. Therefore capacity can not be relied upon to be precisely
130     /// minimal. Prefer reserve if future insertions are expected.
131     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
132     pub fn reserve_exact(&mut self, additional: usize) {
133         self.inner.reserve_exact(additional)
134     }
135 }
136
137 #[stable(feature = "rust1", since = "1.0.0")]
138 impl From<String> for OsString {
139     fn from(s: String) -> OsString {
140         OsString { inner: Buf::from_string(s) }
141     }
142 }
143
144 #[stable(feature = "rust1", since = "1.0.0")]
145 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for OsString {
146     fn from(s: &'a T) -> OsString {
147         s.as_ref().to_os_string()
148     }
149 }
150
151 #[stable(feature = "rust1", since = "1.0.0")]
152 impl ops::Index<ops::RangeFull> for OsString {
153     type Output = OsStr;
154
155     #[inline]
156     fn index(&self, _index: ops::RangeFull) -> &OsStr {
157         OsStr::from_inner(self.inner.as_slice())
158     }
159 }
160
161 #[stable(feature = "rust1", since = "1.0.0")]
162 impl ops::Deref for OsString {
163     type Target = OsStr;
164
165     #[inline]
166     fn deref(&self) -> &OsStr {
167         &self[..]
168     }
169 }
170
171 #[stable(feature = "osstring_default", since = "1.9.0")]
172 impl Default for OsString {
173     #[inline]
174     fn default() -> OsString {
175         OsString::new()
176     }
177 }
178
179 #[stable(feature = "rust1", since = "1.0.0")]
180 impl Debug for OsString {
181     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
182         fmt::Debug::fmt(&**self, formatter)
183     }
184 }
185
186 #[stable(feature = "rust1", since = "1.0.0")]
187 impl PartialEq for OsString {
188     fn eq(&self, other: &OsString) -> bool {
189         &**self == &**other
190     }
191 }
192
193 #[stable(feature = "rust1", since = "1.0.0")]
194 impl PartialEq<str> for OsString {
195     fn eq(&self, other: &str) -> bool {
196         &**self == other
197     }
198 }
199
200 #[stable(feature = "rust1", since = "1.0.0")]
201 impl PartialEq<OsString> for str {
202     fn eq(&self, other: &OsString) -> bool {
203         &**other == self
204     }
205 }
206
207 #[stable(feature = "rust1", since = "1.0.0")]
208 impl Eq for OsString {}
209
210 #[stable(feature = "rust1", since = "1.0.0")]
211 impl PartialOrd for OsString {
212     #[inline]
213     fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
214         (&**self).partial_cmp(&**other)
215     }
216     #[inline]
217     fn lt(&self, other: &OsString) -> bool { &**self < &**other }
218     #[inline]
219     fn le(&self, other: &OsString) -> bool { &**self <= &**other }
220     #[inline]
221     fn gt(&self, other: &OsString) -> bool { &**self > &**other }
222     #[inline]
223     fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
224 }
225
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl PartialOrd<str> for OsString {
228     #[inline]
229     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
230         (&**self).partial_cmp(other)
231     }
232 }
233
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl Ord for OsString {
236     #[inline]
237     fn cmp(&self, other: &OsString) -> cmp::Ordering {
238         (&**self).cmp(&**other)
239     }
240 }
241
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl Hash for OsString {
244     #[inline]
245     fn hash<H: Hasher>(&self, state: &mut H) {
246         (&**self).hash(state)
247     }
248 }
249
250 impl OsStr {
251     /// Coerces into an `OsStr` slice.
252     ///
253     /// # Examples
254     ///
255     /// ```
256     /// use std::ffi::OsStr;
257     ///
258     /// let os_str = OsStr::new("foo");
259     /// ```
260     #[stable(feature = "rust1", since = "1.0.0")]
261     pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
262         s.as_ref()
263     }
264
265     fn from_inner(inner: &Slice) -> &OsStr {
266         unsafe { mem::transmute(inner) }
267     }
268
269     /// Yields a `&str` slice if the `OsStr` is valid Unicode.
270     ///
271     /// This conversion may entail doing a check for UTF-8 validity.
272     #[stable(feature = "rust1", since = "1.0.0")]
273     pub fn to_str(&self) -> Option<&str> {
274         self.inner.to_str()
275     }
276
277     /// Converts an `OsStr` to a `Cow<str>`.
278     ///
279     /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
280     #[stable(feature = "rust1", since = "1.0.0")]
281     pub fn to_string_lossy(&self) -> Cow<str> {
282         self.inner.to_string_lossy()
283     }
284
285     /// Copies the slice into an owned `OsString`.
286     #[stable(feature = "rust1", since = "1.0.0")]
287     pub fn to_os_string(&self) -> OsString {
288         OsString { inner: self.inner.to_owned() }
289     }
290
291     /// Checks whether the `OsStr` is empty.
292     ///
293     /// # Examples
294     ///
295     /// ```
296     /// use std::ffi::OsStr;
297     ///
298     /// let os_str = OsStr::new("");
299     /// assert!(os_str.is_empty());
300     ///
301     /// let os_str = OsStr::new("foo");
302     /// assert!(!os_str.is_empty());
303     /// ```
304     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
305     pub fn is_empty(&self) -> bool {
306         self.inner.inner.is_empty()
307     }
308
309     /// Returns the length of this `OsStr`.
310     ///
311     /// Note that this does **not** return the number of bytes in this string
312     /// as, for example, OS strings on Windows are encoded as a list of `u16`
313     /// rather than a list of bytes. This number is simply useful for passing to
314     /// other methods like `OsString::with_capacity` to avoid reallocations.
315     ///
316     /// See `OsStr` introduction for more information about encoding.
317     ///
318     /// # Examples
319     ///
320     /// ```
321     /// use std::ffi::OsStr;
322     ///
323     /// let os_str = OsStr::new("");
324     /// assert_eq!(os_str.len(), 0);
325     ///
326     /// let os_str = OsStr::new("foo");
327     /// assert_eq!(os_str.len(), 3);
328     /// ```
329     #[stable(feature = "osstring_simple_functions", since = "1.9.0")]
330     pub fn len(&self) -> usize {
331         self.inner.inner.len()
332     }
333
334     /// Gets the underlying byte representation.
335     ///
336     /// Note: it is *crucial* that this API is private, to avoid
337     /// revealing the internal, platform-specific encodings.
338     fn bytes(&self) -> &[u8] {
339         unsafe { mem::transmute(&self.inner) }
340     }
341 }
342
343 #[stable(feature = "osstring_default", since = "1.9.0")]
344 impl<'a> Default for &'a OsStr {
345     #[inline]
346     fn default() -> &'a OsStr {
347         OsStr::new("")
348     }
349 }
350
351 #[stable(feature = "rust1", since = "1.0.0")]
352 impl PartialEq for OsStr {
353     fn eq(&self, other: &OsStr) -> bool {
354         self.bytes().eq(other.bytes())
355     }
356 }
357
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl PartialEq<str> for OsStr {
360     fn eq(&self, other: &str) -> bool {
361         *self == *OsStr::new(other)
362     }
363 }
364
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl PartialEq<OsStr> for str {
367     fn eq(&self, other: &OsStr) -> bool {
368         *other == *OsStr::new(self)
369     }
370 }
371
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl Eq for OsStr {}
374
375 #[stable(feature = "rust1", since = "1.0.0")]
376 impl PartialOrd for OsStr {
377     #[inline]
378     fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
379         self.bytes().partial_cmp(other.bytes())
380     }
381     #[inline]
382     fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
383     #[inline]
384     fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
385     #[inline]
386     fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
387     #[inline]
388     fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
389 }
390
391 #[stable(feature = "rust1", since = "1.0.0")]
392 impl PartialOrd<str> for OsStr {
393     #[inline]
394     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
395         self.partial_cmp(OsStr::new(other))
396     }
397 }
398
399 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
400 // have more flexible coherence rules.
401
402 #[stable(feature = "rust1", since = "1.0.0")]
403 impl Ord for OsStr {
404     #[inline]
405     fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
406 }
407
408 macro_rules! impl_cmp {
409     ($lhs:ty, $rhs: ty) => {
410         #[stable(feature = "cmp_os_str", since = "1.8.0")]
411         impl<'a, 'b> PartialEq<$rhs> for $lhs {
412             #[inline]
413             fn eq(&self, other: &$rhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
414         }
415
416         #[stable(feature = "cmp_os_str", since = "1.8.0")]
417         impl<'a, 'b> PartialEq<$lhs> for $rhs {
418             #[inline]
419             fn eq(&self, other: &$lhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
420         }
421
422         #[stable(feature = "cmp_os_str", since = "1.8.0")]
423         impl<'a, 'b> PartialOrd<$rhs> for $lhs {
424             #[inline]
425             fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
426                 <OsStr as PartialOrd>::partial_cmp(self, other)
427             }
428         }
429
430         #[stable(feature = "cmp_os_str", since = "1.8.0")]
431         impl<'a, 'b> PartialOrd<$lhs> for $rhs {
432             #[inline]
433             fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
434                 <OsStr as PartialOrd>::partial_cmp(self, other)
435             }
436         }
437     }
438 }
439
440 impl_cmp!(OsString, OsStr);
441 impl_cmp!(OsString, &'a OsStr);
442 impl_cmp!(Cow<'a, OsStr>, OsStr);
443 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
444 impl_cmp!(Cow<'a, OsStr>, OsString);
445
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl Hash for OsStr {
448     #[inline]
449     fn hash<H: Hasher>(&self, state: &mut H) {
450         self.bytes().hash(state)
451     }
452 }
453
454 #[stable(feature = "rust1", since = "1.0.0")]
455 impl Debug for OsStr {
456     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
457         self.inner.fmt(formatter)
458     }
459 }
460
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl Borrow<OsStr> for OsString {
463     fn borrow(&self) -> &OsStr { &self[..] }
464 }
465
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl ToOwned for OsStr {
468     type Owned = OsString;
469     fn to_owned(&self) -> OsString { self.to_os_string() }
470 }
471
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl AsRef<OsStr> for OsStr {
474     fn as_ref(&self) -> &OsStr {
475         self
476     }
477 }
478
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl AsRef<OsStr> for OsString {
481     fn as_ref(&self) -> &OsStr {
482         self
483     }
484 }
485
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl AsRef<OsStr> for str {
488     fn as_ref(&self) -> &OsStr {
489         OsStr::from_inner(Slice::from_str(self))
490     }
491 }
492
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl AsRef<OsStr> for String {
495     fn as_ref(&self) -> &OsStr {
496         (&**self).as_ref()
497     }
498 }
499
500 impl FromInner<Buf> for OsString {
501     fn from_inner(buf: Buf) -> OsString {
502         OsString { inner: buf }
503     }
504 }
505
506 impl IntoInner<Buf> for OsString {
507     fn into_inner(self) -> Buf {
508         self.inner
509     }
510 }
511
512 impl AsInner<Slice> for OsStr {
513     fn as_inner(&self) -> &Slice {
514         &self.inner
515     }
516 }
517
518 #[cfg(test)]
519 mod tests {
520     use super::*;
521     use sys_common::{AsInner, IntoInner};
522
523     #[test]
524     fn test_os_string_with_capacity() {
525         let os_string = OsString::with_capacity(0);
526         assert_eq!(0, os_string.inner.into_inner().capacity());
527
528         let os_string = OsString::with_capacity(10);
529         assert_eq!(10, os_string.inner.into_inner().capacity());
530
531         let mut os_string = OsString::with_capacity(0);
532         os_string.push("abc");
533         assert!(os_string.inner.into_inner().capacity() >= 3);
534     }
535
536     #[test]
537     fn test_os_string_clear() {
538         let mut os_string = OsString::from("abc");
539         assert_eq!(3, os_string.inner.as_inner().len());
540
541         os_string.clear();
542         assert_eq!(&os_string, "");
543         assert_eq!(0, os_string.inner.as_inner().len());
544     }
545
546     #[test]
547     fn test_os_string_capacity() {
548         let os_string = OsString::with_capacity(0);
549         assert_eq!(0, os_string.capacity());
550
551         let os_string = OsString::with_capacity(10);
552         assert_eq!(10, os_string.capacity());
553
554         let mut os_string = OsString::with_capacity(0);
555         os_string.push("abc");
556         assert!(os_string.capacity() >= 3);
557     }
558
559     #[test]
560     fn test_os_string_reserve() {
561         let mut os_string = OsString::new();
562         assert_eq!(os_string.capacity(), 0);
563
564         os_string.reserve(2);
565         assert!(os_string.capacity() >= 2);
566
567         for _ in 0..16 {
568             os_string.push("a");
569         }
570
571         assert!(os_string.capacity() >= 16);
572         os_string.reserve(16);
573         assert!(os_string.capacity() >= 32);
574
575         os_string.push("a");
576
577         os_string.reserve(16);
578         assert!(os_string.capacity() >= 33)
579     }
580
581     #[test]
582     fn test_os_string_reserve_exact() {
583         let mut os_string = OsString::new();
584         assert_eq!(os_string.capacity(), 0);
585
586         os_string.reserve_exact(2);
587         assert!(os_string.capacity() >= 2);
588
589         for _ in 0..16 {
590             os_string.push("a");
591         }
592
593         assert!(os_string.capacity() >= 16);
594         os_string.reserve_exact(16);
595         assert!(os_string.capacity() >= 32);
596
597         os_string.push("a");
598
599         os_string.reserve_exact(16);
600         assert!(os_string.capacity() >= 33)
601     }
602
603     #[test]
604     fn test_os_string_default() {
605         let os_string: OsString = Default::default();
606         assert_eq!("", &os_string);
607     }
608
609     #[test]
610     fn test_os_str_is_empty() {
611         let mut os_string = OsString::new();
612         assert!(os_string.is_empty());
613
614         os_string.push("abc");
615         assert!(!os_string.is_empty());
616
617         os_string.clear();
618         assert!(os_string.is_empty());
619     }
620
621     #[test]
622     fn test_os_str_len() {
623         let mut os_string = OsString::new();
624         assert_eq!(0, os_string.len());
625
626         os_string.push("abc");
627         assert_eq!(3, os_string.len());
628
629         os_string.clear();
630         assert_eq!(0, os_string.len());
631     }
632
633     #[test]
634     fn test_os_str_default() {
635         let os_str: &OsStr = Default::default();
636         assert_eq!("", os_str);
637     }
638 }