Skip to content

Commit 1092960

Browse files
authored
Avoid string allocation to get length of port (#823)
1 parent 74b8694 commit 1092960

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

url/src/slicing.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,29 @@ impl Index<Range<Position>> for Url {
3737
}
3838
}
3939

40+
// Counts how many base-10 digits are required to represent n in the given base
41+
fn count_digits(n: u16) -> usize {
42+
match n {
43+
0..=9 => 1,
44+
10..=99 => 2,
45+
100..=999 => 3,
46+
1000..=9999 => 4,
47+
10000..=65535 => 5,
48+
}
49+
}
50+
51+
#[test]
52+
fn test_count_digits() {
53+
assert_eq!(count_digits(0), 1);
54+
assert_eq!(count_digits(1), 1);
55+
assert_eq!(count_digits(9), 1);
56+
assert_eq!(count_digits(10), 2);
57+
assert_eq!(count_digits(99), 2);
58+
assert_eq!(count_digits(100), 3);
59+
assert_eq!(count_digits(9999), 4);
60+
assert_eq!(count_digits(65535), 5);
61+
}
62+
4063
/// Indicates a position within a URL based on its components.
4164
///
4265
/// A range of positions can be used for slicing `Url`:
@@ -152,7 +175,7 @@ impl Url {
152175
Position::AfterPort => {
153176
if let Some(port) = self.port {
154177
debug_assert!(self.byte_at(self.host_end) == b':');
155-
self.host_end as usize + ":".len() + port.to_string().len()
178+
self.host_end as usize + ":".len() + count_digits(port)
156179
} else {
157180
self.host_end as usize
158181
}

0 commit comments

Comments
 (0)