Skip to main content

sqlx_core/net/
mod.rs

1mod socket;
2pub mod tls;
3
4pub use socket::{
5    connect_tcp, connect_uds, BufferedSocket, Socket, SocketIntoBox, WithSocket, WriteBuffer,
6};
7use std::fmt::{Debug, Display, Formatter};
8use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
9
10#[derive(Clone, PartialEq, Eq)]
11pub struct UrlHost {
12    original: Box<str>,
13    brackets: Brackets,
14}
15
16#[derive(Clone, PartialEq, Eq)]
17enum Brackets {
18    None,
19    Included,
20    Needed,
21}
22
23impl UrlHost {
24    pub fn empty() -> Self {
25        UrlHost {
26            original: "".into(),
27            brackets: Brackets::None,
28        }
29    }
30
31    pub fn localhost() -> Self {
32        UrlHost {
33            original: "localhost".into(),
34            brackets: Brackets::None,
35        }
36    }
37
38    fn check_brackets(&mut self) {
39        if self.original.starts_with('[') && self.original.ends_with(']') {
40            self.brackets = Brackets::Included;
41        } else if self.original.parse::<Ipv6Addr>().is_ok() {
42            // IPv6 address passed through `.host()`, should be bracketed in a URL
43            self.brackets = Brackets::Needed;
44        } else {
45            self.brackets = Brackets::None;
46        }
47    }
48
49    pub fn set(&mut self, s: &str) {
50        self.original = s.into();
51        self.check_brackets();
52    }
53
54    pub fn original(&self) -> &str {
55        &self.original
56    }
57
58    pub fn stripped(&self) -> &str {
59        self.original.trim_matches(&['[', ']'][..])
60    }
61}
62
63impl From<String> for UrlHost {
64    fn from(value: String) -> Self {
65        let mut this = Self {
66            original: value.into(),
67            brackets: Brackets::None,
68        };
69        this.check_brackets();
70        this
71    }
72}
73
74impl Debug for UrlHost {
75    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
76        Debug::fmt(&self.original, f)
77    }
78}
79
80impl Display for UrlHost {
81    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
82        if let Brackets::Needed = self.brackets {
83            write!(f, "[{}]", self.original)
84        } else {
85            f.write_str(&self.original)
86        }
87    }
88}
89
90impl<'a> From<&'a UrlHost> for SocketHost<'a> {
91    fn from(host: &'a UrlHost) -> Self {
92        SocketHost::Str(host.stripped())
93    }
94}
95
96#[derive(Clone, Copy)]
97pub enum SocketHost<'a> {
98    Str(&'a str),
99    // Separating `Ipv4Addr` and `Ipv6Addr` makes for a flatter enum
100    Ipv4(Ipv4Addr),
101    Ipv6(Ipv6Addr),
102}
103
104impl From<IpAddr> for SocketHost<'_> {
105    fn from(value: IpAddr) -> Self {
106        match value {
107            IpAddr::V4(addr) => Self::Ipv4(addr),
108            IpAddr::V6(addr) => Self::Ipv6(addr),
109        }
110    }
111}
112
113impl SocketHost<'_> {
114    fn try_as_ip(&self) -> Result<IpAddr, &str> {
115        match *self {
116            // `Url::host()` returns the host wrapped in brackets which the socket API isn't expecting
117            Self::Str(s) => s.trim_matches(&['[', ']'][..]).parse().map_err(|_| s),
118            Self::Ipv4(addr) => Ok(addr.into()),
119            Self::Ipv6(addr) => Ok(addr.into()),
120        }
121    }
122}