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 ckey::CKey;
use serde::{Deserialize, Serialize};
use std::fmt::Formatter;
use url::Url;

/// EP stands for End Point.
///
/// It contains all the informations required to, typically,
/// contact a node. It's composed of a Key and a URL. Neither the Key or the URL
/// could be enough. Obviously, when you only have the Key, you don't
/// know where to call the node. And if you only have the URL, you still
/// need the Key because a given URL might respond for several different
/// virtual nodes.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EP {
    key: CKey,
    url: Url,
}

pub const LOCAL: &str = "local";

impl EP {
    /// Generate a new local endpoint.
    ///
    /// # Examples
    /// ```
    /// use confitul::EP;
    ///
    /// let e = EP::new_local();
    /// print!("e: {:?}", e);
    /// ```
    pub fn new_local() -> EP {
        let key = CKey::new_rand();
        let url = format!("{}:{}", LOCAL, key);
        EP {
            key,
            url: Url::parse(url.as_str()).unwrap(),
        }
    }

    /// Parses an endpoint from a key and an url.
    ///
    /// # Examples
    /// ```
    /// use confitul::EP;
    ///
    /// let e = EP::parse("12345678ffffffff01234567fffffffff00123456ffffffff0012345ffffffff","http://just-a-test.com").unwrap();
    /// print!("e: {:?}", e);
    /// ```
    pub fn parse(key: &str, url: &str) -> Result<EP, Box<dyn std::error::Error>> {
        let parsed_key = CKey::parse(key)?;
        let parsed_url = Url::parse(url)?;
        Ok(EP {
            key: parsed_key,
            url: parsed_url,
        })
    }
}

impl std::fmt::Display for EP {
    /// Pretty-print an endpoint.
    ///
    /// # Examples
    /// ```
    /// use confitul::EP;
    ///
    /// let e = EP::parse("12345678ffffffff01234567fffffffff00123456ffffffff0012345ffffffff","http://just-a-test.com").unwrap();
    /// assert_eq!("{\"key\":\"0.071111111\",\"url\":\"http://just-a-test.com/\"}", format!("{}", e));
    /// ```
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{{\"key\":\"{}\",\"url\":\"{}\"}}",
            self.key,
            self.url.as_str()
        )
    }
}