From b41d0b98838fa21573aebba9ef3960b7680f571c Mon Sep 17 00:00:00 2001 From: BlakStar Date: Fri, 10 Nov 2023 22:58:58 +0900 Subject: [PATCH] Resolve arith overflow on with_capacity (#628) Closes #626 #627 --- src/header/map.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/header/map.rs b/src/header/map.rs index e243c7c1..dd0f262a 100644 --- a/src/header/map.rs +++ b/src/header/map.rs @@ -452,6 +452,10 @@ impl HeaderMap { /// 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 /// @@ -472,7 +476,13 @@ impl HeaderMap { 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); @@ -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 + ), + } } #[inline]