# HG changeset patch # User alfadur # Date 1549540191 -10800 # Node ID e5415faa117bde28d74a8f7cb22277ebe9f3a69f # Parent 2071da901c63b5bd5a47acd256cd8fef88e66b8a add data structure for extending slabs diff -r 2071da901c63 -r e5415faa117b rust/hedgewars-server/src/server.rs --- a/rust/hedgewars-server/src/server.rs Wed Feb 06 22:40:38 2019 +0300 +++ b/rust/hedgewars-server/src/server.rs Thu Feb 07 14:49:51 2019 +0300 @@ -5,6 +5,7 @@ #[cfg(feature = "official-server")] mod database; mod handlers; +pub mod indexslab; pub mod io; pub mod network; pub mod room; diff -r 2071da901c63 -r e5415faa117b rust/hedgewars-server/src/server/indexslab.rs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/rust/hedgewars-server/src/server/indexslab.rs Thu Feb 07 14:49:51 2019 +0300 @@ -0,0 +1,68 @@ +use std::{ + iter, + ops::{Index, IndexMut}, +}; + +pub struct IndexSlab { + data: Vec>, +} + +impl IndexSlab { + pub fn new() -> Self { + Self { data: Vec::new() } + } + + pub fn with_capacity(capacity: usize) -> Self { + Self { + data: Vec::with_capacity(capacity), + } + } + + pub fn insert(&mut self, index: usize, value: T) { + if index >= self.data.len() { + self.data.reserve(index - self.data.len() + 1); + self.data.extend((self.data.len()..index).map(|_| None)); + self.data.push(Some(value)) + } else { + self.data[index] = Some(value); + } + } + + pub fn contains(&self, index: usize) -> bool { + self.data.get(index).and_then(|x| x.as_ref()).is_some() + } + + pub fn remove(&mut self, index: usize) { + if let Some(x) = self.data.get_mut(index) { + *x = None + } + } + + pub fn iter(&self) -> impl Iterator { + self.data + .iter() + .enumerate() + .filter_map(|(index, opt)| opt.as_ref().and_then(|x| Some((index, x)))) + } + + pub fn iter_mut(&mut self) -> impl Iterator { + self.data + .iter_mut() + .enumerate() + .filter_map(|(index, opt)| opt.as_mut().and_then(|x| Some((index, x)))) + } +} + +impl Index for IndexSlab { + type Output = T; + + fn index(&self, index: usize) -> &Self::Output { + self.data[index].as_ref().unwrap() + } +} + +impl IndexMut for IndexSlab { + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + self.data[index].as_mut().unwrap() + } +}