Skip to content

Resolve arith overflow on with_capacity #628

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

Merged
merged 3 commits into from
Nov 10, 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
20 changes: 18 additions & 2 deletions src/header/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,10 @@ impl<T> HeaderMap<T> {
/// allocations before `capacity` headers are stored in the map.
///
/// More capacity than requested may be allocated.
///
/// # Panics
///
/// Requested capacity too large: would overflow `usize`.
///
/// # Examples
///
Expand All @@ -472,7 +476,13 @@ impl<T> HeaderMap<T> {
danger: Danger::Green,
}
} else {
let raw_cap = to_raw_capacity(capacity).next_power_of_two();
let raw_cap = match to_raw_capacity(capacity).checked_next_power_of_two() {
Some(c) => c,
None => panic!(
"requested capacity {} too large: next power of two would overflow `usize`",
capacity
),
};
assert!(raw_cap <= MAX_SIZE, "requested capacity too large");
debug_assert!(raw_cap > 0);

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

#[inline]
fn to_raw_capacity(n: usize) -> usize {
n + n / 3
match n.checked_add(n / 3) {
Some(n) => n,
None => panic!(
"requested capacity {} too large: overflow while converting to raw capacity",
n
),
}
Comment on lines +3231 to +3237
Copy link
Contributor

@WhyNotHugo WhyNotHugo Sep 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH, this could just be:

n.checked_add(n / 3).expect("requested capacity must fit usize without overflow")

The only downside if that the requested capacity is not shown in the error, so maybe you'll want to hear what the maintainers think before applying any changes.

(the same applies to the above match that basically hand-rolls an expect).

}

#[inline]
Expand Down