]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/owned_slice.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / libsyntax / owned_slice.rs
1 // Copyright 2014 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 std::default::Default;
12 use std::fmt;
13 use std::iter::FromIterator;
14 use std::ops::Deref;
15 use std::vec;
16 use serialize::{Encodable, Decodable, Encoder, Decoder};
17
18 /// A non-growable owned slice. This is a separate type to allow the
19 /// representation to change.
20 #[derive(Hash, PartialEq, Eq, PartialOrd, Ord)]
21 pub struct OwnedSlice<T> {
22     data: Box<[T]>
23 }
24
25 impl<T:fmt::Debug> fmt::Debug for OwnedSlice<T> {
26     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
27         self.data.fmt(fmt)
28     }
29 }
30
31 impl<T> OwnedSlice<T> {
32     pub fn empty() -> OwnedSlice<T> {
33         OwnedSlice  { data: box [] }
34     }
35
36     #[inline(never)]
37     pub fn from_vec(v: Vec<T>) -> OwnedSlice<T> {
38         OwnedSlice { data: v.into_boxed_slice() }
39     }
40
41     #[inline(never)]
42     pub fn into_vec(self) -> Vec<T> {
43         self.data.into_vec()
44     }
45
46     pub fn as_slice<'a>(&'a self) -> &'a [T] {
47         &*self.data
48     }
49
50     pub fn move_iter(self) -> vec::IntoIter<T> {
51         self.into_vec().into_iter()
52     }
53
54     pub fn map<U, F: FnMut(&T) -> U>(&self, f: F) -> OwnedSlice<U> {
55         self.iter().map(f).collect()
56     }
57 }
58
59 impl<T> Deref for OwnedSlice<T> {
60     type Target = [T];
61
62     fn deref(&self) -> &[T] {
63         self.as_slice()
64     }
65 }
66
67 impl<T> Default for OwnedSlice<T> {
68     fn default() -> OwnedSlice<T> {
69         OwnedSlice::empty()
70     }
71 }
72
73 impl<T: Clone> Clone for OwnedSlice<T> {
74     fn clone(&self) -> OwnedSlice<T> {
75         OwnedSlice::from_vec(self.to_vec())
76     }
77 }
78
79 impl<T> FromIterator<T> for OwnedSlice<T> {
80     fn from_iter<I: Iterator<Item=T>>(iter: I) -> OwnedSlice<T> {
81         OwnedSlice::from_vec(iter.collect())
82     }
83 }
84
85 impl<T: Encodable> Encodable for OwnedSlice<T> {
86     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
87         Encodable::encode(&**self, s)
88     }
89 }
90
91 impl<T: Decodable> Decodable for OwnedSlice<T> {
92     fn decode<D: Decoder>(d: &mut D) -> Result<OwnedSlice<T>, D::Error> {
93         Ok(OwnedSlice::from_vec(match Decodable::decode(d) {
94             Ok(t) => t,
95             Err(e) => return Err(e)
96         }))
97     }
98 }