[−][src]Trait moore_common::score::NodeStorage
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
Loading content...Required methods
pub fn get(&self, id: &I) -> Option<&Self::Node>
[src]
Obtains a reference to the node with the given ID.
Returns None
when no node with the given ID exists.
pub fn set(&mut self, id: I, node: Self::Node) -> Option<Self::Node>
[src]
Store a reference to a node under the given ID.
Later that reference can be retrieved again by presenting the same ID to
the get
function. Returns the previously stored entry, if any.
Implementations on Foreign Types
impl<K, V> NodeStorage<K> for HashMap<K, V> where
K: Hash + Eq,
[src]
K: Hash + Eq,
type Node = V
pub fn get(&self, id: &K) -> Option<&V>
[src]
pub fn set(&mut self, id: K, node: V) -> Option<V>
[src]
impl<K, V> NodeStorage<K> for BTreeMap<K, V> where
K: Ord,
[src]
K: Ord,