Skip to content

Commit b41d0b9

Browse files
authored
Resolve arith overflow on with_capacity (#628)
Closes #626 #627
1 parent 25c1803 commit b41d0b9

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/header/map.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,10 @@ impl<T> HeaderMap<T> {
452452
/// allocations before `capacity` headers are stored in the map.
453453
///
454454
/// More capacity than requested may be allocated.
455+
///
456+
/// # Panics
457+
///
458+
/// Requested capacity too large: would overflow `usize`.
455459
///
456460
/// # Examples
457461
///
@@ -472,7 +476,13 @@ impl<T> HeaderMap<T> {
472476
danger: Danger::Green,
473477
}
474478
} else {
475-
let raw_cap = to_raw_capacity(capacity).next_power_of_two();
479+
let raw_cap = match to_raw_capacity(capacity).checked_next_power_of_two() {
480+
Some(c) => c,
481+
None => panic!(
482+
"requested capacity {} too large: next power of two would overflow `usize`",
483+
capacity
484+
),
485+
};
476486
assert!(raw_cap <= MAX_SIZE, "requested capacity too large");
477487
debug_assert!(raw_cap > 0);
478488

@@ -3218,7 +3228,13 @@ fn usable_capacity(cap: usize) -> usize {
32183228

32193229
#[inline]
32203230
fn to_raw_capacity(n: usize) -> usize {
3221-
n + n / 3
3231+
match n.checked_add(n / 3) {
3232+
Some(n) => n,
3233+
None => panic!(
3234+
"requested capacity {} too large: overflow while converting to raw capacity",
3235+
n
3236+
),
3237+
}
32223238
}
32233239

32243240
#[inline]

0 commit comments

Comments
 (0)