confitul/ep.rs
1use ckey::CKey;
2use serde::{Deserialize, Serialize};
3use std::fmt::Formatter;
4use url::Url;
5
6/// EP stands for End Point.
7///
8/// It contains all the informations required to, typically,
9/// contact a node. It's composed of a Key and a URL. Neither the Key or the URL
10/// could be enough. Obviously, when you only have the Key, you don't
11/// know where to call the node. And if you only have the URL, you still
12/// need the Key because a given URL might respond for several different
13/// virtual nodes.
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
15pub struct EP {
16 key: CKey,
17 url: Url,
18}
19
20pub const LOCAL: &str = "local";
21
22impl EP {
23 /// Generate a new local endpoint.
24 ///
25 /// # Examples
26 /// ```
27 /// use confitul::EP;
28 ///
29 /// let e = EP::new_local();
30 /// print!("e: {:?}", e);
31 /// ```
32 pub fn new_local() -> EP {
33 let key = CKey::new_rand();
34 let url = format!("{}:{}", LOCAL, key);
35 EP {
36 key,
37 url: Url::parse(url.as_str()).unwrap(),
38 }
39 }
40
41 /// Parses an endpoint from a key and an url.
42 ///
43 /// # Examples
44 /// ```
45 /// use confitul::EP;
46 ///
47 /// let e = EP::parse("12345678ffffffff01234567fffffffff00123456ffffffff0012345ffffffff","http://just-a-test.com").unwrap();
48 /// print!("e: {:?}", e);
49 /// ```
50 pub fn parse(key: &str, url: &str) -> Result<EP, Box<dyn std::error::Error>> {
51 let parsed_key = CKey::parse(key)?;
52 let parsed_url = Url::parse(url)?;
53 Ok(EP {
54 key: parsed_key,
55 url: parsed_url,
56 })
57 }
58}
59
60impl std::fmt::Display for EP {
61 /// Pretty-print an endpoint.
62 ///
63 /// # Examples
64 /// ```
65 /// use confitul::EP;
66 ///
67 /// let e = EP::parse("12345678ffffffff01234567fffffffff00123456ffffffff0012345ffffffff","http://just-a-test.com").unwrap();
68 /// assert_eq!("{\"key\":\"0.071111111\",\"url\":\"http://just-a-test.com/\"}", format!("{}", e));
69 /// ```
70 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
71 write!(
72 f,
73 "{{\"key\":\"{}\",\"url\":\"{}\"}}",
74 self.key,
75 self.url.as_str()
76 )
77 }
78}