1 //! A private parser implementation of IPv4, IPv6, and socket addresses.
3 //! This module is "publicly exported" through the `FromStr` implementations
9 use crate::error::Error;
11 use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
12 use crate::str::FromStr;
14 trait ReadNumberHelper: crate::marker::Sized {
16 fn checked_mul(&self, other: u32) -> Option<Self>;
17 fn checked_add(&self, other: u32) -> Option<Self>;
20 macro_rules! impl_helper {
21 ($($t:ty)*) => ($(impl ReadNumberHelper for $t {
24 fn checked_mul(&self, other: u32) -> Option<Self> {
25 Self::checked_mul(*self, other.try_into().ok()?)
28 fn checked_add(&self, other: u32) -> Option<Self> {
29 Self::checked_add(*self, other.try_into().ok()?)
34 impl_helper! { u8 u16 u32 }
37 // Parsing as ASCII, so can use byte array.
42 fn new(input: &'a str) -> Parser<'a> {
43 Parser { state: input.as_bytes() }
46 /// Run a parser, and restore the pre-parse state if it fails.
47 fn read_atomically<T, F>(&mut self, inner: F) -> Option<T>
49 F: FnOnce(&mut Parser<'_>) -> Option<T>,
51 let state = self.state;
52 let result = inner(self);
59 /// Run a parser, but fail if the entire input wasn't consumed.
60 /// Doesn't run atomically.
61 fn parse_with<T, F>(&mut self, inner: F, kind: AddrKind) -> Result<T, AddrParseError>
63 F: FnOnce(&mut Parser<'_>) -> Option<T>,
65 let result = inner(self);
66 if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind))
69 /// Peek the next character from the input
70 fn peek_char(&self) -> Option<char> {
71 self.state.first().map(|&b| char::from(b))
74 /// Read the next character from the input
75 fn read_char(&mut self) -> Option<char> {
76 self.state.split_first().map(|(&b, tail)| {
83 /// Read the next character from the input if it matches the target.
84 fn read_given_char(&mut self, target: char) -> Option<()> {
85 self.read_atomically(|p| {
86 p.read_char().and_then(|c| if c == target { Some(()) } else { None })
90 /// Helper for reading separators in an indexed loop. Reads the separator
91 /// character iff index > 0, then runs the parser. When used in a loop,
92 /// the separator character will only be read on index > 0 (see
93 /// read_ipv4_addr for an example)
94 fn read_separator<T, F>(&mut self, sep: char, index: usize, inner: F) -> Option<T>
96 F: FnOnce(&mut Parser<'_>) -> Option<T>,
98 self.read_atomically(move |p| {
100 p.read_given_char(sep)?;
106 // Read a number off the front of the input in the given radix, stopping
107 // at the first non-digit character or eof. Fails if the number has more
108 // digits than max_digits or if there is no number.
109 fn read_number<T: ReadNumberHelper>(
112 max_digits: Option<usize>,
113 allow_zero_prefix: bool,
115 self.read_atomically(move |p| {
116 let mut result = T::ZERO;
117 let mut digit_count = 0;
118 let has_leading_zero = p.peek_char() == Some('0');
120 while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
121 result = result.checked_mul(radix)?;
122 result = result.checked_add(digit)?;
124 if let Some(max_digits) = max_digits {
125 if digit_count > max_digits {
131 if digit_count == 0 {
133 } else if !allow_zero_prefix && has_leading_zero && digit_count > 1 {
141 /// Read an IPv4 address.
142 fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
143 self.read_atomically(|p| {
144 let mut groups = [0; 4];
146 for (i, slot) in groups.iter_mut().enumerate() {
147 *slot = p.read_separator('.', i, |p| {
148 // Disallow octal number in IP string.
149 // https://tools.ietf.org/html/rfc6943#section-3.1.1
150 p.read_number(10, Some(3), false)
158 /// Read an IPv6 Address.
159 fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
160 /// Read a chunk of an IPv6 address into `groups`. Returns the number
161 /// of groups read, along with a bool indicating if an embedded
162 /// trailing IPv4 address was read. Specifically, read a series of
163 /// colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional
164 /// trailing embedded IPv4 address.
165 fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) {
166 let limit = groups.len();
168 for (i, slot) in groups.iter_mut().enumerate() {
169 // Try to read a trailing embedded IPv4 address. There must be
170 // at least two groups left.
172 let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
174 if let Some(v4_addr) = ipv4 {
175 let [one, two, three, four] = v4_addr.octets();
176 groups[i + 0] = u16::from_be_bytes([one, two]);
177 groups[i + 1] = u16::from_be_bytes([three, four]);
178 return (i + 2, true);
182 let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true));
185 Some(g) => *slot = g,
186 None => return (i, false),
189 (groups.len(), false)
192 self.read_atomically(|p| {
193 // Read the front part of the address; either the whole thing, or up
195 let mut head = [0; 8];
196 let (head_size, head_ipv4) = read_groups(p, &mut head);
199 return Some(head.into());
202 // IPv4 part is not allowed before `::`
207 // Read `::` if previous code parsed less than 8 groups.
208 // `::` indicates one or more groups of 16 bits of zeros.
209 p.read_given_char(':')?;
210 p.read_given_char(':')?;
212 // Read the back part of the address. The :: must contain at least one
213 // set of zeroes, so our max length is 7.
214 let mut tail = [0; 7];
215 let limit = 8 - (head_size + 1);
216 let (tail_size, _) = read_groups(p, &mut tail[..limit]);
218 // Concat the head and tail of the IP address
219 head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
225 /// Read an IP Address, either IPv4 or IPv6.
226 fn read_ip_addr(&mut self) -> Option<IpAddr> {
227 self.read_ipv4_addr().map(IpAddr::V4).or_else(move || self.read_ipv6_addr().map(IpAddr::V6))
230 /// Read a `:` followed by a port in base 10.
231 fn read_port(&mut self) -> Option<u16> {
232 self.read_atomically(|p| {
233 p.read_given_char(':')?;
234 p.read_number(10, None, true)
238 /// Read a `%` followed by a scope ID in base 10.
239 fn read_scope_id(&mut self) -> Option<u32> {
240 self.read_atomically(|p| {
241 p.read_given_char('%')?;
242 p.read_number(10, None, true)
246 /// Read an IPv4 address with a port.
247 fn read_socket_addr_v4(&mut self) -> Option<SocketAddrV4> {
248 self.read_atomically(|p| {
249 let ip = p.read_ipv4_addr()?;
250 let port = p.read_port()?;
251 Some(SocketAddrV4::new(ip, port))
255 /// Read an IPv6 address with a port.
256 fn read_socket_addr_v6(&mut self) -> Option<SocketAddrV6> {
257 self.read_atomically(|p| {
258 p.read_given_char('[')?;
259 let ip = p.read_ipv6_addr()?;
260 let scope_id = p.read_scope_id().unwrap_or(0);
261 p.read_given_char(']')?;
263 let port = p.read_port()?;
264 Some(SocketAddrV6::new(ip, port, 0, scope_id))
268 /// Read an IP address with a port
269 fn read_socket_addr(&mut self) -> Option<SocketAddr> {
270 self.read_socket_addr_v4()
272 .or_else(|| self.read_socket_addr_v6().map(SocketAddr::V6))
276 #[stable(feature = "ip_addr", since = "1.7.0")]
277 impl FromStr for IpAddr {
278 type Err = AddrParseError;
279 fn from_str(s: &str) -> Result<IpAddr, AddrParseError> {
280 Parser::new(s).parse_with(|p| p.read_ip_addr(), AddrKind::Ip)
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl FromStr for Ipv4Addr {
286 type Err = AddrParseError;
287 fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
288 // don't try to parse if too long
290 Err(AddrParseError(AddrKind::Ipv4))
292 Parser::new(s).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4)
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl FromStr for Ipv6Addr {
299 type Err = AddrParseError;
300 fn from_str(s: &str) -> Result<Ipv6Addr, AddrParseError> {
301 Parser::new(s).parse_with(|p| p.read_ipv6_addr(), AddrKind::Ipv6)
305 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
306 impl FromStr for SocketAddrV4 {
307 type Err = AddrParseError;
308 fn from_str(s: &str) -> Result<SocketAddrV4, AddrParseError> {
309 Parser::new(s).parse_with(|p| p.read_socket_addr_v4(), AddrKind::SocketV4)
313 #[stable(feature = "socket_addr_from_str", since = "1.5.0")]
314 impl FromStr for SocketAddrV6 {
315 type Err = AddrParseError;
316 fn from_str(s: &str) -> Result<SocketAddrV6, AddrParseError> {
317 Parser::new(s).parse_with(|p| p.read_socket_addr_v6(), AddrKind::SocketV6)
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl FromStr for SocketAddr {
323 type Err = AddrParseError;
324 fn from_str(s: &str) -> Result<SocketAddr, AddrParseError> {
325 Parser::new(s).parse_with(|p| p.read_socket_addr(), AddrKind::Socket)
329 #[derive(Debug, Clone, PartialEq, Eq)]
339 /// An error which can be returned when parsing an IP address or a socket address.
341 /// This error is used as the error type for the [`FromStr`] implementation for
342 /// [`IpAddr`], [`Ipv4Addr`], [`Ipv6Addr`], [`SocketAddr`], [`SocketAddrV4`], and
343 /// [`SocketAddrV6`].
345 /// # Potential causes
347 /// `AddrParseError` may be thrown because the provided string does not parse as the given type,
348 /// often because it includes information only handled by a different address type.
351 /// use std::net::IpAddr;
352 /// let _foo: IpAddr = "127.0.0.1:8080".parse().expect("Cannot handle the socket port");
355 /// [`IpAddr`] doesn't handle the port. Use [`SocketAddr`] instead.
358 /// use std::net::SocketAddr;
360 /// // No problem, the `panic!` message has disappeared.
361 /// let _foo: SocketAddr = "127.0.0.1:8080".parse().expect("unreachable panic");
363 #[stable(feature = "rust1", since = "1.0.0")]
364 #[derive(Debug, Clone, PartialEq, Eq)]
365 pub struct AddrParseError(AddrKind);
367 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
368 impl fmt::Display for AddrParseError {
369 #[allow(deprecated, deprecated_in_future)]
370 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
371 fmt.write_str(self.description())
375 #[stable(feature = "addr_parse_error_error", since = "1.4.0")]
376 impl Error for AddrParseError {
378 fn description(&self) -> &str {
380 AddrKind::Ip => "invalid IP address syntax",
381 AddrKind::Ipv4 => "invalid IPv4 address syntax",
382 AddrKind::Ipv6 => "invalid IPv6 address syntax",
383 AddrKind::Socket => "invalid socket address syntax",
384 AddrKind::SocketV4 => "invalid IPv4 socket address syntax",
385 AddrKind::SocketV6 => "invalid IPv6 socket address syntax",