use std;
use fnv;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Id(u32);
pub struct Map<Img> {
next_index: u32,
map: HashMap<Img>,
pub trigger_redraw: std::cell::Cell<bool>,
}
pub type HashMap<Img> = fnv::FnvHashMap<Id, Img>;
pub struct NewIds {
index_range: std::ops::Range<u32>,
}
impl<Img> std::ops::Deref for Map<Img> {
type Target = HashMap<Img>;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl<Img> Map<Img> {
pub fn new() -> Self {
Map {
next_index: 0,
map: HashMap::<Img>::default(),
trigger_redraw: std::cell::Cell::new(true),
}
}
pub fn get_mut(&mut self, id: Id) -> Option<&mut Img> {
self.trigger_redraw.set(true);
self.map.get_mut(&id)
}
pub fn insert(&mut self, img: Img) -> Id {
self.trigger_redraw.set(true);
let index = self.next_index;
self.next_index = index.wrapping_add(1);
let id = Id(index);
self.map.insert(id, img);
id
}
pub fn replace(&mut self, id: Id, img: Img) -> Option<Img> {
self.trigger_redraw.set(true);
self.map.insert(id, img)
}
pub fn remove(&mut self, id: Id) -> Option<Img> {
self.trigger_redraw.set(true);
self.map.remove(&id)
}
pub fn extend<I>(&mut self, images: I) -> NewIds
where I: IntoIterator<Item=Img>,
{
self.trigger_redraw.set(true);
let start_index = self.next_index;
let mut end_index = start_index;
for image in images {
self.map.insert(Id(end_index), image);
end_index += 1;
}
NewIds { index_range: start_index..end_index }
}
}
impl Iterator for NewIds {
type Item = Id;
fn next(&mut self) -> Option<Self::Item> {
self.index_range.next().map(|i| Id(i))
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.len()))
}
}
impl ExactSizeIterator for NewIds {
fn len(&self) -> usize {
self.index_range.len()
}
}