Trait moore_common::score::NodeStorage
source · [−]pub trait NodeStorage<I> {
type Node;
fn get(&self, id: &I) -> Option<&Self::Node>;
fn set(&mut self, id: I, node: Self::Node) -> Option<Self::Node>;
}
Expand description
The NodeStorage
trait allows for references to nodes to be stored and
retrieved via a unique node ID.
Once a node is created for example in an arena, a reference to it can be
stored in a NodeStorage
to associate it with an ID. If that ID is
presented to the NodeStorage
again, that same reference will be produced.
Implementors of this trait are expected to implement it multiple times, once
for each different ID/node type pair that they support. This then allows for
nodes to be looked up in a type safe manner based on their ID.
The NodeStorage
does not assume ownership over the nodes added to it.
Therefore all nodes are references of at least the lifetime 'tn
.
Example
use moore_common::score::NodeStorage;
use std::collections::HashMap;
#[derive(PartialEq, Eq, Debug)]
struct Foo;
#[derive(PartialEq, Eq, Debug)]
struct Bar;
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
struct FooId(usize);
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
struct BarId(usize);
struct Table<'tn> {
foos: HashMap<FooId, &'tn Foo>,
bars: HashMap<BarId, &'tn Bar>,
}
impl<'tn> NodeStorage<FooId> for Table<'tn> {
type Node = &'tn Foo;
fn get(&self, id: &FooId) -> Option<&&'tn Foo> { self.foos.get(id) }
fn set(&mut self, id: FooId, node: &'tn Foo) -> Option<&'tn Foo> { self.foos.insert(id, node) }
}
impl<'tn> NodeStorage<BarId> for Table<'tn> {
type Node = &'tn Bar;
fn get(&self, id: &BarId) -> Option<&&'tn Bar> { self.bars.get(id) }
fn set(&mut self, id: BarId, node: &'tn Bar) -> Option<&'tn Bar> { self.bars.insert(id, node) }
}
// Store node refs in table:
let foo = Foo;
let bar = Bar;
let mut tbl = Table{ foos: HashMap::new(), bars: HashMap::new() };
tbl.set(FooId(1), &foo);
tbl.set(BarId(2), &bar);
// Retrieve node refs again:
assert_eq!(tbl.get(&FooId(1)), Some(&&foo));
assert_eq!(tbl.get(&BarId(2)), Some(&&bar));
assert_eq!(tbl.get(&BarId(1)), None);
assert_eq!(tbl.get(&FooId(2)), None);
// The following would produce a compiler error due to type mismatch:
// let _: &Foo = *tbl.get(&BarId(1)).unwrap();
// let _: &Bar = *tbl.get(&FooId(2)).unwrap();
Associated Types
Required methods
Obtains a reference to the node with the given ID.
Returns None
when no node with the given ID exists.