1mod hostname;
2
3pub use hostname::hostname;
4
5pub fn split_host_port(input: &str) -> (&str, &str) {
12 if let Some(index) = input.rfind(':') {
13 if index == (input.len() - 1) {
14 return (&input[..index], "");
16 }
17 let mut host = &input[..index];
18 let mut port = &input[index + 1..];
19 if port.rfind(']').is_some() {
20 host = input.trim_start_matches('[').trim_end_matches(']');
22 port = "";
23 } else if host.find('[').is_some() {
24 host = host.trim_start_matches('[').trim_end_matches(']');
26 }
27 return (host, port);
28 }
29 return (input, "");
30}
31
32#[cfg(test)]
33mod test {
34 use super::*;
35
36 #[test]
37 fn test_split_host_port() {
38 struct Expected {
39 host: &'static str,
40 port: &'static str,
41 }
42 let tests = [
43 (
44 "",
45 Expected {
46 host: "",
47 port: "",
48 },
49 ),
50 (
51 "localhost",
52 Expected {
53 host: "localhost",
54 port: "",
55 },
56 ),
57 (
58 "127.0.0.1",
59 Expected {
60 host: "127.0.0.1",
61 port: "",
62 },
63 ),
64 (
65 "[::1]",
66 Expected {
67 host: "::1",
68 port: "",
69 },
70 ),
71 (
72 "localhost:8080",
73 Expected {
74 host: "localhost",
75 port: "8080",
76 },
77 ),
78 (
79 "127.0.0.1:8080",
80 Expected {
81 host: "127.0.0.1",
82 port: "8080",
83 },
84 ),
85 (
86 "[::1]:8080",
87 Expected {
88 host: "::1",
89 port: "8080",
90 },
91 ),
92 (
93 "localhost:",
94 Expected {
95 host: "localhost",
96 port: "",
97 },
98 ),
99 ];
100
101 for test in tests {
102 let (host, port) = split_host_port(test.0);
103 assert_eq!(test.1.host, host);
104 assert_eq!(test.1.port, port);
105 }
106 }
107}