hyperium / hyperium/http

[feature request] `get_one`, `get_one_mut` on `HeadersMap`

Open
#295 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
1.4k
Forks
378
Avg merge
1d 21h
Merged PRs (30d)
5

Description

I'll write this like a proposal:

Motivation

I want to be able to get a header from a HeadersMap, and also assert that there is exactly one header with the given name. Currently I do what I'm proposing here, but in my client library. I think this is functionality that would be useful to multiple consumers of http and so maybe could be in the library itself.

Proposal

Introduce functions get_one and get_one_mut on HeadersMap, with the following implementation (or equivalent, more performant impl):

impl<T> HeaderMap<T> {
    pub fn get_one<K>(&self, key: K) -> Result<&T, GetOneError> 
        where K: AsHeaderName
    {
        let mut iter = self.get_all(key);
        let value = match iter.next() {
             Some(v) => v,
             None => return Err(GetOneError::Missing)
        };
        if let Some(_) = iter.next() {
            Err(GetOneError::Multiple);
        } else {
            Ok(value)
        }
    }
}

with a similar impl for get_one_mut, and the implied GetOneError std::error::Error.

You could probably get the count for Multiple without hitting the happy path, if that was considered worthwhile.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating HeadersMap and its existing get_all API, then review nearby tests and error types. Implement the proposed get_one and get_one_mut behavior so missing and multiple values return distinct errors while exactly one value returns successfully, and verify both shared and mutable access.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
api
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.