ruvel 0.15.0

The laravel alternative framework with rust performance
Documentation
use std::borrow::Cow;

/// A lightweight, low-allocation case-insensitive HTTP header map.
///
/// Header field names are case-insensitive according to RFC 9110 (Section 5.1).
/// Uses an inline/small vector structure where keys and values can be borrowed (`Cow::Borrowed`)
/// or owned (`Cow::Owned`), avoiding unnecessary heap allocations on parse and lookup.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Headers {
    // Stores (original_key, value)
    entries: Vec<(Cow<'static, str>, Cow<'static, str>)>,
}

impl Headers {
    /// Create a new, empty `Headers`.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Create a new `Headers` with pre-allocated capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            entries: Vec::with_capacity(capacity),
        }
    }

    /// Create a `Headers` with a single initial entry, avoiding over-allocation and
    /// duplicate-key scanning when constructing standard responses.
    pub(crate) fn with_single(
        key: impl Into<Cow<'static, str>>,
        value: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self {
            entries: vec![(key.into(), value.into())],
        }
    }

    /// Insert a header name-value pair while preserving the original header name casing.
    ///
    /// Singleton headers (`Host`, `Content-Type`, `Content-Length`, `Authorization`, etc.) overwrite
    /// any existing case-insensitive match; multi-value headers (`Set-Cookie`, `Cookie`,
    /// `Connection`, `X-*`, etc.) append additional entries.
    pub fn insert(
        &mut self,
        key: impl Into<Cow<'static, str>>,
        value: impl Into<Cow<'static, str>>,
    ) {
        let key = key.into();
        let value = value.into();

        if is_single_value_header(&key)
            && let Some(entry) = self
                .entries
                .iter_mut()
                .find(|(k, _)| k.eq_ignore_ascii_case(&key))
        {
            entry.0 = key;
            entry.1 = value;
            return;
        }

        self.entries.push((key, value));
    }

    /// Push a header pair directly without duplicate scanning.
    #[inline]
    pub(crate) fn push_direct(&mut self, key: Cow<'static, str>, value: Cow<'static, str>) {
        self.entries.push((key, value));
    }

    /// Returns `true` if `name` is treated as a singleton header on insert.
    #[inline]
    pub(crate) fn is_single_value(name: &str) -> bool {
        is_single_value_header(name)
    }

    /// Replace all existing entries for `key` (case-insensitive) with a single `(key, value)` entry
    /// while preserving `key`'s exact casing.
    pub fn set(&mut self, key: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) {
        let key = key.into();
        let value = value.into();

        let mut replaced = false;
        let mut idx = 0;
        while idx < self.entries.len() {
            if self.entries[idx].0.eq_ignore_ascii_case(&key) {
                if !replaced {
                    self.entries[idx] = (key.clone(), value.clone());
                    replaced = true;
                    idx += 1;
                } else {
                    self.entries.remove(idx);
                }
            } else {
                idx += 1;
            }
        }

        if !replaced {
            self.entries.push((key, value));
        }
    }

    /// Get the first header value matching `key` (case-insensitive).
    pub fn get(&self, key: &str) -> Option<&str> {
        self.entries
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(key))
            .map(|(_, v)| v.as_ref())
    }

    /// Iterate over all header values matching `key` (case-insensitive) in insertion order.
    pub fn get_all<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'a str> {
        self.entries
            .iter()
            .filter(move |(k, _)| k.eq_ignore_ascii_case(key))
            .map(|(_, v)| v.as_ref())
    }

    /// Check if a header exists (case-insensitive).
    pub fn contains_key(&self, key: &str) -> bool {
        self.entries
            .iter()
            .any(|(k, _)| k.eq_ignore_ascii_case(key))
    }

    /// Remove all entries matching `key` (case-insensitive) and return the first removed value.
    pub fn remove(&mut self, key: &str) -> Option<String> {
        let mut removed: Option<String> = None;
        let mut idx = 0;
        while idx < self.entries.len() {
            if self.entries[idx].0.eq_ignore_ascii_case(key) {
                let (_, val) = self.entries.remove(idx);
                if removed.is_none() {
                    removed = Some(val.into_owned());
                }
            } else {
                idx += 1;
            }
        }
        removed
    }

    /// Return the number of header entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns `true` if the map contains no headers.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Return all stored `(original_key, value)` header entries in insertion order.
    #[inline]
    pub fn all(&self) -> &[(Cow<'static, str>, Cow<'static, str>)] {
        &self.entries
    }

    /// Iterator over `(&original_key, &value)`.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.entries.iter().map(|(k, v)| (k.as_ref(), v.as_ref()))
    }
}

impl<'a> IntoIterator for &'a Headers {
    type Item = (&'a str, &'a str);
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        let items: Vec<Self::Item> = self
            .entries
            .iter()
            .map(|(k, v)| (k.as_ref(), v.as_ref()))
            .collect();
        items.into_iter()
    }
}

impl IntoIterator for Headers {
    type Item = (Cow<'static, str>, Cow<'static, str>);
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.into_iter()
    }
}

impl<K: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>> FromIterator<(K, V)> for Headers {
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        let mut map = Headers::new();
        for (k, v) in iter {
            map.insert(k, v);
        }
        map
    }
}

#[inline]
fn is_single_value_header(name: &str) -> bool {
    match name.len() {
        3 => name.eq_ignore_ascii_case("age"),
        4 => {
            name.eq_ignore_ascii_case("host")
                || name.eq_ignore_ascii_case("date")
                || name.eq_ignore_ascii_case("etag")
                || name.eq_ignore_ascii_case("from")
        }
        5 => name.eq_ignore_ascii_case("range"),
        6 => name.eq_ignore_ascii_case("origin") || name.eq_ignore_ascii_case("server"),
        7 => name.eq_ignore_ascii_case("expires") || name.eq_ignore_ascii_case("referer"),
        8 => name.eq_ignore_ascii_case("if-range") || name.eq_ignore_ascii_case("location"),
        10 => name.eq_ignore_ascii_case("user-agent"),
        11 => name.eq_ignore_ascii_case("retry-after"),
        12 => {
            name.eq_ignore_ascii_case("content-type") || name.eq_ignore_ascii_case("max-forwards")
        }
        13 => {
            name.eq_ignore_ascii_case("authorization")
                || name.eq_ignore_ascii_case("content-range")
                || name.eq_ignore_ascii_case("last-modified")
        }
        14 => name.eq_ignore_ascii_case("content-length"),
        17 => name.eq_ignore_ascii_case("if-modified-since"),
        19 => {
            name.eq_ignore_ascii_case("if-unmodified-since")
                || name.eq_ignore_ascii_case("proxy-authorization")
                || name.eq_ignore_ascii_case("content-disposition")
        }
        _ => false,
    }
}