Split EntityMap into entity::PrimaryMap and entity::EntityMap.

The new PrimaryMap replaces the primary EntityMap and the PrimaryEntityData
marker trait which was causing some confusion. We now have a clear
division between the two types of maps:

- PrimaryMap is used to assign entity numbers to the primary data for an
  entity.
- EntityMap is a secondary mapping adding additional info.

The split also means that the secondary EntityMap can now behave as if
all keys have a default value. This means that we can get rid of the
annoying ensure() and get_or_default() methods ther were used everywhere
instead of indexing. Just use normal indexing now; non-existent keys
will return the default value.
This commit is contained in:
Jakob Stoklund Olesen
2017-08-18 15:04:10 -07:00
parent 8599372098
commit 7e08b14cf6
30 changed files with 413 additions and 363 deletions

View File

@@ -0,0 +1,55 @@
//! A double-ended iterator over entity references.
use entity::EntityRef;
use std::marker::PhantomData;
/// Iterate over all keys in order.
pub struct Keys<K: EntityRef> {
pos: usize,
rev_pos: usize,
unused: PhantomData<K>,
}
impl<K: EntityRef> Keys<K> {
/// Create a `Keys` iterator that visits `count` entities starting from 0.
pub fn new(count: usize) -> Keys<K> {
Keys {
pos: 0,
rev_pos: count,
unused: PhantomData,
}
}
}
impl<K: EntityRef> Iterator for Keys<K> {
type Item = K;
fn next(&mut self) -> Option<Self::Item> {
if self.pos < self.rev_pos {
let k = K::new(self.pos);
self.pos += 1;
Some(k)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = self.rev_pos - self.pos;
(size, Some(size))
}
}
impl<K: EntityRef> DoubleEndedIterator for Keys<K> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.rev_pos > self.pos {
let k = K::new(self.rev_pos - 1);
self.rev_pos -= 1;
Some(k)
} else {
None
}
}
}
impl<K: EntityRef> ExactSizeIterator for Keys<K> {}

View File

@@ -0,0 +1,135 @@
//! Densely numbered entity references as mapping keys.
//!
//! The `EntityMap` data structure uses the dense index space to implement a map with a vector.
//! Unlike `PrimaryMap`, and `EntityMap` can't be used to allocate entity references. It is used to
//! associate secondary information with entities.
use entity::{EntityRef, Keys};
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
/// A mapping `K -> V` for densely indexed entity references.
#[derive(Debug, Clone)]
pub struct EntityMap<K, V>
where K: EntityRef,
V: Clone
{
elems: Vec<V>,
default: V,
unused: PhantomData<K>,
}
/// Shared `EntityMap` implementation for all value types.
impl<K, V> EntityMap<K, V>
where K: EntityRef,
V: Clone
{
/// Create a new empty map.
pub fn new() -> Self
where V: Default
{
EntityMap {
elems: Vec::new(),
default: Default::default(),
unused: PhantomData,
}
}
/// Get the element at `k` if it exists.
pub fn get(&self, k: K) -> Option<&V> {
self.elems.get(k.index())
}
/// Is this map completely empty?
pub fn is_empty(&self) -> bool {
self.elems.is_empty()
}
/// Remove all entries from this map.
pub fn clear(&mut self) {
self.elems.clear()
}
/// Iterate over all the keys in this map.
pub fn keys(&self) -> Keys<K> {
Keys::new(self.elems.len())
}
/// Resize the map to have `n` entries by adding default entries as needed.
pub fn resize(&mut self, n: usize) {
self.elems.resize(n, self.default.clone());
}
}
/// Immutable indexing into an `EntityMap`.
///
/// All keys are permitted. Untouched entries have the default value.
impl<K, V> Index<K> for EntityMap<K, V>
where K: EntityRef,
V: Clone
{
type Output = V;
fn index(&self, k: K) -> &V {
self.get(k).unwrap_or(&self.default)
}
}
/// Mutable indexing into an `EntityMap`.
///
/// The map grows as needed to accommodate new keys.
impl<K, V> IndexMut<K> for EntityMap<K, V>
where K: EntityRef,
V: Clone
{
fn index_mut(&mut self, k: K) -> &mut V {
let i = k.index();
if i >= self.elems.len() {
self.resize(i + 1);
}
&mut self.elems[i]
}
}
#[cfg(test)]
mod tests {
use super::*;
// `EntityRef` impl for testing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct E(u32);
impl EntityRef for E {
fn new(i: usize) -> Self {
E(i as u32)
}
fn index(self) -> usize {
self.0 as usize
}
}
#[test]
fn basic() {
let r0 = E(0);
let r1 = E(1);
let r2 = E(2);
let mut m = EntityMap::new();
let v: Vec<E> = m.keys().collect();
assert_eq!(v, []);
m[r2] = 3;
m[r1] = 5;
assert_eq!(m[r1], 5);
assert_eq!(m[r2], 3);
let v: Vec<E> = m.keys().collect();
assert_eq!(v, [r0, r1, r2]);
let shared = &m;
assert_eq!(shared[r0], 0);
assert_eq!(shared[r1], 5);
assert_eq!(shared[r2], 3);
}
}

View File

@@ -5,6 +5,14 @@
//!
//! Various data structures based on the entity references are defined in sub-modules.
mod keys;
mod map;
mod primary;
pub use self::keys::Keys;
pub use self::map::EntityMap;
pub use self::primary::PrimaryMap;
/// A type wrapping a small integer index should implement `EntityRef` so it can be used as the key
/// of an `EntityMap` or `SparseMap`.
pub trait EntityRef: Copy + Eq {

View File

@@ -0,0 +1,141 @@
//! Densely numbered entity references as mapping keys.
//!
//! The `PrimaryMap` data structure uses the dense index space to implement a map with a vector.
//!
//! A primary map contains the main definition of an entity, and it can be used to allocate new
//! entity references with the `push` method.
//!
//! There should only be a single `PrimaryMap` instance for a given `EntityRef` type, otherwise
//! conflicting references will be created.
use entity::{EntityRef, Keys};
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
/// A mapping `K -> V` for densely indexed entity references.
#[derive(Debug, Clone)]
pub struct PrimaryMap<K, V>
where K: EntityRef
{
elems: Vec<V>,
unused: PhantomData<K>,
}
impl<K, V> PrimaryMap<K, V>
where K: EntityRef
{
/// Create a new empty map.
pub fn new() -> Self {
PrimaryMap {
elems: Vec::new(),
unused: PhantomData,
}
}
/// Check if `k` is a valid key in the map.
pub fn is_valid(&self, k: K) -> bool {
k.index() < self.elems.len()
}
/// Get the element at `k` if it exists.
pub fn get(&self, k: K) -> Option<&V> {
self.elems.get(k.index())
}
/// Is this map completely empty?
pub fn is_empty(&self) -> bool {
self.elems.is_empty()
}
/// Get the total number of entity references created.
pub fn len(&self) -> usize {
self.elems.len()
}
/// Iterate over all the keys in this map.
pub fn keys(&self) -> Keys<K> {
Keys::new(self.elems.len())
}
/// Remove all entries from this map.
pub fn clear(&mut self) {
self.elems.clear()
}
/// Get the key that will be assigned to the next pushed value.
pub fn next_key(&self) -> K {
K::new(self.elems.len())
}
/// Append `v` to the mapping, assigning a new key which is returned.
pub fn push(&mut self, v: V) -> K {
let k = self.next_key();
self.elems.push(v);
k
}
}
/// Immutable indexing into an `PrimaryMap`.
/// The indexed value must be in the map.
impl<K, V> Index<K> for PrimaryMap<K, V>
where K: EntityRef
{
type Output = V;
fn index(&self, k: K) -> &V {
&self.elems[k.index()]
}
}
/// Mutable indexing into an `PrimaryMap`.
impl<K, V> IndexMut<K> for PrimaryMap<K, V>
where K: EntityRef
{
fn index_mut(&mut self, k: K) -> &mut V {
&mut self.elems[k.index()]
}
}
#[cfg(test)]
mod tests {
use super::*;
// `EntityRef` impl for testing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct E(u32);
impl EntityRef for E {
fn new(i: usize) -> Self {
E(i as u32)
}
fn index(self) -> usize {
self.0 as usize
}
}
#[test]
fn basic() {
let r0 = E(0);
let r1 = E(1);
let m = PrimaryMap::<E, isize>::new();
let v: Vec<E> = m.keys().collect();
assert_eq!(v, []);
assert!(!m.is_valid(r0));
assert!(!m.is_valid(r1));
}
#[test]
fn push() {
let mut m = PrimaryMap::new();
let k1: E = m.push(12);
let k2 = m.push(33);
assert_eq!(m[k1], 12);
assert_eq!(m[k2], 33);
let v: Vec<E> = m.keys().collect();
assert_eq!(v, [k1, k2]);
}
}