aboutsummaryrefslogtreecommitdiffstats
path: root/src/media.rs
blob: c6b1c220df26f47209858bb8eed3abeda68f52f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//! 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<String> {
    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"));
    }
}