diff --git a/library/std/src/net/parser.rs b/library/std/src/net/parser.rs index 069b660998559..5c5ff90fa518c 100644 --- a/library/std/src/net/parser.rs +++ b/library/std/src/net/parser.rs @@ -62,6 +62,13 @@ impl<'a> Parser<'a> { where F: FnOnce(&mut Parser<'_>) -> Option, { + // don't try to parse if too short or too long + if self.state.len() > kind.max_string_length() + || self.state.len() < kind.min_string_length() + { + return Err(AddrParseError(kind)); + } + let result = inner(self); if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind)) } @@ -285,12 +292,7 @@ impl FromStr for IpAddr { impl FromStr for Ipv4Addr { type Err = AddrParseError; fn from_str(s: &str) -> Result { - // don't try to parse if too long - if s.len() > 15 { - Err(AddrParseError(AddrKind::Ipv4)) - } else { - Parser::new(s).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4) - } + Parser::new(s).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4) } } @@ -336,6 +338,26 @@ enum AddrKind { SocketV6, } +impl AddrKind { + // the minimum length of a parsable string with this `AddrKind` + const fn min_string_length(&self) -> usize { + match self { + Self::Ip | Self::Ipv4 => 7, + // FIXME + _ => 0, + } + } + + // the maximum length of a parsable string with this `AddrKind` + const fn max_string_length(&self) -> usize { + match self { + Self::Ipv4 => 15, + // FIXME + _ => usize::MAX, + } + } +} + /// An error which can be returned when parsing an IP address or a socket address. /// /// This error is used as the error type for the [`FromStr`] implementation for