1 // Copyright 2012 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.
12 * Defines a type OptVec<T> that can be used in place of ~[T].
13 * OptVec avoids the need for allocation for empty vectors.
14 * OptVec implements the iterable interface as well as
15 * other useful things like `push()` and `len()`.
18 use std::vec::{VecIterator};
20 #[deriving(Clone, Encodable, Decodable, IterBytes)]
26 pub fn with<T>(t: T) -> OptVec<T> {
30 pub fn from<T>(t: ~[T]) -> OptVec<T> {
39 fn push(&mut self, t: T) {
48 // FIXME(#5074): flow insensitive means we can't move
49 // assignment inside `match`
53 fn map<U>(&self, op: &fn(&T) -> U) -> OptVec<U> {
56 Vec(ref v) => Vec(v.map(op))
60 fn map_move<U>(self, op: &fn(T) -> U) -> OptVec<U> {
63 Vec(v) => Vec(v.move_iter().map(op).collect())
67 fn get<'a>(&'a self, i: uint) -> &'a T {
69 Empty => fail!("Invalid index %u", i),
74 fn is_empty(&self) -> bool {
78 fn len(&self) -> uint {
86 fn iter<'r>(&'r self) -> OptVecIterator<'r, T> {
88 Empty => OptVecIterator{iter: None},
89 Vec(ref v) => OptVecIterator{iter: Some(v.iter())}
94 fn map_to_vec<B>(&self, op: &fn(&T) -> B) -> ~[B] {
95 self.iter().map(op).collect()
98 fn mapi_to_vec<B>(&self, op: &fn(uint, &T) -> B) -> ~[B] {
100 self.map_to_vec(|a| {
108 pub fn take_vec<T>(v: OptVec<T>) -> ~[T] {
115 impl<T:Clone> OptVec<T> {
116 fn prepend(&self, t: T) -> OptVec<T> {
120 Vec(ref v1) => { v0.push_all(*v1); }
126 impl<A:Eq> Eq for OptVec<A> {
127 fn eq(&self, other: &OptVec<A>) -> bool {
128 // Note: cannot use #[deriving(Eq)] here because
129 // (Empty, Vec(~[])) ought to be equal.
130 match (self, other) {
131 (&Empty, &Empty) => true,
132 (&Empty, &Vec(ref v)) => v.is_empty(),
133 (&Vec(ref v), &Empty) => v.is_empty(),
134 (&Vec(ref v1), &Vec(ref v2)) => *v1 == *v2
138 fn ne(&self, other: &OptVec<A>) -> bool {
143 pub struct OptVecIterator<'self, T> {
144 priv iter: Option<VecIterator<'self, T>>
147 impl<'self, T> Iterator<&'self T> for OptVecIterator<'self, T> {
149 fn next(&mut self) -> Option<&'self T> {
151 Some(ref mut x) => x.next(),
157 fn size_hint(&self) -> (uint, Option<uint>) {
159 Some(ref x) => x.size_hint(),