1use core::convert::TryInto;
7use std::error::Error;
8use core::fmt;
9use crate::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
10use core::str::FromStr;
11
12trait ReadNumberHelper: core::marker::Sized {
13 const ZERO: Self;
14 fn checked_mul(&self, other: u32) -> Option<Self>;
15 fn checked_add(&self, other: u32) -> Option<Self>;
16}
17
18macro_rules! impl_helper {
19 ($($t:ty)*) => ($(impl ReadNumberHelper for $t {
20 const ZERO: Self = 0;
21 #[inline]
22 fn checked_mul(&self, other: u32) -> Option<Self> {
23 Self::checked_mul(*self, other.try_into().ok()?)
24 }
25 #[inline]
26 fn checked_add(&self, other: u32) -> Option<Self> {
27 Self::checked_add(*self, other.try_into().ok()?)
28 }
29 })*)
30}
31
32impl_helper! { u8 u16 u32 }
33
34struct Parser<'a> {
35 state: &'a [u8],
37}
38
39impl<'a> Parser<'a> {
40 fn new(input: &'a [u8]) -> Parser<'a> {
41 Parser { state: input }
42 }
43
44 fn read_atomically<T, F>(&mut self, inner: F) -> Option<T>
46 where
47 F: FnOnce(&mut Parser<'_>) -> Option<T>,
48 {
49 let state = self.state;
50 let result = inner(self);
51 if result.is_none() {
52 self.state = state;
53 }
54 result
55 }
56
57 fn parse_with<T, F>(&mut self, inner: F, kind: AddrKind) -> Result<T, AddrParseError>
60 where
61 F: FnOnce(&mut Parser<'_>) -> Option<T>,
62 {
63 let result = inner(self);
64 if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind))
65 }
66
67 fn peek_char(&self) -> Option<char> {
69 self.state.first().map(|&b| char::from(b))
70 }
71
72 fn read_char(&mut self) -> Option<char> {
74 self.state.split_first().map(|(&b, tail)| {
75 self.state = tail;
76 char::from(b)
77 })
78 }
79
80 #[must_use]
81 fn read_given_char(&mut self, target: char) -> Option<()> {
83 self.read_atomically(|p| {
84 p.read_char().and_then(|c| if c == target { Some(()) } else { None })
85 })
86 }
87
88 fn read_separator<T, F>(&mut self, sep: char, index: usize, inner: F) -> Option<T>
93 where
94 F: FnOnce(&mut Parser<'_>) -> Option<T>,
95 {
96 self.read_atomically(move |p| {
97 if index > 0 {
98 p.read_given_char(sep)?;
99 }
100 inner(p)
101 })
102 }
103
104 fn read_number<T: ReadNumberHelper>(
108 &mut self,
109 radix: u32,
110 max_digits: Option<usize>,
111 allow_zero_prefix: bool,
112 ) -> Option<T> {
113 self.read_atomically(move |p| {
114 let mut result = T::ZERO;
115 let mut digit_count = 0;
116 let has_leading_zero = p.peek_char() == Some('0');
117
118 while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
119 result = result.checked_mul(radix)?;
120 result = result.checked_add(digit)?;
121 digit_count += 1;
122 if let Some(max_digits) = max_digits {
123 if digit_count > max_digits {
124 return None;
125 }
126 }
127 }
128
129 if digit_count == 0 {
130 None
131 } else if !allow_zero_prefix && has_leading_zero && digit_count > 1 {
132 None
133 } else {
134 Some(result)
135 }
136 })
137 }
138
139 fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
141 self.read_atomically(|p| {
142 let mut groups = [0; 4];
143
144 for (i, slot) in groups.iter_mut().enumerate() {
145 *slot = p.read_separator('.', i, |p| {
146 p.read_number(10, Some(3), false)
149 })?;
150 }
151
152 Some(groups.into())
153 })
154 }
155
156 fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
158 fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) {
164 let limit = groups.len();
165
166 for (i, slot) in groups.iter_mut().enumerate() {
167 if i < limit - 1 {
170 let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
171
172 if let Some(v4_addr) = ipv4 {
173 let [one, two, three, four] = v4_addr.octets();
174 groups[i + 0] = u16::from_be_bytes([one, two]);
175 groups[i + 1] = u16::from_be_bytes([three, four]);
176 return (i + 2, true);
177 }
178 }
179
180 let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true));
181
182 match group {
183 Some(g) => *slot = g,
184 None => return (i, false),
185 }
186 }
187 (groups.len(), false)
188 }
189
190 self.read_atomically(|p| {
191 let mut head = [0; 8];
194 let (head_size, head_ipv4) = read_groups(p, &mut head);
195
196 if head_size == 8 {
197 return Some(head.into());
198 }
199
200 if head_ipv4 {
202 return None;
203 }
204
205 p.read_given_char(':')?;
208 p.read_given_char(':')?;
209
210 let mut tail = [0; 7];
213 let limit = 8 - (head_size + 1);
214 let (tail_size, _) = read_groups(p, &mut tail[..limit]);
215
216 head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
218
219 Some(head.into())
220 })
221 }
222
223 fn read_ip_addr(&mut self) -> Option<IpAddr> {
225 self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6))
226 }
227
228 fn read_port(&mut self) -> Option<u16> {
230 self.read_atomically(|p| {
231 p.read_given_char(':')?;
232 p.read_number(10, None, true)
233 })
234 }
235
236 fn read_scope_id(&mut self) -> Option<u32> {
238 self.read_atomically(|p| {
239 p.read_given_char('%')?;
240 p.read_number(10, None, true)
241 })
242 }
243
244 fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> {
246 self.read_atomically(|p| {
247 let ip = p.read_ipv4_addr()?;
248 let port = p.read_port()?;
249 Some(SocketAddrV4::new(ip, port))
250 })
251 }
252
253 fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> {
255 self.read_atomically(|p| {
256 p.read_given_char('[')?;
257 let ip = p.read_ipv6_addr()?;
258 let scope_id = p.read_scope_id().unwrap_or(0);
259 p.read_given_char(']')?;
260
261 let port = p.read_port()?;
262 Some(SocketAddrV6::new(ip, port, 0, scope_id))
263 })
264 }
265
266 fn read_socket_addr(&mut self) -> Option<SocketAddr> {
268 self.read_socket_addr_v4()
269 .map(SocketAddr::V4)
270 .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6))
271 }
272}
273
274impl IpAddr {
275 pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
287 Parser::new(b).parse_with(|p| p.read_ip_addr(), AddrKind::Ip)
288 }
289}
290
291impl FromStr for IpAddr {
292 type Err = AddrParseError;
293 fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
294 Self::parse_ascii(s.as_bytes())
295 }
296}
297
298impl Ipv4Addr {
299 pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
309 if b.len() > 15 {
311 Err(AddrParseError(AddrKind::Ipv4))
312 } else {
313 Parser::new(b).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4)
314 }
315 }
316}
317
318impl FromStr for Ipv4Addr {
319 type Err = AddrParseError;
320 fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
321 Self::parse_ascii(s.as_bytes())
322 }
323}
324
325impl Ipv6Addr {
326 pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
336 Parser::new(b).parse_with(|p| p.read_ipv6_addr(), AddrKind::Ipv6)
337 }
338}
339
340impl FromStr for Ipv6Addr {
341 type Err = AddrParseError;
342 fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
343 Self::parse_ascii(s.as_bytes())
344 }
345}
346
347impl SocketAddrV4 {
348 pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
358 Parser::new(b).parse_with(|p| p.read_socket_addr_v4(), AddrKind::SocketV4)
359 }
360}
361
362impl FromStr for SocketAddrV4 {
363 type Err = AddrParseError;
364 fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> {
365 Self::parse_ascii(s.as_bytes())
366 }
367}
368
369impl SocketAddrV6 {
370 pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
380 Parser::new(b).parse_with(|p| p.read_socket_addr_v6(), AddrKind::SocketV6)
381 }
382}
383
384impl FromStr for SocketAddrV6 {
385 type Err = AddrParseError;
386 fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> {
387 Self::parse_ascii(s.as_bytes())
388 }
389}
390
391impl SocketAddr {
392 pub fn parse_ascii(b: &[u8]) -> Result<Self, AddrParseError> {
404 Parser::new(b).parse_with(|p| p.read_socket_addr(), AddrKind::Socket)
405 }
406}
407
408impl FromStr for SocketAddr {
409 type Err = AddrParseError;
410 fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> {
411 Self::parse_ascii(s.as_bytes())
412 }
413}
414
415#[derive(Debug, Clone, PartialEq, Eq)]
416enum AddrKind {
417 Ip,
418 Ipv4,
419 Ipv6,
420 Socket,
421 SocketV4,
422 SocketV6,
423}
424
425#[derive(Debug, Clone, PartialEq, Eq)]
450pub struct AddrParseError(AddrKind);
451
452impl fmt::Display for AddrParseError {
453 #[allow(deprecated, deprecated_in_future)]
454 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
455 fmt.write_str(self.description())
456 }
457}
458
459impl Error for AddrParseError {
460 #[allow(deprecated)]
461 fn description(&self) -> &str {
462 match self.0 {
463 AddrKind::Ip => "invalid IP address syntax",
464 AddrKind::Ipv4 => "invalid IPv4 address syntax",
465 AddrKind::Ipv6 => "invalid IPv6 address syntax",
466 AddrKind::Socket => "invalid socket address syntax",
467 AddrKind::SocketV4 => "invalid IPv4 socket address syntax",
468 AddrKind::SocketV6 => "invalid IPv6 socket address syntax",
469 }
470 }
471}