#![allow(missing_docs)]
use self::Entry::*;
use std::cmp::max;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::{Enumerate, FilterMap, Map, FromIterator};
use std::mem::{replace, swap};
use std::ops::{Index, IndexMut};
use std::vec::{self, Vec};
use std::slice;
pub struct VecMap<V> {
v: Vec<Option<V>>,
}
pub enum Entry<'a, V:'a> {
Vacant(VacantEntry<'a, V>),
Occupied(OccupiedEntry<'a, V>),
}
pub struct VacantEntry<'a, V:'a> {
map: &'a mut VecMap<V>,
index: usize,
}
pub struct OccupiedEntry<'a, V:'a> {
map: &'a mut VecMap<V>,
index: usize,
}
impl<V> Default for VecMap<V> {
#[inline]
fn default() -> VecMap<V> { VecMap::new() }
}
impl<V:Clone> Clone for VecMap<V> {
#[inline]
fn clone(&self) -> VecMap<V> {
VecMap { v: self.v.clone() }
}
#[inline]
fn clone_from(&mut self, source: &VecMap<V>) {
self.v.clone_from(&source.v);
}
}
impl<V: Hash> Hash for VecMap<V> {
fn hash<H: Hasher>(&self, state: &mut H) {
let mut count: usize = 0;
for elt in self {
elt.hash(state);
count += 1;
}
count.hash(state);
}
}
impl<V> VecMap<V> {
pub fn new() -> VecMap<V> { VecMap { v: vec![] } }
pub fn with_capacity(capacity: usize) -> VecMap<V> {
VecMap { v: Vec::with_capacity(capacity) }
}
#[inline]
pub fn capacity(&self) -> usize {
self.v.capacity()
}
pub fn reserve_len(&mut self, len: usize) {
let cur_len = self.v.len();
if len >= cur_len {
self.v.reserve(len - cur_len);
}
}
pub fn reserve_len_exact(&mut self, len: usize) {
let cur_len = self.v.len();
if len >= cur_len {
self.v.reserve_exact(len - cur_len);
}
}
pub fn keys<'r>(&'r self) -> Keys<'r, V> {
fn first<A, B>((a, _): (A, B)) -> A { a }
let first: fn((usize, &'r V)) -> usize = first;
Keys { iter: self.iter().map(first) }
}
pub fn values<'r>(&'r self) -> Values<'r, V> {
fn second<A, B>((_, b): (A, B)) -> B { b }
let second: fn((usize, &'r V)) -> &'r V = second;
Values { iter: self.iter().map(second) }
}
pub fn iter<'r>(&'r self) -> Iter<'r, V> {
Iter {
front: 0,
back: self.v.len(),
iter: self.v.iter()
}
}
pub fn iter_mut<'r>(&'r mut self) -> IterMut<'r, V> {
IterMut {
front: 0,
back: self.v.len(),
iter: self.v.iter_mut()
}
}
pub fn split_off(&mut self, at: usize) -> Self {
let mut other = VecMap::new();
if at == 0 {
swap(self, &mut other);
return other
} else if at > self.v.len() {
return other;
}
let first_index = self.v.iter().position(|el| el.is_some());
let start_index = match first_index {
Some(index) => max(at, index),
None => {
return other;
}
};
other.v.extend((0..start_index).map(|_| None));
other.v.extend(self.v[start_index..].iter_mut().map(|el| el.take()));
other
}
pub fn len(&self) -> usize {
self.v.iter().filter(|elt| elt.is_some()).count()
}
pub fn is_empty(&self) -> bool {
self.v.iter().all(|elt| elt.is_none())
}
pub fn clear(&mut self) { self.v.clear() }
pub fn get(&self, key: &usize) -> Option<&V> {
if *key < self.v.len() {
match self.v[*key] {
Some(ref value) => Some(value),
None => None
}
} else {
None
}
}
#[inline]
pub fn contains_key(&self, key: &usize) -> bool {
self.get(key).is_some()
}
pub fn get_mut(&mut self, key: &usize) -> Option<&mut V> {
if *key < self.v.len() {
match *(&mut self.v[*key]) {
Some(ref mut value) => Some(value),
None => None
}
} else {
None
}
}
pub fn insert(&mut self, key: usize, value: V) -> Option<V> {
let len = self.v.len();
if len <= key {
self.v.extend((0..key - len + 1).map(|_| None));
}
replace(&mut self.v[key], Some(value))
}
pub fn remove(&mut self, key: &usize) -> Option<V> {
if *key >= self.v.len() {
return None;
}
let result = &mut self.v[*key];
result.take()
}
pub fn entry(&mut self, key: usize) -> Entry<V> {
if self.contains_key(&key) {
Occupied(OccupiedEntry {
map: self,
index: key,
})
} else {
Vacant(VacantEntry {
map: self,
index: key,
})
}
}
}
impl<'a, V> Entry<'a, V> {
pub fn get(self) -> Result<&'a mut V, VacantEntry<'a, V>> {
match self {
Occupied(entry) => Ok(entry.into_mut()),
Vacant(entry) => Err(entry),
}
}
pub fn or_insert(self, default: V) -> &'a mut V {
match self {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(default),
}
}
pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
match self {
Occupied(entry) => entry.into_mut(),
Vacant(entry) => entry.insert(default()),
}
}
}
impl<'a, V> VacantEntry<'a, V> {
pub fn insert(self, value: V) -> &'a mut V {
let index = self.index;
self.map.insert(index, value);
&mut self.map[index]
}
}
impl<'a, V> OccupiedEntry<'a, V> {
pub fn get(&self) -> &V {
let index = self.index;
&self.map[index]
}
pub fn get_mut(&mut self) -> &mut V {
let index = self.index;
&mut self.map[index]
}
pub fn into_mut(self) -> &'a mut V {
let index = self.index;
&mut self.map[index]
}
pub fn insert(&mut self, value: V) -> V {
let index = self.index;
self.map.insert(index, value).unwrap()
}
pub fn remove(self) -> V {
let index = self.index;
self.map.remove(&index).unwrap()
}
}
impl<V: PartialEq> PartialEq for VecMap<V> {
fn eq(&self, other: &VecMap<V>) -> bool {
for ((k1, v1), (k2, v2)) in self.iter().zip(other.iter()) {
if k1 != k2 || v1 != v2 {
return false;
}
}
true
}
}
impl<V: Eq> Eq for VecMap<V> {}
impl<V: fmt::Debug> fmt::Debug for VecMap<V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{{"));
for (i, (k, v)) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}: {:?}", k, *v));
}
write!(f, "}}")
}
}
impl<V> FromIterator<(usize, V)> for VecMap<V> {
fn from_iter<I: IntoIterator<Item=(usize, V)>>(iter: I) -> VecMap<V> {
let mut map = VecMap::new();
map.extend(iter);
map
}
}
impl<T> IntoIterator for VecMap<T> {
type Item = (usize, T);
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
fn filter<A>((i, v): (usize, Option<A>)) -> Option<(usize, A)> {
v.map(|v| (i, v))
}
let filter: fn((usize, Option<T>)) -> Option<(usize, T)> = filter;
IntoIter { iter: self.v.into_iter().enumerate().filter_map(filter) }
}
}
impl<'a, T> IntoIterator for &'a VecMap<T> {
type Item = (usize, &'a T);
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut VecMap<T> {
type Item = (usize, &'a mut T);
type IntoIter = IterMut<'a, T>;
fn into_iter(mut self) -> IterMut<'a, T> {
self.iter_mut()
}
}
impl<V> Extend<(usize, V)> for VecMap<V> {
fn extend<I: IntoIterator<Item=(usize, V)>>(&mut self, iter: I) {
for (k, v) in iter {
self.insert(k, v);
}
}
}
impl<V> Index<usize> for VecMap<V> {
type Output = V;
#[inline]
fn index<'a>(&'a self, i: usize) -> &'a V {
self.get(&i).expect("key not present")
}
}
impl<'a,V> Index<&'a usize> for VecMap<V> {
type Output = V;
#[inline]
fn index(&self, i: &usize) -> &V {
self.get(i).expect("key not present")
}
}
impl<V> IndexMut<usize> for VecMap<V> {
#[inline]
fn index_mut(&mut self, i: usize) -> &mut V {
self.get_mut(&i).expect("key not present")
}
}
impl<'a, V> IndexMut<&'a usize> for VecMap<V> {
#[inline]
fn index_mut(&mut self, i: &usize) -> &mut V {
self.get_mut(i).expect("key not present")
}
}
macro_rules! iterator {
(impl $name:ident -> $elem:ty, $($getter:ident),+) => {
impl<'a, V> Iterator for $name<'a, V> {
type Item = $elem;
#[inline]
fn next(&mut self) -> Option<$elem> {
while self.front < self.back {
match self.iter.next() {
Some(elem) => {
match elem$(. $getter ())+ {
Some(x) => {
let index = self.front;
self.front += 1;
return Some((index, x));
},
None => {},
}
}
_ => ()
}
self.front += 1;
}
None
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.back - self.front))
}
}
}
}
macro_rules! double_ended_iterator {
(impl $name:ident -> $elem:ty, $($getter:ident),+) => {
impl<'a, V> DoubleEndedIterator for $name<'a, V> {
#[inline]
fn next_back(&mut self) -> Option<$elem> {
while self.front < self.back {
match self.iter.next_back() {
Some(elem) => {
match elem$(. $getter ())+ {
Some(x) => {
self.back -= 1;
return Some((self.back, x));
},
None => {},
}
}
_ => ()
}
self.back -= 1;
}
None
}
}
}
}
pub struct Iter<'a, V:'a> {
front: usize,
back: usize,
iter: slice::Iter<'a, Option<V>>
}
impl<'a, V> Clone for Iter<'a, V> {
fn clone(&self) -> Iter<'a, V> {
Iter {
front: self.front,
back: self.back,
iter: self.iter.clone()
}
}
}
iterator! { impl Iter -> (usize, &'a V), as_ref }
double_ended_iterator! { impl Iter -> (usize, &'a V), as_ref }
pub struct IterMut<'a, V:'a> {
front: usize,
back: usize,
iter: slice::IterMut<'a, Option<V>>
}
iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
double_ended_iterator! { impl IterMut -> (usize, &'a mut V), as_mut }
pub struct Keys<'a, V: 'a> {
iter: Map<Iter<'a, V>, fn((usize, &'a V)) -> usize>
}
impl<'a, V> Clone for Keys<'a, V> {
fn clone(&self) -> Keys<'a, V> {
Keys {
iter: self.iter.clone()
}
}
}
pub struct Values<'a, V: 'a> {
iter: Map<Iter<'a, V>, fn((usize, &'a V)) -> &'a V>
}
impl<'a, V> Clone for Values<'a, V> {
fn clone(&self) -> Values<'a, V> {
Values {
iter: self.iter.clone()
}
}
}
pub struct IntoIter<V> {
iter: FilterMap<
Enumerate<vec::IntoIter<Option<V>>>,
fn((usize, Option<V>)) -> Option<(usize, V)>>
}
impl<'a, V> Iterator for Keys<'a, V> {
type Item = usize;
fn next(&mut self) -> Option<usize> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl<'a, V> DoubleEndedIterator for Keys<'a, V> {
fn next_back(&mut self) -> Option<usize> { self.iter.next_back() }
}
impl<'a, V> Iterator for Values<'a, V> {
type Item = &'a V;
fn next(&mut self) -> Option<(&'a V)> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl<'a, V> DoubleEndedIterator for Values<'a, V> {
fn next_back(&mut self) -> Option<(&'a V)> { self.iter.next_back() }
}
impl<V> Iterator for IntoIter<V> {
type Item = (usize, V);
fn next(&mut self) -> Option<(usize, V)> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
}
impl<V> DoubleEndedIterator for IntoIter<V> {
fn next_back(&mut self) -> Option<(usize, V)> { self.iter.next_back() }
}