confitul 0.1.4

ConfitUL contains utilities for ConfitDB which is an experimental, distributed, real-time database, giving full control on conflict resolution.
Documentation
use crate::cluster_options::ClusterOptions;
use crate::local_host::LocalHost;
use crate::memory_store::MemoryStore;
use crate::node::Node;
use ckey::CKey;
use std::collections::HashMap;
use std::hash::Hash;
use url::ParseError;

#[derive(Debug)]
pub struct Cluster<C, V>
where
    C: Eq + Hash + Clone,
    V: Clone,
{
    pub local_host: LocalHost,
    //    remote_hosts: HashMap<HostId, RemoteHost>,
    nodes: HashMap<CKey, Node>,
    store: MemoryStore<C, V>,
}

impl<C, V> Cluster<C, V>
where
    C: Eq + Hash + Clone,
    V: Clone,
{
    pub fn new(options: Option<ClusterOptions>) -> Result<Cluster<C, V>, ParseError> {
        let real_options = options.unwrap_or(ClusterOptions::default());
        let local_host = LocalHost::new(Some(real_options.local_host))?;
        let mut cluster = Cluster {
            local_host,
            //          remote_hosts: HashMap::new(),
            nodes: HashMap::new(),
            store: MemoryStore::new(),
        };
        cluster.resize(real_options.size);
        Ok(cluster)
    }

    pub fn resize(&mut self, size: usize) {
        while self.nodes.len() > size {
            let to_remove = self.nodes.iter().next().unwrap().0.clone();
            self.nodes.remove(&to_remove);
        }
        while self.nodes.len() < size {
            let node = Node::new_rand();
            match self.nodes.insert(node.key, node) {
                // Really, there should be no dupes here, we're talking
                // about *hopefully* random generation of 256 bit keys.
                // Having dupes is unlikely, should it happen, let's call it.
                Some(_) => panic!("duplicate node key"),
                None => {}
            }
        }
    }

    pub fn store(&self) -> &MemoryStore<C, V> {
        &self.store
    }
}