]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/os_str.rs
Auto merge of #20373 - huonw:self-call-lint, r=luqmana
[rust.git] / src / libstd / sys / unix / 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 /// The underlying OsString/OsStr implementation on Unix systems: just
12 /// a `Vec<u8>`/`[u8]`.
13
14 use core::prelude::*;
15
16 use fmt::{self, Debug};
17 use vec::Vec;
18 use slice::SliceExt as StdSliceExt;
19 use str;
20 use string::{String, CowString};
21 use mem;
22
23 #[derive(Clone)]
24 pub struct Buf {
25     pub inner: Vec<u8>
26 }
27
28 pub struct Slice {
29     pub inner: [u8]
30 }
31
32 impl Debug for Slice {
33     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
34         self.to_string_lossy().fmt(formatter)
35     }
36 }
37
38 impl Debug for Buf {
39     fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
40         self.as_slice().fmt(formatter)
41     }
42 }
43
44 impl Buf {
45     pub fn from_string(s: String) -> Buf {
46         Buf { inner: s.into_bytes() }
47     }
48
49     pub fn from_str(s: &str) -> Buf {
50         Buf { inner: s.as_bytes().to_vec() }
51     }
52
53     pub fn as_slice(&self) -> &Slice {
54         unsafe { mem::transmute(self.inner.as_slice()) }
55     }
56
57     pub fn into_string(self) -> Result<String, Buf> {
58         String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } )
59     }
60
61     pub fn push_slice(&mut self, s: &Slice) {
62         self.inner.push_all(&s.inner)
63     }
64 }
65
66 impl Slice {
67     fn from_u8_slice(s: &[u8]) -> &Slice {
68         unsafe { mem::transmute(s) }
69     }
70
71     pub fn from_str(s: &str) -> &Slice {
72         unsafe { mem::transmute(s.as_bytes()) }
73     }
74
75     pub fn to_str(&self) -> Option<&str> {
76         str::from_utf8(&self.inner).ok()
77     }
78
79     pub fn to_string_lossy(&self) -> CowString {
80         String::from_utf8_lossy(&self.inner)
81     }
82
83     pub fn to_owned(&self) -> Buf {
84         Buf { inner: self.inner.to_vec() }
85     }
86 }