http-type 23.0.0

A comprehensive Rust type library for HTTP operations and concurrent programming. Provides core HTTP types (Request/Response with builder patterns, Method, HttpStatus, HttpVersion, ContentType, FileExtension with MIME mapping, Cookie parsing/building, HttpUrl parsing, WebSocket frame/opcode, protocol upgrade types, stream/task management, panic handling), thread-safe concurrent wrappers (ArcMutex, ArcRwLock, BoxRwLock, RcRwLock), dynamic dispatch types (BoxAny, RcAny, ArcAny with Send/Sync variants), high-performance hash collections (HashMapXxHash3_64, HashSetXxHash3_64), and static lifetime utilities (BoxLeak, Lifetime trait).
Documentation
use super::*;

/// Resolves the transfer coding of an HTTP/1.1 request.
///
/// # Arguments
///
/// - `&VecDeque<String>` - The values in wire order.
/// # Returns
///
/// - `Result<RequestFraming, RequestError>` - Chunked framing or the reason it cannot be decoded.
#[cold]
pub(super) fn parse_transfer_encoding(
    values: &VecDeque<String>,
) -> Result<RequestFraming, RequestError> {
    let invalid: RequestError = RequestError::HttpRead(HttpStatus::BadRequest);
    let mut chunked: bool = false;
    let mut unsupported: bool = false;
    for value in values {
        for item in value.split(COMMA) {
            let coding: &str = item.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE);
            if coding.is_empty() {
                continue;
            }
            if chunked {
                return Err(invalid);
            }
            if coding.eq_ignore_ascii_case(CHUNKED) {
                chunked = true;
            } else if coding.bytes().all(|byte: u8| {
                byte.is_ascii_alphanumeric() || HTTP_HEADER_TOKEN_PUNCTUATION.contains(&byte)
            }) {
                unsupported = true;
            } else {
                return Err(invalid);
            }
        }
    }
    if !chunked {
        return Err(invalid);
    }
    if unsupported {
        return Err(RequestError::HttpRead(HttpStatus::NotImplemented));
    }
    Ok(RequestFraming::Chunked)
}

/// Reads one LF-terminated HTTP line with a strict upper bound to prevent unbounded memory growth.
///
/// # Arguments
///
/// - `&mut R` - The buffered reader to consume from.
/// - `&mut String` - The destination string buffer (cleared before reading).
/// - `usize` - The maximum line length in bytes (`usize::MAX` disables the cap).
/// - `RequestError` - The error returned when the line exceeds `max_len`.
///
/// # Returns
///
/// - `Result<usize, RequestError>` - The number of bytes read (`0` on clean EOF), or a limit/UTF-8/I/O error.
pub(crate) async fn read_http_line_bounded<R>(
    reader: &mut R,
    out: &mut String,
    max_len: usize,
    overflow_error: RequestError,
) -> Result<usize, RequestError>
where
    R: AsyncBufReadExt + Unpin,
{
    out.clear();
    let mut raw: Vec<u8> = Vec::new();
    loop {
        let available: &[u8] = reader.fill_buf().await?;
        if available.is_empty() {
            break;
        }
        let budget: usize = max_len.saturating_sub(raw.len());
        if budget == 0 {
            return Err(overflow_error);
        }
        let scan_len: usize = available.len().min(budget);
        let newline: Option<usize> = available[..scan_len]
            .iter()
            .position(|byte: &u8| *byte == BR_U8);
        let consumed: usize = newline.map_or(scan_len, |index: usize| index + 1);
        raw.extend_from_slice(&available[..consumed]);
        reader.consume(consumed);
        if newline.is_some() {
            break;
        }
        if raw.len() >= max_len && max_len != usize::MAX {
            return Err(overflow_error);
        }
    }
    let text: &str =
        from_utf8(&raw).map_err(|_| RequestError::ReadConnection(HttpStatus::BadRequest))?;
    out.push_str(text);
    Ok(raw.len())
}

/// Validates an HTTP/1.1 `Host` header value per RFC 9110 Section 7.2 (`uri-host [ ":" port ]`).
///
/// Rejects userinfo (`@`), whitespace, path/query delimiters, control characters, and
/// malformed IPv6 bracket literals or ports.
///
/// # Arguments
///
/// - `&str` - The trimmed `Host` header value.
///
/// # Returns
///
/// - `bool` - `true` when the `Host` value is syntactically valid.
#[inline(always)]
pub(crate) fn is_valid_http_host(value: &str) -> bool {
    if value.is_empty() {
        return true;
    }
    let bytes: &[u8] = value.as_bytes();
    let port_part: Option<&[u8]> = if bytes[0] == LEFT_SQUARE_BRACKET_U8 {
        let Some(close_idx) = bytes
            .iter()
            .position(|byte: &u8| *byte == RIGHT_SQUARE_BRACKET_U8)
        else {
            return false;
        };
        let literal: &[u8] = &bytes[1..close_idx];
        if literal.is_empty()
            || !literal
                .iter()
                .all(|byte: &u8| byte.is_ascii_hexdigit() || *byte == COLON_U8 || *byte == POINT_U8)
        {
            return false;
        }
        let rest: &[u8] = &bytes[close_idx + 1..];
        if rest.is_empty() {
            None
        } else if let Some(port) = rest.strip_prefix(COLON_BYTES) {
            Some(port)
        } else {
            return false;
        }
    } else {
        let mut colon_pos: Option<usize> = None;
        for (idx, &byte) in bytes.iter().enumerate() {
            if byte == COLON_U8 {
                if idx == 0 {
                    return false;
                }
                colon_pos = Some(idx);
                break;
            }
            if !HTTP_HOST_REG_NAME_TABLE[byte as usize] {
                return false;
            }
        }
        colon_pos.map(|idx: usize| &bytes[idx + 1..])
    };
    if let Some(port) = port_part {
        if port.is_empty() {
            return false;
        }
        let mut acc: u32 = 0;
        for &byte in port {
            if !byte.is_ascii_digit() {
                return false;
            }
            acc = acc * 10 + u32::from(byte - ZERO_STR_U8);
            if acc > u32::from(u16::MAX) {
                return false;
            }
        }
    }
    true
}

/// Finds the first index of `needle` inside `bytes` using 8-byte SWAR word scanning.
///
/// # Arguments
///
/// - `&[u8]` - The byte slice to search.
/// - `u8` - The target byte value.
///
/// # Returns
///
/// - `Option<usize>` - Byte offset of the first match, or `None`.
#[inline(always)]
pub(crate) fn find_byte_swar(bytes: &[u8], needle: u8) -> Option<usize> {
    let len: usize = bytes.len();
    let mut idx: usize = 0;
    let repeat: u64 = u64::from_ne_bytes([needle; 8]);
    while idx + 8 <= len {
        let chunk: [u8; 8] = [
            bytes[idx],
            bytes[idx + 1],
            bytes[idx + 2],
            bytes[idx + 3],
            bytes[idx + 4],
            bytes[idx + 5],
            bytes[idx + 6],
            bytes[idx + 7],
        ];
        let word: u64 = u64::from_le_bytes(chunk) ^ repeat;
        let mask: u64 = word.wrapping_sub(SWAR_LO_ONES) & !word & SWAR_HI_BITS;
        if mask != 0 {
            return Some(idx + ((mask.trailing_zeros() as usize) >> 3));
        }
        idx += 8;
    }
    while idx < len {
        if bytes[idx] == needle {
            return Some(idx);
        }
        idx += 1;
    }
    None
}

/// Validates an HTTP header field value slice and reports whether it is pure ASCII.
///
/// Uses an 8-byte SWAR printable-ASCII fast path (`0x20..=0x7E`) and falls back to
/// `HTTP_HEADER_VALUE_VALID_TABLE` for tabs or obs-text (`>= 0x80`).
///
/// # Arguments
///
/// - `&[u8]` - The raw field value bytes after the colon.
///
/// # Returns
///
/// - `Option<bool>` - `Some(true)` if valid pure ASCII, `Some(false)` if valid with non-ASCII bytes, or `None` if forbidden control bytes exist.
#[inline(always)]
pub(crate) fn validate_header_value_swar(bytes: &[u8]) -> Option<bool> {
    let len: usize = bytes.len();
    let mut idx: usize = 0;
    let mut non_ascii: u8 = 0;
    while idx + 8 <= len {
        let chunk: [u8; 8] = [
            bytes[idx],
            bytes[idx + 1],
            bytes[idx + 2],
            bytes[idx + 3],
            bytes[idx + 4],
            bytes[idx + 5],
            bytes[idx + 6],
            bytes[idx + 7],
        ];
        let word: u64 = u64::from_le_bytes(chunk);
        let invalid_or_non_printable: u64 =
            (word | word.wrapping_sub(SWAR_SPACES) | word.wrapping_add(SWAR_LO_ONES))
                & SWAR_HI_BITS;
        if invalid_or_non_printable != 0 {
            for &byte in &chunk {
                if !HTTP_HEADER_VALUE_VALID_TABLE[byte as usize] {
                    return None;
                }
                non_ascii |= byte & 0x80;
            }
        }
        idx += 8;
    }
    while idx < len {
        let byte: u8 = bytes[idx];
        if !HTTP_HEADER_VALUE_VALID_TABLE[byte as usize] {
            return None;
        }
        non_ascii |= byte & 0x80;
        idx += 1;
    }
    Some(non_ascii == 0)
}

/// Parses one entity-tag prefix without allocating or interpreting escapes.
///
/// # Arguments
///
/// - `&[u8]` - The input beginning with a strong or weak entity-tag.
///
/// # Returns
///
/// - `Option<(&[u8], &[u8])>` - The opaque value and unconsumed suffix, or `None` for invalid syntax.
pub(super) fn parse_entity_tag(input: &[u8]) -> Option<(&[u8], &[u8])> {
    let bytes: &[u8] = input.strip_prefix(ENTITY_TAG_WEAK_PREFIX).unwrap_or(input);
    let opaque: &[u8] = bytes.strip_prefix(&[ENTITY_TAG_QUOTE])?;
    for (index, &byte) in opaque.iter().enumerate() {
        if byte == ENTITY_TAG_QUOTE {
            return Some((&opaque[..index], &opaque[index + 1..]));
        }
        if byte <= HTTP_HEADER_CONTROL_LIMIT || byte == HTTP_HEADER_DELETE {
            return None;
        }
    }
    None
}