subrpc_core/
endpoint_url.rs

1use std::fmt::Display;
2
3use anyhow::bail;
4use serde::{Deserialize, Serialize};
5
6#[derive(PartialEq, PartialOrd, Ord, Hash, Eq, Debug, Deserialize, Serialize, Clone)]
7#[serde(untagged)]
8#[serde(try_from = "&str")]
9pub enum EndpointUrl {
10	Http(String),
11	Https(String),
12	Ws(String),
13	Wss(String),
14}
15
16impl Display for EndpointUrl {
17	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18		match self {
19			EndpointUrl::Http(s) | EndpointUrl::Https(s) | EndpointUrl::Ws(s) | EndpointUrl::Wss(s) => f.write_str(s),
20		}
21	}
22}
23
24impl TryFrom<&str> for EndpointUrl {
25	type Error = anyhow::Error;
26
27	fn try_from(s: &str) -> Result<Self, Self::Error> {
28		if s.starts_with("wss://") {
29			return Ok(EndpointUrl::Wss(s.to_string()));
30		}
31
32		if s.starts_with("ws://") {
33			return Ok(EndpointUrl::Ws(s.to_string()));
34		}
35
36		if s.starts_with("https://") {
37			return Ok(EndpointUrl::Https(s.to_string()));
38		}
39
40		if s.starts_with("http://") {
41			return Ok(EndpointUrl::Http(s.to_string()));
42		}
43
44		// Err(format!("Invalid endpoint: {}", s))
45		bail!("Invalid endpoint: {}", s)
46	}
47}
48
49// /// Serde is using From<T>
50// impl From<&str> for EndpointUrl {
51// 	fn from(s: &str) -> Self {
52// 		Self::try_from(s).unwrap()
53// 	}
54// }
55
56#[cfg(test)]
57mod test_from {
58	use super::*;
59
60	#[test]
61	fn test_from_str() {
62		assert_eq!(EndpointUrl::Wss("wss://foobar".to_string()), EndpointUrl::try_from("wss://foobar").unwrap());
63	}
64}