Skip to content

speed up parsing for short ipv4s in std::net::Ipv4Addr::from_str #97118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions library/std/src/net/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ impl<'a> Parser<'a> {
where
F: FnOnce(&mut Parser<'_>) -> Option<T>,
{
// 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))
}
Expand Down Expand Up @@ -285,12 +292,7 @@ impl FromStr for IpAddr {
impl FromStr for Ipv4Addr {
type Err = AddrParseError;
fn from_str(s: &str) -> Result<Ipv4Addr, AddrParseError> {
// 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)
}
}

Expand Down Expand Up @@ -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
Expand Down