Skip to main content

socks5_impl/
user_key.rs

1/// Required for username/password authentication.
2#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
3#[derive(Default, Debug, Eq, PartialEq, PartialOrd, Ord, Clone, Hash)]
4pub struct UserKey {
5    pub username: String,
6    pub password: String,
7}
8
9impl std::fmt::Display for UserKey {
10    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11        use percent_encoding::{NON_ALPHANUMERIC, percent_encode};
12        match (self.username.is_empty(), self.password.is_empty()) {
13            (true, true) => write!(f, ""),
14            (true, false) => write!(f, ":{}", percent_encode(self.password.as_bytes(), NON_ALPHANUMERIC)),
15            (false, true) => write!(f, "{}", percent_encode(self.username.as_bytes(), NON_ALPHANUMERIC)),
16            (false, false) => {
17                let username = percent_encode(self.username.as_bytes(), NON_ALPHANUMERIC).to_string();
18                let password = percent_encode(self.password.as_bytes(), NON_ALPHANUMERIC).to_string();
19                write!(f, "{username}:{password}")
20            }
21        }
22    }
23}
24
25impl UserKey {
26    /// Constructs `UserKey` with the specified username and password.
27    pub fn new<U, P>(username: U, password: P) -> Self
28    where
29        U: Into<String>,
30        P: Into<String>,
31    {
32        Self {
33            username: username.into(),
34            password: password.into(),
35        }
36    }
37
38    pub fn username_arr(&self) -> Vec<u8> {
39        self.username.as_bytes().to_vec()
40    }
41
42    pub fn password_arr(&self) -> Vec<u8> {
43        self.password.as_bytes().to_vec()
44    }
45}
46
47#[test]
48fn test_user_key() {
49    let user_key = UserKey::new("username", "pass@word");
50    assert_eq!(user_key.to_string(), "username:pass%40word");
51    let user_key = UserKey::new("username", "");
52    assert_eq!(user_key.to_string(), "username");
53    let user_key = UserKey::new("", "password");
54    assert_eq!(user_key.to_string(), ":password");
55    let user_key = UserKey::new("", "");
56    assert_eq!(user_key.to_string(), "");
57}