1 //! A private parser implementation of IPv4, IPv6, and socket addresses.
3 //! This module is "publicly exported" through the `FromStr` implementations
9 use crate::convert::TryInto as _;
10 use crate::error::Error;
12 use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
13 use crate::str::FromStr;
15 trait ReadNumberHelper: crate::marker::Sized {
17 fn checked_mul(&self, other: u32) -> Option<Self>;
18 fn checked_add(&self, other: u32) -> Option<Self>;
21 macro_rules! impl_helper {
22 ($($t:ty)*) => ($(impl ReadNumberHelper for $t {
25 fn checked_mul(&self, other: u32) -> Option<Self> {
26 Self::checked_mul(*self, other.try_into().ok()?)
29 fn checked_add(&self, other: u32) -> Option<Self> {
30 Self::checked_add(*self, other.try_into().ok()?)
35 impl_helper! { u8 u16 }
38 // parsing as ASCII, so can use byte array
43 fn new(input: &'a str) -> Parser<'a> {
44 Parser { state: input.as_bytes() }
47 fn is_eof(&self) -> bool {
51 /// Run a parser, and restore the pre-parse state if it fails
52 fn read_atomically<T, F>(&mut self, inner: F) -> Option<T>
54 F: FnOnce(&mut Parser<'_>) -> Option<T>,
56 let state = self.state;
57 let result = inner(self);
64 /// Run a parser, but fail if the entire input wasn't consumed.
65 /// Doesn't run atomically.
66 fn read_till_eof<T, F>(&mut self, inner: F) -> Option<T>
68 F: FnOnce(&mut Parser<'_>) -> Option<T>,
70 inner(self).filter(|_| self.is_eof())
73 /// Same as read_till_eof, but returns a Result<AddrParseError> on failure
74 fn parse_with<T, F>(&mut self, inner: F) -> Result<T, AddrParseError>
76 F: FnOnce(&mut Parser<'_>) -> Option<T>,
78 self.read_till_eof(inner).ok_or(AddrParseError(()))
81 /// Read the next character from the input
82 fn read_char(&mut self) -> Option<char> {
83 self.state.split_first().map(|(&b, tail)| {
89 /// Read the next character from the input if it matches the target
90 fn read_given_char(&mut self, target: char) -> Option<char> {
91 self.read_atomically(|p| p.read_char().filter(|&c| c == target))
94 /// Helper for reading separators in an indexed loop. Reads the separator
95 /// character iff index > 0, then runs the parser. When used in a loop,
96 /// the separator character will only be read on index > 0 (see
97 /// read_ipv4_addr for an example)
98 fn read_separator<T, F>(&mut self, sep: char, index: usize, inner: F) -> Option<T>
100 F: FnOnce(&mut Parser<'_>) -> Option<T>,
102 self.read_atomically(move |p| {
104 let _ = p.read_given_char(sep)?;
110 // Read a number off the front of the input in the given radix, stopping
111 // at the first non-digit character or eof. Fails if the number has more
112 // digits than max_digits or if there is no number.
113 fn read_number<T: ReadNumberHelper>(
116 max_digits: Option<usize>,
118 self.read_atomically(move |p| {
119 let mut result = T::ZERO;
120 let mut digit_count = 0;
122 while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
123 result = result.checked_mul(radix)?;
124 result = result.checked_add(digit)?;
126 if let Some(max_digits) = max_digits {
127 if digit_count > max_digits {
133 if digit_count == 0 { None } else { Some(result) }
137 /// Read an IPv4 address
138 fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
139 self.read_atomically(|p| {
140 let mut groups = [0; 4];
142 for (i, slot) in groups.iter_mut().enumerate() {
143 *slot = p.read_separator('.', i, |p| p.read_number(10, None))?;
150 /// Read an IPV6 Address
151 fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
152 /// Read a chunk of an ipv6 address into `groups`. Returns the number
153 /// of groups read, along with a bool indicating if an embedded
154 /// trailing ipv4 address was read. Specifically, read a series of
155 /// colon-separated ipv6 groups (0x0000 - 0xFFFF), with an optional
156 /// trailing embedded ipv4 address.
157 fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) {
158 let limit = groups.len();
160 for (i, slot) in groups.iter_mut().enumerate() {
161 // Try to read a trailing embedded ipv4 address. There must be
162 // at least two groups left.
164 let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
166 if let Some(v4_addr) = ipv4 {
167 let [one, two, three, four] = v4_addr.octets();
168 groups[i + 0] = u16::from_be_bytes([one, two]);
169 groups[i + 1] = u16::from_be_bytes([three, four]);
170 return (i + 2, true);
174 let group = p.read_separator(':', i, |p| p.read_number(16, Some(4)));
177 Some(g) => *slot = g,
178 None => return (i, false),
181 (groups.len(), false)
184 self.read_atomically(|p| {
185 // Read the front part of the address; either the whole thing, or up
187 let mut head = [0; 8];
188 let (head_size, head_ipv4) = read_groups(p, &mut head);
191 return Some(head.into());
194 // IPv4 part is not allowed before `::`
199 // read `::` if previous code parsed less than 8 groups
200 // `::` indicates one or more groups of 16 bits of zeros
201 let _ = p.read_given_char(':')?;
202 let _ = p.read_given_char(':')?;
204 // Read the back part of the address. The :: must contain at least one
205 // set of zeroes, so our max length is 7.
206 let mut tail = [0; 7];
207 let limit = 8 - (head_size + 1);
208 let (tail_size, _) = read_groups(p, &mut tail[..limit]);
210 // Concat the head and tail of the IP address
211 head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
217 /// Read an IP Address, either IPV4 or IPV6.
218 fn read_ip_addr(&mut self) -> Option<IpAddr> {
219 self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6))
222 /// Read a : followed by a port in base 10.
223 fn read_port(&mut self) -> Option<u16> {
224 self.read_atomically(|p| {
225 let _ = p.read_given_char(':')?;
226 p.read_number(10, None)
230 /// Read an IPV4 address with a port
231 fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> {
232 self.read_atomically(|p| {
233 let ip = p.read_ipv4_addr()?;
234 let port = p.read_port()?;
235 Some(SocketAddrV4::new(ip, port))
239 /// Read an IPV6 address with a port
240 fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> {
241 self.read_atomically(|p| {
242 let _ = p.read_given_char('[')?;
243 let ip = p.read_ipv6_addr()?;
244 let _ = p.read_given_char(']')?;
246 let port = p.read_port()?;
247 Some(SocketAddrV6::new(ip, port, 0, 0))
251 /// Read an IP address with a port
252 fn read_socket_addr(&mut self) -> Option<SocketAddr> {
253 self.read_socket_addr_v4()
255 .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6))
259 #[stable(feature = "ip_addr", since = "1.7.0")]
260 impl FromStr for IpAddr {
261 type Err = AddrParseError;
262 fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
263 Parser::new(s).parse_with(|p| p.read_ip_addr())
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl FromStr for Ipv4Addr {
269 type Err = AddrParseError;
270 fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
271 Parser::new(s).parse_with(|p| p.read_ipv4_addr())
275 #[stable(feature = "rust1", since = "1.0.0")]
276 impl FromStr for Ipv6Addr {
277 type Err = AddrParseError;
278 fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
279 Parser::new(s).parse_with(|p| p.read_ipv6_addr())
283 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
284 impl FromStr for SocketAddrV4 {
285 type Err = AddrParseError;
286 fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> {
287 Parser::new(s).parse_with(|p| p.read_socket_addr_v4())
291 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
292 impl FromStr for SocketAddrV6 {
293 type Err = AddrParseError;
294 fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> {
295 Parser::new(s).parse_with(|p| p.read_socket_addr_v6())
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl FromStr for SocketAddr {
301 type Err = AddrParseError;
302 fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> {
303 Parser::new(s).parse_with(|p| p.read_socket_addr())
307 /// An error which can be returned when parsing an IP address or a socket address.
309 /// This error is used as the error type for the [`FromStr`] implementation for
310 /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and
311 /// [`SocketAddrV6`].
313 /// # Potential causes
315 /// `AddrParseError` may be thrown because the provided string does not parse as the given type,
316 /// often because it includes information only handled by a different address type.
319 /// use std::net::IpAddr;
320 /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port");
323 /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead.
326 /// use std::net::SocketAddr;
328 /// // No problem, the `panic!` message has disappeared.
329 /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic");
331 #[stable(feature = "rust1", since = "1.0.0")]
332 #[derive(Debug, Clone, PartialEq, Eq)]
333 pub struct AddrParseError(());
335 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
336 impl fmt::Display for AddrParseError {
337 #[allow(deprecated, deprecated_in_future)]
338 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
339 fmt.write_str(self.description())
343 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
344 impl Error for AddrParseError {
346 fn description(&self) -> &str {
347 "invalid IP address syntax"