Skip to content

Commit

Permalink
Avoid string allocation to get length of port (#823)
Browse files Browse the repository at this point in the history
  • Loading branch information
qsantos authored Mar 7, 2023
1 parent 74b8694 commit 1092960
Showing 1 changed file with 24 additions and 1 deletion.
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

0 comments on commit 1092960

Please sign in to comment.