myst-client 0.1.4

A client library for the Myst network
Documentation
use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};

use super::NodeId;

#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct NetworkState {
    pub graph: HashMap<NodeId, HashSet<NodeId>>,
}

impl NetworkState {
    pub fn new() -> Self {
        Self {
            graph: HashMap::new(),
        }
    }

    pub fn update(&mut self, new_state: NetworkState) {
        for (node, new_neighbors) in new_state.graph.into_iter() {
            let entry = self.graph.entry(node).or_default();
            entry.extend(new_neighbors);
        }
    }

    pub fn neighbors(&self, node_id: &NodeId) -> HashSet<NodeId> {
        self.graph.get(node_id).cloned().unwrap_or_default()
    }

    /// Get all known nodes in the network
    pub fn all_nodes(&self) -> HashSet<NodeId> {
        let mut nodes = HashSet::new();
        // Add all nodes that appear as keys
        nodes.extend(self.graph.keys().cloned());
        // Add all nodes that appear as values in the adjacency sets
        for neighbors in self.graph.values() {
            nodes.extend(neighbors.iter().cloned());
        }
        nodes
    }

    /// Get number of nodes in the network
    pub fn node_count(&self) -> usize {
        self.graph.len()
    }

    pub fn insert_adjacencies(&mut self, node: NodeId, neighbors: HashSet<NodeId>) {
        self.graph
            .entry(node.clone())
            .or_default()
            .extend(neighbors.clone());

        for neighbor in neighbors {
            self.graph.entry(neighbor).or_default().insert(node.clone());
        }
    }
}