Skip to main content

somatize_core/
catalog.rs

1//! The store: which implementation belongs to each node.
2//!
3//! Apart from the [`Graph`](crate::Graph) on purpose: a graph is data — it
4//! serializes, compares, gets sent elsewhere — and an implementation is not.
5//! What joins them is the node id, and nothing else.
6
7use crate::{Node, NodeId};
8use std::collections::HashMap;
9use std::sync::Arc;
10
11/// A graph's implementations, by node id.
12#[derive(Default, Clone)]
13pub struct Catalog {
14    nodes: HashMap<NodeId, Arc<dyn Node>>,
15}
16
17impl Catalog {
18    /// An empty store.
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    /// Registers a node's implementation, returning whatever was there before.
24    pub fn insert(&mut self, id: impl Into<NodeId>, node: Arc<dyn Node>) -> Option<Arc<dyn Node>> {
25        self.nodes.insert(id.into(), node)
26    }
27
28    /// The implementation registered for a node.
29    pub fn get(&self, id: &NodeId) -> Option<&Arc<dyn Node>> {
30        self.nodes.get(id)
31    }
32
33    /// How many implementations there are.
34    pub fn len(&self) -> usize {
35        self.nodes.len()
36    }
37
38    /// Whether there are none.
39    pub fn is_empty(&self) -> bool {
40        self.nodes.is_empty()
41    }
42}
43
44impl std::fmt::Debug for Catalog {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.debug_struct("Catalog")
47            .field("nodes", &self.nodes.keys().collect::<Vec<_>>())
48            .finish()
49    }
50}