//! Types, as media types (docs/design.md, 5.1): compared in a normal form, and keyed //! (holding records) where their top level is an object, which to start with means //! JSON. use anyhow::{Result, bail}; /// `media_type` in its normal form: type and subtype and parameter names in lower /// case, parameters sorted by name, `; ` between them. Parameter values stay as they /// are, but for the quotes around a quoted one that needs none. pub fn normalize(media_type: &str) -> Result { let mut parts = media_type.split(';'); let essence = parts.next().unwrap_or_default().trim().to_ascii_lowercase(); let Some((kind, subtype)) = essence.split_once('/') else { bail!("type {media_type:?} is not a media type (TYPE/SUBTYPE)"); }; if !is_token(kind) || !is_token(subtype) { bail!("type {media_type:?} is not a media type (TYPE/SUBTYPE)"); } let mut parameters = Vec::new(); for parameter in parts { let Some((name, value)) = parameter.split_once('=') else { bail!("type {media_type:?}: parameter {parameter:?} is not NAME=VALUE"); }; let name = name.trim().to_ascii_lowercase(); let mut value = value.trim().to_owned(); if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') { let inner = &value[1..value.len() - 1]; if is_token(inner) { value = inner.to_owned(); } } if !is_token(&name) || value.is_empty() { bail!("type {media_type:?}: parameter {parameter:?} is not NAME=VALUE"); } if parameters.iter().any(|(other, _)| *other == name) { bail!("type {media_type:?}: parameter {name} is given twice"); } parameters.push((name, value)); } parameters.sort(); let mut normal = essence; for (name, value) in parameters { normal.push_str(&format!("; {name}={value}")); } Ok(normal) } /// Whether entries of `media_type` (normalized) are keyed: JSON objects, whose keys are /// records. pub fn keyed(media_type: &str) -> bool { let essence = media_type.split(';').next().unwrap_or_default(); let subtype = essence .split_once('/') .map(|(_, subtype)| subtype) .unwrap_or_default(); subtype == "json" || subtype.ends_with("+json") } fn is_token(text: &str) -> bool { !text.is_empty() && text .bytes() .all(|byte| byte.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&byte)) } #[cfg(test)] mod tests { use super::*; #[test] fn normal_forms() { assert_eq!( normalize("Application/X-OpenSSH-Private-Key;Algorithm=\"ed25519\"").unwrap(), "application/x-openssh-private-key; algorithm=ed25519" ); assert_eq!( normalize("text/plain; b=2; a=1").unwrap(), "text/plain; a=1; b=2" ); assert!(normalize("text").is_err()); assert!(normalize("text/plain; a").is_err()); assert!(normalize("text/plain; a=1; A=2").is_err()); } #[test] fn keyed_types() { assert!(keyed("application/x-enstate-hosts+json")); assert!(keyed("application/json")); assert!(!keyed("application/octet-stream")); assert!(!keyed("application/x-pem-file; x=json")); } }