1use std::collections::HashMap;
19
20use serde::{Deserialize, Serialize};
21
22pub const DEFAULT_PROTOCOL: &str = "triple";
23
24#[derive(Default, Debug, Clone, Serialize, Deserialize)]
25pub struct Protocol {
26 pub ip: String,
27 pub port: String,
28 pub name: String,
29
30 #[serde(skip_serializing, skip_deserializing)]
31 pub params: HashMap<String, String>,
32}
33
34pub type ProtocolConfig = HashMap<String, Protocol>;
35
36pub trait ProtocolRetrieve {
37 fn get_protocol(&self, protocol_key: &str) -> Option<Protocol>;
38 fn get_protocol_or_default(&self, protocol_key: &str) -> Protocol;
39}
40
41impl Protocol {
42 pub fn name(self, name: String) -> Self {
43 Self { name, ..self }
44 }
45
46 pub fn ip(self, ip: String) -> Self {
47 Self { ip, ..self }
48 }
49
50 pub fn port(self, port: String) -> Self {
51 Self { port, ..self }
52 }
53
54 pub fn params(self, params: HashMap<String, String>) -> Self {
55 Self { params, ..self }
56 }
57
58 pub fn to_url(self) -> String {
59 format!("{}://{}:{}", self.name, self.ip, self.port)
60 }
61}
62
63impl ProtocolRetrieve for ProtocolConfig {
64 fn get_protocol(&self, protocol_key: &str) -> Option<Protocol> {
65 let result = self.get(protocol_key);
66 if let Some(..) = result {
67 Some(result.unwrap().clone())
68 } else {
69 None
70 }
71 }
72
73 fn get_protocol_or_default(&self, protocol_key: &str) -> Protocol {
74 let result = self.get_protocol(protocol_key);
75 if let Some(..) = result {
76 result.unwrap().clone()
77 } else {
78 let result = self.get_protocol(protocol_key);
79 if result.is_none() {
80 panic!("default triple protocol dose not defined.")
81 } else {
82 result.unwrap()
83 }
84 }
85 }
86}