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

Avoid string allocation to get length of port #823

Merged
merged 3 commits into from
Mar 7, 2023
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
25 changes: 24 additions & 1 deletion url/src/slicing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@ impl Index<Range<Position>> for Url {
}
}

// Counts how many base-10 digits are required to represent n in the given base
fn count_digits(n: u16) -> usize {
match n {
0..=9 => 1,
10..=99 => 2,
100..=999 => 3,
1000..=9999 => 4,
10000..=65535 => 5,
}
}

#[test]
fn test_count_digits() {
assert_eq!(count_digits(0), 1);
assert_eq!(count_digits(1), 1);
assert_eq!(count_digits(9), 1);
assert_eq!(count_digits(10), 2);
assert_eq!(count_digits(99), 2);
assert_eq!(count_digits(100), 3);
assert_eq!(count_digits(9999), 4);
assert_eq!(count_digits(65535), 5);
}

/// Indicates a position within a URL based on its components.
///
/// A range of positions can be used for slicing `Url`:
Expand Down Expand Up @@ -152,7 +175,7 @@ impl Url {
Position::AfterPort => {
if let Some(port) = self.port {
debug_assert!(self.byte_at(self.host_end) == b':');
self.host_end as usize + ":".len() + port.to_string().len()
self.host_end as usize + ":".len() + count_digits(port)
} else {
self.host_end as usize
}
Expand Down