]>
Commit | Line | Data |
---|---|---|
85aaf69f SL |
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 | /// The underlying OsString/OsStr implementation on Unix systems: just | |
12 | /// a `Vec<u8>`/`[u8]`. | |
13 | ||
c34b1796 | 14 | use borrow::Cow; |
85aaf69f SL |
15 | use fmt::{self, Debug}; |
16 | use vec::Vec; | |
85aaf69f | 17 | use str; |
c34b1796 | 18 | use string::String; |
85aaf69f SL |
19 | use mem; |
20 | ||
21 | #[derive(Clone, Hash)] | |
22 | pub struct Buf { | |
23 | pub inner: Vec<u8> | |
24 | } | |
25 | ||
26 | pub struct Slice { | |
27 | pub inner: [u8] | |
28 | } | |
29 | ||
30 | impl Debug for Slice { | |
31 | fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { | |
32 | self.to_string_lossy().fmt(formatter) | |
33 | } | |
34 | } | |
35 | ||
36 | impl Debug for Buf { | |
37 | fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { | |
38 | self.as_slice().fmt(formatter) | |
39 | } | |
40 | } | |
41 | ||
42 | impl Buf { | |
43 | pub fn from_string(s: String) -> Buf { | |
44 | Buf { inner: s.into_bytes() } | |
45 | } | |
46 | ||
85aaf69f SL |
47 | pub fn as_slice(&self) -> &Slice { |
48 | unsafe { mem::transmute(&*self.inner) } | |
49 | } | |
50 | ||
51 | pub fn into_string(self) -> Result<String, Buf> { | |
52 | String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } ) | |
53 | } | |
54 | ||
55 | pub fn push_slice(&mut self, s: &Slice) { | |
92a42be0 | 56 | self.inner.extend_from_slice(&s.inner) |
85aaf69f SL |
57 | } |
58 | } | |
59 | ||
60 | impl Slice { | |
61 | fn from_u8_slice(s: &[u8]) -> &Slice { | |
62 | unsafe { mem::transmute(s) } | |
63 | } | |
64 | ||
65 | pub fn from_str(s: &str) -> &Slice { | |
c34b1796 | 66 | Slice::from_u8_slice(s.as_bytes()) |
85aaf69f SL |
67 | } |
68 | ||
69 | pub fn to_str(&self) -> Option<&str> { | |
70 | str::from_utf8(&self.inner).ok() | |
71 | } | |
72 | ||
c34b1796 | 73 | pub fn to_string_lossy(&self) -> Cow<str> { |
85aaf69f SL |
74 | String::from_utf8_lossy(&self.inner) |
75 | } | |
76 | ||
77 | pub fn to_owned(&self) -> Buf { | |
78 | Buf { inner: self.inner.to_vec() } | |
79 | } | |
80 | } |