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.
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.
11 use borrow::{Borrow, Cow, ToOwned};
12 use fmt::{self, Debug};
17 use hash::{Hash, Hasher};
20 use sys::os_str::{Buf, Slice};
21 use sys_common::{AsInner, IntoInner, FromInner};
23 /// A type that can represent owned, mutable platform-native strings, but is
24 /// cheaply inter-convertible with Rust strings.
26 /// The need for this type arises from the fact that:
28 /// * On Unix systems, strings are often arbitrary sequences of non-zero
29 /// bytes, in many cases interpreted as UTF-8.
31 /// * On Windows, strings are often arbitrary sequences of non-zero 16-bit
32 /// values, interpreted as UTF-16 when it is valid to do so.
34 /// * In Rust, strings are always valid UTF-8, but may contain zeros.
36 /// `OsString` and `OsStr` bridge this gap by simultaneously representing Rust
37 /// and platform-native string values, and in particular allowing a Rust string
38 /// to be converted into an "OS" string with no cost.
40 #[stable(feature = "rust1", since = "1.0.0")]
45 /// Slices into OS strings (see `OsString`).
46 #[stable(feature = "rust1", since = "1.0.0")]
52 /// Constructs a new empty `OsString`.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub fn new() -> OsString {
55 OsString { inner: Buf::from_string(String::new()) }
59 fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
60 use os::unix::ffi::OsStringExt;
61 Some(OsString::from_vec(vec))
65 fn _from_bytes(vec: Vec<u8>) -> Option<OsString> {
66 String::from_utf8(vec).ok().map(OsString::from)
69 /// Converts to an `OsStr` slice.
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub fn as_os_str(&self) -> &OsStr {
75 /// Converts the `OsString` into a `String` if it contains valid Unicode data.
77 /// On failure, ownership of the original `OsString` is returned.
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub fn into_string(self) -> Result<String, OsString> {
80 self.inner.into_string().map_err(|buf| OsString { inner: buf} )
83 /// Extends the string with the given `&OsStr` slice.
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub fn push<T: AsRef<OsStr>>(&mut self, s: T) {
86 self.inner.push_slice(&s.as_ref().inner)
89 /// Creates a new `OsString` with the given capacity. The string will be
90 /// able to hold exactly `capacity` bytes without reallocating. If
91 /// `capacity` is 0, the string will not allocate.
93 /// See main `OsString` documentation information about encoding.
94 #[unstable(feature = "osstring_simple_functions",
95 reason = "recently added", issue = "29453")]
96 pub fn with_capacity(capacity: usize) -> OsString {
98 inner: Buf::with_capacity(capacity)
102 /// Truncates the `OsString` to zero length.
103 #[unstable(feature = "osstring_simple_functions",
104 reason = "recently added", issue = "29453")]
105 pub fn clear(&mut self) {
109 /// Returns the number of bytes this `OsString` can hold without
112 /// See `OsString` introduction for information about encoding.
113 #[unstable(feature = "osstring_simple_functions",
114 reason = "recently added", issue = "29453")]
115 pub fn capacity(&self) -> usize {
116 self.inner.capacity()
119 /// Reserves capacity for at least `additional` more bytes to be inserted
120 /// in the given `OsString`. The collection may reserve more space to avoid
121 /// frequent reallocations.
122 #[unstable(feature = "osstring_simple_functions",
123 reason = "recently added", issue = "29453")]
124 pub fn reserve(&mut self, additional: usize) {
125 self.inner.reserve(additional)
128 /// Reserves the minimum capacity for exactly `additional` more bytes to be
129 /// inserted in the given `OsString`. Does nothing if the capacity is
130 /// already sufficient.
132 /// Note that the allocator may give the collection more space than it
133 /// requests. Therefore capacity can not be relied upon to be precisely
134 /// minimal. Prefer reserve if future insertions are expected.
135 #[unstable(feature = "osstring_simple_functions",
136 reason = "recently added", issue = "29453")]
137 pub fn reserve_exact(&mut self, additional: usize) {
138 self.inner.reserve_exact(additional)
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl From<String> for OsString {
144 fn from(s: String) -> OsString {
145 OsString { inner: Buf::from_string(s) }
149 #[stable(feature = "rust1", since = "1.0.0")]
150 impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for OsString {
151 fn from(s: &'a T) -> OsString {
152 s.as_ref().to_os_string()
156 #[stable(feature = "rust1", since = "1.0.0")]
157 impl ops::Index<ops::RangeFull> for OsString {
161 fn index(&self, _index: ops::RangeFull) -> &OsStr {
162 OsStr::from_inner(self.inner.as_slice())
166 #[stable(feature = "rust1", since = "1.0.0")]
167 impl ops::Deref for OsString {
171 fn deref(&self) -> &OsStr {
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl Debug for OsString {
178 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
179 fmt::Debug::fmt(&**self, formatter)
183 #[stable(feature = "rust1", since = "1.0.0")]
184 impl PartialEq for OsString {
185 fn eq(&self, other: &OsString) -> bool {
190 #[stable(feature = "rust1", since = "1.0.0")]
191 impl PartialEq<str> for OsString {
192 fn eq(&self, other: &str) -> bool {
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl PartialEq<OsString> for str {
199 fn eq(&self, other: &OsString) -> bool {
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl Eq for OsString {}
207 #[stable(feature = "rust1", since = "1.0.0")]
208 impl PartialOrd for OsString {
210 fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
211 (&**self).partial_cmp(&**other)
214 fn lt(&self, other: &OsString) -> bool { &**self < &**other }
216 fn le(&self, other: &OsString) -> bool { &**self <= &**other }
218 fn gt(&self, other: &OsString) -> bool { &**self > &**other }
220 fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
223 #[stable(feature = "rust1", since = "1.0.0")]
224 impl PartialOrd<str> for OsString {
226 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
227 (&**self).partial_cmp(other)
231 #[stable(feature = "rust1", since = "1.0.0")]
232 impl Ord for OsString {
234 fn cmp(&self, other: &OsString) -> cmp::Ordering {
235 (&**self).cmp(&**other)
239 #[stable(feature = "rust1", since = "1.0.0")]
240 impl Hash for OsString {
242 fn hash<H: Hasher>(&self, state: &mut H) {
243 (&**self).hash(state)
248 /// Coerces into an `OsStr` slice.
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &OsStr {
254 fn from_inner(inner: &Slice) -> &OsStr {
255 unsafe { mem::transmute(inner) }
258 /// Yields a `&str` slice if the `OsStr` is valid Unicode.
260 /// This conversion may entail doing a check for UTF-8 validity.
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn to_str(&self) -> Option<&str> {
266 /// Converts an `OsStr` to a `Cow<str>`.
268 /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub fn to_string_lossy(&self) -> Cow<str> {
271 self.inner.to_string_lossy()
274 /// Copies the slice into an owned `OsString`.
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub fn to_os_string(&self) -> OsString {
277 OsString { inner: self.inner.to_owned() }
280 /// Checks whether the `OsStr` is empty.
281 #[unstable(feature = "osstring_simple_functions",
282 reason = "recently added", issue = "29453")]
283 pub fn is_empty(&self) -> bool {
284 self.inner.inner.is_empty()
287 /// Returns the number of bytes in this `OsStr`.
289 /// See `OsStr` introduction for information about encoding.
290 #[unstable(feature = "osstring_simple_functions",
291 reason = "recently added", issue = "29453")]
292 pub fn len(&self) -> usize {
293 self.inner.inner.len()
296 /// Gets the underlying byte representation.
298 /// Note: it is *crucial* that this API is private, to avoid
299 /// revealing the internal, platform-specific encodings.
300 fn bytes(&self) -> &[u8] {
301 unsafe { mem::transmute(&self.inner) }
305 #[stable(feature = "rust1", since = "1.0.0")]
306 impl PartialEq for OsStr {
307 fn eq(&self, other: &OsStr) -> bool {
308 self.bytes().eq(other.bytes())
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl PartialEq<str> for OsStr {
314 fn eq(&self, other: &str) -> bool {
315 *self == *OsStr::new(other)
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl PartialEq<OsStr> for str {
321 fn eq(&self, other: &OsStr) -> bool {
322 *other == *OsStr::new(self)
326 #[stable(feature = "rust1", since = "1.0.0")]
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl PartialOrd for OsStr {
332 fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
333 self.bytes().partial_cmp(other.bytes())
336 fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
338 fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
340 fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
342 fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl PartialOrd<str> for OsStr {
348 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
349 self.partial_cmp(OsStr::new(other))
353 // FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
354 // have more flexible coherence rules.
356 #[stable(feature = "rust1", since = "1.0.0")]
359 fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
362 macro_rules! impl_cmp {
363 ($lhs:ty, $rhs: ty) => {
364 #[stable(feature = "cmp_os_str", since = "1.8.0")]
365 impl<'a, 'b> PartialEq<$rhs> for $lhs {
367 fn eq(&self, other: &$rhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
370 #[stable(feature = "cmp_os_str", since = "1.8.0")]
371 impl<'a, 'b> PartialEq<$lhs> for $rhs {
373 fn eq(&self, other: &$lhs) -> bool { <OsStr as PartialEq>::eq(self, other) }
376 #[stable(feature = "cmp_os_str", since = "1.8.0")]
377 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
379 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
380 <OsStr as PartialOrd>::partial_cmp(self, other)
384 #[stable(feature = "cmp_os_str", since = "1.8.0")]
385 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
387 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
388 <OsStr as PartialOrd>::partial_cmp(self, other)
394 impl_cmp!(OsString, OsStr);
395 impl_cmp!(OsString, &'a OsStr);
396 impl_cmp!(Cow<'a, OsStr>, OsStr);
397 impl_cmp!(Cow<'a, OsStr>, &'b OsStr);
398 impl_cmp!(Cow<'a, OsStr>, OsString);
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl Hash for OsStr {
403 fn hash<H: Hasher>(&self, state: &mut H) {
404 self.bytes().hash(state)
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl Debug for OsStr {
410 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
411 self.inner.fmt(formatter)
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl Borrow<OsStr> for OsString {
417 fn borrow(&self) -> &OsStr { &self[..] }
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl ToOwned for OsStr {
422 type Owned = OsString;
423 fn to_owned(&self) -> OsString { self.to_os_string() }
426 #[stable(feature = "rust1", since = "1.0.0")]
427 impl AsRef<OsStr> for OsStr {
428 fn as_ref(&self) -> &OsStr {
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl AsRef<OsStr> for OsString {
435 fn as_ref(&self) -> &OsStr {
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl AsRef<OsStr> for str {
442 fn as_ref(&self) -> &OsStr {
443 OsStr::from_inner(Slice::from_str(self))
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl AsRef<OsStr> for String {
449 fn as_ref(&self) -> &OsStr {
454 impl FromInner<Buf> for OsString {
455 fn from_inner(buf: Buf) -> OsString {
456 OsString { inner: buf }
460 impl IntoInner<Buf> for OsString {
461 fn into_inner(self) -> Buf {
466 impl AsInner<Slice> for OsStr {
467 fn as_inner(&self) -> &Slice {
475 use sys_common::{AsInner, IntoInner};
478 fn test_os_string_with_capacity() {
479 let os_string = OsString::with_capacity(0);
480 assert_eq!(0, os_string.inner.into_inner().capacity());
482 let os_string = OsString::with_capacity(10);
483 assert_eq!(10, os_string.inner.into_inner().capacity());
485 let mut os_string = OsString::with_capacity(0);
486 os_string.push("abc");
487 assert!(os_string.inner.into_inner().capacity() >= 3);
491 fn test_os_string_clear() {
492 let mut os_string = OsString::from("abc");
493 assert_eq!(3, os_string.inner.as_inner().len());
496 assert_eq!(&os_string, "");
497 assert_eq!(0, os_string.inner.as_inner().len());
501 fn test_os_string_capacity() {
502 let os_string = OsString::with_capacity(0);
503 assert_eq!(0, os_string.capacity());
505 let os_string = OsString::with_capacity(10);
506 assert_eq!(10, os_string.capacity());
508 let mut os_string = OsString::with_capacity(0);
509 os_string.push("abc");
510 assert!(os_string.capacity() >= 3);
514 fn test_os_string_reserve() {
515 let mut os_string = OsString::new();
516 assert_eq!(os_string.capacity(), 0);
518 os_string.reserve(2);
519 assert!(os_string.capacity() >= 2);
525 assert!(os_string.capacity() >= 16);
526 os_string.reserve(16);
527 assert!(os_string.capacity() >= 32);
531 os_string.reserve(16);
532 assert!(os_string.capacity() >= 33)
536 fn test_os_string_reserve_exact() {
537 let mut os_string = OsString::new();
538 assert_eq!(os_string.capacity(), 0);
540 os_string.reserve_exact(2);
541 assert!(os_string.capacity() >= 2);
547 assert!(os_string.capacity() >= 16);
548 os_string.reserve_exact(16);
549 assert!(os_string.capacity() >= 32);
553 os_string.reserve_exact(16);
554 assert!(os_string.capacity() >= 33)
558 fn test_os_str_is_empty() {
559 let mut os_string = OsString::new();
560 assert!(os_string.is_empty());
562 os_string.push("abc");
563 assert!(!os_string.is_empty());
566 assert!(os_string.is_empty());
570 fn test_os_str_len() {
571 let mut os_string = OsString::new();
572 assert_eq!(0, os_string.len());
574 os_string.push("abc");
575 assert_eq!(3, os_string.len());
578 assert_eq!(0, os_string.len());