about summary refs log tree commit diff
path: root/src/libsyntax/opt_vec.rs
blob: 21f05fa684a844ff061514899ec1567dcc9e6b7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!
 * Defines a type OptVec<T> that can be used in place of ~[T].
 * OptVec avoids the need for allocation for empty vectors.
 * OptVec implements the iterable interface as well as
 * other useful things like `push()` and `len()`.
 */

use std::vec;

#[deriving(Clone, Encodable, Decodable, IterBytes)]
pub enum OptVec<T> {
    Empty,
    Vec(~[T])
}

pub fn with<T>(t: T) -> OptVec<T> {
    Vec(~[t])
}

pub fn from<T>(t: ~[T]) -> OptVec<T> {
    if t.len() == 0 {
        Empty
    } else {
        Vec(t)
    }
}

impl<T> OptVec<T> {
    pub fn push(&mut self, t: T) {
        match *self {
            Vec(ref mut v) => {
                v.push(t);
                return;
            }
            Empty => {
                *self = Vec(~[t]);
            }
        }
    }

    pub fn pop(&mut self) -> Option<T> {
        match *self {
            Vec(ref mut v) => v.pop(),
            Empty => None
        }
    }

    pub fn last<'a>(&'a self) -> Option<&'a T> {
        match *self {
            Vec(ref v) => v.last(),
            Empty => None
        }
    }

    pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
        match *self {
            Vec(ref mut v) => v.mut_last(),
            Empty => None
        }
    }

    pub fn map<U>(&self, op: |&T| -> U) -> OptVec<U> {
        match *self {
            Empty => Empty,
            Vec(ref v) => Vec(v.map(op))
        }
    }

    pub fn map_move<U>(self, op: |T| -> U) -> OptVec<U> {
        match self {
            Empty => Empty,
            Vec(v) => Vec(v.move_iter().map(op).collect())
        }
    }

    pub fn get<'a>(&'a self, i: uint) -> &'a T {
        match *self {
            Empty => fail!("invalid index {}", i),
            Vec(ref v) => &v[i]
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn len(&self) -> uint {
        match *self {
            Empty => 0,
            Vec(ref v) => v.len()
        }
    }

    pub fn swap_remove(&mut self, index: uint) {
        match *self {
            Empty => { fail!("index out of bounds"); }
            Vec(ref mut v) => {
                assert!(index < v.len());
                v.swap_remove(index);
            }
        }
    }

    #[inline]
    pub fn iter<'r>(&'r self) -> Items<'r, T> {
        match *self {
            Empty => Items{iter: None},
            Vec(ref v) => Items{iter: Some(v.iter())}
        }
    }

    #[inline]
    pub fn map_to_vec<B>(&self, op: |&T| -> B) -> ~[B] {
        self.iter().map(op).collect()
    }

    pub fn mapi_to_vec<B>(&self, op: |uint, &T| -> B) -> ~[B] {
        let mut index = 0;
        self.map_to_vec(|a| {
            let i = index;
            index += 1;
            op(i, a)
        })
    }
}

pub fn take_vec<T>(v: OptVec<T>) -> ~[T] {
    match v {
        Empty => ~[],
        Vec(v) => v
    }
}

impl<T:Clone> OptVec<T> {
    pub fn prepend(&self, t: T) -> OptVec<T> {
        let mut v0 = ~[t];
        match *self {
            Empty => {}
            Vec(ref v1) => { v0.push_all(*v1); }
        }
        return Vec(v0);
    }
}

impl<A:Eq> Eq for OptVec<A> {
    fn eq(&self, other: &OptVec<A>) -> bool {
        // Note: cannot use #[deriving(Eq)] here because
        // (Empty, Vec(~[])) ought to be equal.
        match (self, other) {
            (&Empty, &Empty) => true,
            (&Empty, &Vec(ref v)) => v.is_empty(),
            (&Vec(ref v), &Empty) => v.is_empty(),
            (&Vec(ref v1), &Vec(ref v2)) => *v1 == *v2
        }
    }

    fn ne(&self, other: &OptVec<A>) -> bool {
        !self.eq(other)
    }
}

impl<T> Default for OptVec<T> {
    fn default() -> OptVec<T> { Empty }
}

pub struct Items<'a, T> {
    priv iter: Option<vec::Items<'a, T>>
}

impl<'a, T> Iterator<&'a T> for Items<'a, T> {
    #[inline]
    fn next(&mut self) -> Option<&'a T> {
        match self.iter {
            Some(ref mut x) => x.next(),
            None => None
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        match self.iter {
            Some(ref x) => x.size_hint(),
            None => (0, Some(0))
        }
    }
}

impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a T> {
        match self.iter {
            Some(ref mut x) => x.next_back(),
            None => None
        }
    }
}

impl<A> FromIterator<A> for OptVec<A> {
    fn from_iterator<T: Iterator<A>>(iterator: &mut T) -> OptVec<A> {
        let mut r = Empty;
        for x in *iterator {
            r.push(x);
        }
        r
    }
}