http-query 0.2.0

A client and server SDK for the HTTP QUERY method (RFC 10008).
Documentation
//! RFC 9651 Structured Fields handling for the `Accept-Query` header field.
//!
//! RFC 10008 ยง3 defines `Accept-Query` as a Structured Fields List of media
//! ranges represented as Tokens or Strings, each optionally carrying
//! parameters. Only the bare media-range values are surfaced here (parameters
//! are recognized and stripped), which is what QUERY content negotiation needs.

/// Parses one or more `Accept-Query` header field values into the list of
/// advertised media ranges (unquoted, without parameters).
pub fn parse_accept_query<I, S>(values: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut items = Vec::new();
    for value in values {
        for member in split_sf_list(value.as_ref()) {
            if let Some(media_range) = sf_member_value(&member) {
                items.push(media_range);
            }
        }
    }
    items
}

/// Serializes media ranges into a valid Structured Fields List for the
/// `Accept-Query` header field, quoting values that are not valid Tokens.
pub fn format_accept_query<I, S>(media_types: I) -> String
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let parts: Vec<String> = media_types
        .into_iter()
        .filter_map(|media_type| {
            let trimmed = media_type.as_ref().trim();
            if trimmed.is_empty() {
                None
            } else if is_sf_token(trimmed) {
                Some(trimmed.to_string())
            } else {
                Some(encode_sf_string(trimmed))
            }
        })
        .collect();
    parts.join(", ")
}

/// Reports whether `media_type` is covered by the advertised `media_range`,
/// honoring the `*/*` and `type/*` wildcards. Comparison is case-insensitive.
pub fn matches_media_range(media_range: &str, media_type: &str) -> bool {
    let range = media_range.trim().to_ascii_lowercase();
    let media_type = media_type.trim().to_ascii_lowercase();

    if range.is_empty() {
        return false;
    }
    if range == "*/*" {
        return true;
    }
    if let Some(prefix) = range.strip_suffix('*') {
        if prefix.ends_with('/') {
            return media_type.starts_with(prefix);
        }
    }
    range == media_type
}

fn split_sf_list(value: &str) -> Vec<String> {
    let mut members = Vec::new();
    let mut buf = String::new();
    let mut in_string = false;
    let mut escaped = false;

    for c in value.chars() {
        if in_string {
            buf.push(c);
            if escaped {
                escaped = false;
            } else if c == '\\' {
                escaped = true;
            } else if c == '"' {
                in_string = false;
            }
            continue;
        }
        match c {
            '"' => {
                in_string = true;
                buf.push(c);
            }
            ',' => members.push(std::mem::take(&mut buf)),
            _ => buf.push(c),
        }
    }
    members.push(buf);
    members
}

fn sf_member_value(member: &str) -> Option<String> {
    let member = member.trim();
    if member.is_empty() {
        return None;
    }

    // Strip parameters (everything from the first top-level ';').
    let member = match index_top_level(member, b';') {
        Some(i) => member[..i].trim(),
        None => member,
    };
    if member.is_empty() {
        return None;
    }

    if member.len() >= 2 && member.starts_with('"') && member.ends_with('"') {
        Some(decode_sf_string(member))
    } else {
        Some(member.to_string())
    }
}

fn index_top_level(value: &str, sep: u8) -> Option<usize> {
    let bytes = value.as_bytes();
    let mut in_string = false;
    let mut escaped = false;

    for (i, &c) in bytes.iter().enumerate() {
        if in_string {
            if escaped {
                escaped = false;
            } else if c == b'\\' {
                escaped = true;
            } else if c == b'"' {
                in_string = false;
            }
        } else if c == b'"' {
            in_string = true;
        } else if c == sep {
            return Some(i);
        }
    }
    None
}

fn decode_sf_string(quoted: &str) -> String {
    let inner = &quoted[1..quoted.len() - 1];
    let mut out = String::with_capacity(inner.len());
    let mut escaped = false;
    for c in inner.chars() {
        if escaped {
            out.push(c);
            escaped = false;
        } else if c == '\\' {
            escaped = true;
        } else {
            out.push(c);
        }
    }
    out
}

fn encode_sf_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        if c == '\\' || c == '"' {
            out.push('\\');
        }
        out.push(c);
    }
    out.push('"');
    out
}

fn is_sf_token(s: &str) -> bool {
    let bytes = s.as_bytes();
    let Some(&first) = bytes.first() else {
        return false;
    };
    if !first.is_ascii_alphabetic() && first != b'*' {
        return false;
    }
    bytes[1..]
        .iter()
        .all(|&c| is_tchar(c) || c == b':' || c == b'/')
}

fn is_tchar(c: u8) -> bool {
    c.is_ascii_alphanumeric()
        || matches!(
            c,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'*'
                | b'+'
                | b'-'
                | b'.'
                | b'^'
                | b'_'
                | b'`'
                | b'|'
                | b'~'
        )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_structured_fields() {
        let got =
            parse_accept_query([r#""application/jsonpath", application/sql;charset="UTF-8""#]);
        assert_eq!(got, vec!["application/jsonpath", "application/sql"]);
    }

    #[test]
    fn comma_inside_quotes_is_not_a_separator() {
        let got = parse_accept_query([r#"application/foo;p="a,b", text/plain"#]);
        assert_eq!(got, vec!["application/foo", "text/plain"]);
    }

    #[test]
    fn formats_and_quotes_non_tokens() {
        assert_eq!(
            format_accept_query(["application/json", "application/sql"]),
            "application/json, application/sql"
        );
        assert_eq!(format_accept_query(["3d/model"]), r#""3d/model""#);
        assert_eq!(format_accept_query(["*/*", "image/*"]), "*/*, image/*");
    }

    #[test]
    fn round_trips() {
        let input = ["application/json", "3d/model", "application/sql"];
        let formatted = format_accept_query(input);
        assert_eq!(parse_accept_query([formatted]), input);
    }

    #[test]
    fn matches_wildcards_case_insensitively() {
        assert!(matches_media_range("application/json", "APPLICATION/JSON"));
        assert!(matches_media_range("*/*", "anything/here"));
        assert!(matches_media_range("image/*", "image/png"));
        assert!(!matches_media_range("image/*", "text/plain"));
        assert!(!matches_media_range("application/json", "application/xml"));
    }
}