halephant_core/addr/
split_addr.rs1pub fn split_host_port(addr: &str) -> (&str, &str) {
15 if let Some(rest) = addr.strip_prefix('[') {
16 if let Some((host, port)) = rest.split_once("]:") {
18 (host, port)
19 } else {
20 (rest.trim_end_matches(']'), "5432")
21 }
22 } else if let Some(colon) = addr.rfind(':') {
23 if addr[..colon].contains(':') {
26 (addr, "5432")
28 } else {
29 (&addr[..colon], &addr[colon + 1..])
30 }
31 } else {
32 (addr, "5432")
33 }
34}
35
36#[cfg(test)]
37mod tests {
38 use super::split_host_port;
39
40 #[test]
41 fn simple_host_port() {
42 assert_eq!(split_host_port("localhost:5432"), ("localhost", "5432"));
43 }
44
45 #[test]
46 fn ipv4_port() {
47 assert_eq!(split_host_port("127.0.0.1:5433"), ("127.0.0.1", "5433"));
48 }
49
50 #[test]
51 fn bracketed_ipv6_port() {
52 assert_eq!(split_host_port("[::1]:5432"), ("::1", "5432"));
53 }
54
55 #[test]
56 fn bracketed_ipv6_no_port() {
57 assert_eq!(split_host_port("[::1]"), ("::1", "5432"));
58 }
59
60 #[test]
61 fn bare_ipv6_no_port() {
62 assert_eq!(split_host_port("::1"), ("::1", "5432"));
63 }
64
65 #[test]
66 fn hostname_no_port() {
67 assert_eq!(
68 split_host_port("pg-primary.internal"),
69 ("pg-primary.internal", "5432")
70 );
71 }
72
73 #[test]
74 fn custom_port() {
75 assert_eq!(
76 split_host_port("db.example.com:6432"),
77 ("db.example.com", "6432")
78 );
79 }
80
81 #[test]
82 fn full_ipv6_bracketed() {
83 assert_eq!(
84 split_host_port("[2001:db8::1]:5432"),
85 ("2001:db8::1", "5432")
86 );
87 }
88}