hyperlane-plugin-negotiate 22.14.0

A response negotiation plugin for the Hyperlane framework, answering with the content coding the client accepts and with 304 Not Modified while a validator still matches.
Documentation
use super::*;

/// Checks whether a status carries no body a content coding could apply to.
///
/// # Arguments
///
/// - `ResponseStatusCode` - The status code of the response.
///
/// # Returns
///
/// - `bool` - Whether the status is bodyless.
#[inline]
pub(crate) fn has_no_body(status_code: ResponseStatusCode) -> bool {
    matches!(status_code, 100..=199)
        || status_code == HttpStatus::NoContent.code()
        || status_code == HttpStatus::ResetContent.code()
        || status_code == HttpStatus::NotModified.code()
}

/// Inspects all response headers in a single pass to decide compression eligibility and `Vary` action.
///
/// # Arguments
///
/// - `&Response` - The outgoing response to inspect.
///
/// # Returns
///
/// - `u8` - One of `COMPRESS_STATE_SKIP`, `COMPRESS_STATE_SET_VARY`, `COMPRESS_STATE_ADD_VARY`, or `COMPRESS_STATE_VARY_OK`.
#[inline]
pub(crate) fn inspect_response_for_compress(response: &Response) -> u8 {
    let headers: &ResponseHeaders = response.get_headers();
    if headers.is_empty() {
        return COMPRESS_STATE_SET_VARY;
    }
    let mut has_vary: bool = false;
    let mut vary_declared: bool = false;
    for (key, values) in headers {
        let len: usize = key.len();
        if len == CONTENT_ENCODING.len() && key.eq_ignore_ascii_case(CONTENT_ENCODING) {
            return COMPRESS_STATE_SKIP;
        }
        if len == CACHE_CONTROL.len() && key.eq_ignore_ascii_case(CACHE_CONTROL) {
            if values.iter().any(|value: &String| {
                value.split(COMMA).any(|directive: &str| {
                    directive
                        .trim()
                        .eq_ignore_ascii_case(CACHE_CONTROL_NO_TRANSFORM)
                })
            }) {
                return COMPRESS_STATE_SKIP;
            }
            continue;
        }
        if len == CONTENT_TYPE.len() && key.eq_ignore_ascii_case(CONTENT_TYPE) {
            if values.iter().any(|value: &String| {
                value
                    .split(MEDIA_TYPE_PARAM_DELIMITER)
                    .next()
                    .is_some_and(|media: &str| media.trim().eq_ignore_ascii_case(TEXT_EVENT_STREAM))
            }) {
                return COMPRESS_STATE_SKIP;
            }
            continue;
        }
        if len == VARY.len() && key.eq_ignore_ascii_case(VARY) {
            has_vary = true;
            if !vary_declared
                && values.iter().any(|value: &String| {
                    value.split(COMMA).any(|token: &str| {
                        let trimmed: &str = token.trim();
                        trimmed.eq_ignore_ascii_case(VARY_ACCEPT_ENCODING)
                            || trimmed == VARY_WILDCARD
                    })
                })
            {
                vary_declared = true;
            }
        }
    }
    if vary_declared {
        COMPRESS_STATE_VARY_OK
    } else if has_vary {
        COMPRESS_STATE_ADD_VARY
    } else {
        COMPRESS_STATE_SET_VARY
    }
}

/// Fast-path `Accept-Encoding` parser that avoids quality-value float parsing when no `;` is present.
///
/// # Arguments
///
/// - `&str` - Raw `Accept-Encoding` header value.
///
/// # Returns
///
/// - `Option<Compress>` - Best supported content coding, or `None`.
#[inline]
pub(crate) fn parse_accept_encoding_fast(value: &str) -> Option<Compress> {
    if value.as_bytes().contains(&b';') {
        return Compress::from_accept_encoding(value);
    }
    let mut best: Option<Compress> = None;
    for token in value.split(COMMA) {
        let trimmed: &str = token.trim();
        if trimmed.eq_ignore_ascii_case(CODING_BR) || trimmed == VARY_WILDCARD {
            return Some(Compress::Br);
        }
        if trimmed.eq_ignore_ascii_case(CODING_GZIP) || trimmed.eq_ignore_ascii_case(CODING_X_GZIP)
        {
            best = Some(Compress::Gzip);
        } else if best.is_none() && trimmed.eq_ignore_ascii_case(CODING_DEFLATE) {
            best = Some(Compress::Deflate);
        }
    }
    best
}

/// Parses a list of `Accept-Encoding` values without heap allocation when combined length fits on the stack.
///
/// # Arguments
///
/// - `&RequestHeadersValue` - Values stored under the `accept-encoding` key.
///
/// # Returns
///
/// - `Option<Compress>` - Best supported content coding, or `None`.
#[inline]
pub(crate) fn parse_accept_encoding_values(values: &RequestHeadersValue) -> Option<Compress> {
    if values.len() == 1 {
        return values
            .front()
            .and_then(|val: &String| parse_accept_encoding_fast(val));
    }
    if values.is_empty() {
        return None;
    }
    let mut stack_buf: [u8; STACK_ACCEPT_ENCODING_CAP] = [0u8; STACK_ACCEPT_ENCODING_CAP];
    let mut pos: usize = 0;
    let mut fits: bool = true;
    for (idx, value) in values.iter().enumerate() {
        let need: usize = value.len() + usize::from(idx > 0);
        if pos + need > STACK_ACCEPT_ENCODING_CAP {
            fits = false;
            break;
        }
        if idx > 0 {
            stack_buf[pos] = b',';
            pos += 1;
        }
        stack_buf[pos..pos + value.len()].copy_from_slice(value.as_bytes());
        pos += value.len();
    }
    if fits {
        return from_utf8(&stack_buf[..pos])
            .ok()
            .and_then(parse_accept_encoding_fast);
    }
    let total_len: usize = values
        .iter()
        .map(|val: &String| val.len())
        .sum::<usize>()
        .saturating_add(values.len());
    let mut joined: String = String::with_capacity(total_len);
    for (idx, value) in values.iter().enumerate() {
        if idx > 0 {
            joined.push_str(COMMA);
        }
        joined.push_str(value);
    }
    parse_accept_encoding_fast(&joined)
}