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
use std::slice::{Iter, IterMut};
use std::vec::IntoIter;

#[derive(Default)]
pub struct VecMap<K, V> {
	v: Vec<(K, V)>
}

impl<K: Eq, V> VecMap<K, V> {
	pub fn new() -> Self {
		VecMap { v: Vec::new() }
	}

	pub fn with_capacity(size: usize) -> Self {
		VecMap { v: Vec::with_capacity(size) }
	}

	pub fn from_vec(v: Vec<(K, V)>) -> Self {
		VecMap { v: v }
	}

	pub fn to_vec(self) -> Vec<(K, V)> {
		self.v
	}

	pub fn capacity(&self) -> usize {
		self.v.capacity()
	}

	pub fn reserve(&mut self, additional: usize) {
		self.v.reserve(additional)
	}

	pub fn shrink_to_fit(&mut self) {
		self.v.shrink_to_fit()
	}

	pub fn iter(&self) -> Iter<(K, V)> {
		self.v.iter()
	}

	pub fn iter_mut(&mut self) -> IterMut<(K, V)> {
		self.v.iter_mut()
	}

	pub fn into_iter(self) -> IntoIter<(K, V)> {
		self.v.into_iter()
	}

	pub fn contains_key(&mut self, x: &K) -> bool {
		self.v.iter().any(|&(ref k, _)| x == k)
	}

	pub fn insert(&mut self, k: K, v: V) -> Option<V> {
		use std::mem::replace;
		for &mut (ref mut vk, ref mut vv) in self.v.iter_mut() {
			if k == *vk {
				return Some(replace(vv, v))
			}
		}
		self.v.push((k, v));
		None
	}

	pub fn remove(&mut self, k: &K) -> bool {
		let mut idx = None;
		for (i, v) in self.v.iter().enumerate() {
			if &v.0 == k {
				idx = Some(i);
				break
			}
		}
		match idx {
			None => false,
			Some(idx) => {
				self.v.swap_remove(idx);
				true
			}
		}
	}

	pub fn clear(&mut self) {
		self.v.clear()
	}
}

impl<K: Eq, V: PartialEq> VecMap<K, V> {
	pub fn contains_value(&mut self, x: &V) -> bool {
		self.v.iter().any(|&(_, ref v)| x == v)
	}

}