Skip to main content

halephant_core/addr/
split_addr.rs

1// ---------------------------------------------------------------------------
2// Address parsing
3// ---------------------------------------------------------------------------
4
5/// Split a PostgreSQL-style address into `(host, port)`. Handles:
6/// - `hostname:5432` — simple host and port
7/// - `127.0.0.1:5432` — IPv4 and port
8/// - `[::1]:5432` — bracketed IPv6 and port
9/// - `[::1]` — bracketed IPv6, default port
10/// - `hostname` — no port, default to `"5432"`
11///
12/// Brackets are stripped from the returned host so the value matches `.pgpass`
13/// entries.
14pub fn split_host_port(addr: &str) -> (&str, &str) {
15    if let Some(rest) = addr.strip_prefix('[') {
16        // Bracketed IPv6: [host]:port or [host]
17        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        // Only split on the last colon if there's exactly one (otherwise it's
24        // a bare IPv6 literal like "::1").
25        if addr[..colon].contains(':') {
26            // Multiple colons without brackets — bare IPv6, no port.
27            (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}