Skip to content
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

refactor: standardize duplicate processes in parser #128641

Merged
Merged
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
refactor: standardize duplicate processes in parser
  • Loading branch information
Konippi committed Aug 4, 2024
commit 341511ad4e0405f606d434265b00120f782914d0
56 changes: 24 additions & 32 deletions library/core/src/net/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,18 @@ impl<'a> Parser<'a> {
max_digits: Option<usize>,
allow_zero_prefix: bool,
) -> Option<T> {
// If max_digits.is_some(), then we are parsing a `u8` or `u16` and
// don't need to use checked arithmetic since it fits within a `u32`.
if let Some(max_digits) = max_digits {
// u32::MAX = 4_294_967_295u32, which is 10 digits long.
// `max_digits` must be less than 10 to not overflow a `u32`.
debug_assert!(max_digits < 10);

self.read_atomically(move |p| {
let mut result = 0_u32;
let mut digit_count = 0;
let has_leading_zero = p.peek_char() == Some('0');
self.read_atomically(move |p| {
let mut digit_count = 0;
let has_leading_zero = p.peek_char() == Some('0');

// If max_digits.is_some(), then we are parsing a `u8` or `u16` and
// don't need to use checked arithmetic since it fits within a `u32`.
let result = if let Some(max_digits) = max_digits {
// u32::MAX = 4_294_967_295u32, which is 10 digits long.
// `max_digits` must be less than 10 to not overflow a `u32`.
debug_assert!(max_digits < 10);

let mut result = 0_u32;
while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
result *= radix;
result += digit;
Expand All @@ -134,35 +134,27 @@ impl<'a> Parser<'a> {
}
}

if digit_count == 0 {
None
} else if !allow_zero_prefix && has_leading_zero && digit_count > 1 {
None
} else {
result.try_into().ok()
}
})
} else {
self.read_atomically(move |p| {
result.try_into().ok()
} else {
let mut result = T::ZERO;
let mut digit_count = 0;
let has_leading_zero = p.peek_char() == Some('0');

while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
result = result.checked_mul(radix)?;
result = result.checked_add(digit)?;
digit_count += 1;
}

if digit_count == 0 {
None
} else if !allow_zero_prefix && has_leading_zero && digit_count > 1 {
None
} else {
Some(result)
}
})
}
Some(result)
};

if digit_count == 0 {
None
} else if !allow_zero_prefix && has_leading_zero && digit_count > 1 {
None
} else {
result
}
})
}

/// Reads an IPv4 address.
Expand Down
Loading