Skip to content

try_reserve can panic despite "try" prefix suggesting error handling #785

@AriajSarkar

Description

@AriajSarkar

The try_reserve method in HeaderMap can panic even though its name and signature suggest it should return an error instead. This violates Rust conventions where try_* methods should handle errors gracefully.

Location:

  • File: src/header/map.rs
  • Method: try_reserve (line 744)
  • Helper function: to_raw_capacity (line 3624)

Problem:

The to_raw_capacity helper function panics on overflow:

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

This function is called from try_reserve at line 753:

pub fn try_reserve(&mut self, additional: usize) -> Result<(), MaxSizeReached> {
    let cap = self
        .entries
        .len()
        .checked_add(additional)
        .ok_or_else(MaxSizeReached::new)?;

    let raw_cap = to_raw_capacity(cap);  // ← CAN PANIC HERE
    
    if raw_cap > self.indices.len() {
        let raw_cap = raw_cap
            .checked_next_power_of_two()
            .ok_or_else(MaxSizeReached::new)?;
        // ...
    }
}

I have a potential fix for this. Should I submit a PR?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions