sparesults/
format.rs

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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use std::fmt;

/// [SPARQL query](https://www.w3.org/TR/sparql11-query/) results serialization formats.
#[derive(Eq, PartialEq, Debug, Clone, Copy, Hash)]
#[non_exhaustive]
pub enum QueryResultsFormat {
    /// [SPARQL Query Results XML Format](https://www.w3.org/TR/rdf-sparql-XMLres/)
    Xml,
    /// [SPARQL Query Results JSON Format](https://www.w3.org/TR/sparql11-results-json/)
    Json,
    /// [SPARQL Query Results CSV Format](https://www.w3.org/TR/sparql11-results-csv-tsv/)
    Csv,
    /// [SPARQL Query Results TSV Format](https://www.w3.org/TR/sparql11-results-csv-tsv/)
    Tsv,
}

impl QueryResultsFormat {
    /// The format canonical IRI according to the [Unique URIs for file formats registry](https://www.w3.org/ns/formats/).
    ///
    /// ```
    /// use sparesults::QueryResultsFormat;
    ///
    /// assert_eq!(
    ///     QueryResultsFormat::Json.iri(),
    ///     "http://www.w3.org/ns/formats/SPARQL_Results_JSON"
    /// )
    /// ```
    #[inline]
    pub fn iri(self) -> &'static str {
        match self {
            Self::Xml => "http://www.w3.org/ns/formats/SPARQL_Results_XML",
            Self::Json => "http://www.w3.org/ns/formats/SPARQL_Results_JSON",
            Self::Csv => "http://www.w3.org/ns/formats/SPARQL_Results_CSV",
            Self::Tsv => "http://www.w3.org/ns/formats/SPARQL_Results_TSV",
        }
    }

    /// The format [IANA media type](https://tools.ietf.org/html/rfc2046).
    ///
    /// ```
    /// use sparesults::QueryResultsFormat;
    ///
    /// assert_eq!(
    ///     QueryResultsFormat::Json.media_type(),
    ///     "application/sparql-results+json"
    /// )
    /// ```
    #[inline]
    pub fn media_type(self) -> &'static str {
        match self {
            Self::Xml => "application/sparql-results+xml",
            Self::Json => "application/sparql-results+json",
            Self::Csv => "text/csv; charset=utf-8",
            Self::Tsv => "text/tab-separated-values; charset=utf-8",
        }
    }

    /// The format [IANA-registered](https://tools.ietf.org/html/rfc2046) file extension.
    ///
    /// ```
    /// use sparesults::QueryResultsFormat;
    ///
    /// assert_eq!(QueryResultsFormat::Json.file_extension(), "srj")
    /// ```
    #[inline]
    pub fn file_extension(self) -> &'static str {
        match self {
            Self::Xml => "srx",
            Self::Json => "srj",
            Self::Csv => "csv",
            Self::Tsv => "tsv",
        }
    }

    /// The format name.
    ///
    /// ```
    /// use sparesults::QueryResultsFormat;
    ///
    /// assert_eq!(QueryResultsFormat::Json.name(), "SPARQL Results in JSON")
    /// ```
    #[inline]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Xml => "SPARQL Results in XML",
            Self::Json => "SPARQL Results in JSON",
            Self::Csv => "SPARQL Results in CSV",
            Self::Tsv => "SPARQL Results in TSV",
        }
    }

    /// Looks for a known format from a media type.
    ///
    /// It supports some media type aliases.
    /// For example, "application/xml" is going to return `Xml` even if it is not its canonical media type.
    ///
    /// Example:
    /// ```
    /// use sparesults::QueryResultsFormat;
    ///
    /// assert_eq!(
    ///     QueryResultsFormat::from_media_type("application/sparql-results+json; charset=utf-8"),
    ///     Some(QueryResultsFormat::Json)
    /// )
    /// ```
    #[inline]
    pub fn from_media_type(media_type: &str) -> Option<Self> {
        const MEDIA_SUBTYPES: [(&str, QueryResultsFormat); 8] = [
            ("csv", QueryResultsFormat::Csv),
            ("json", QueryResultsFormat::Json),
            ("plain", QueryResultsFormat::Csv),
            ("sparql-results+json", QueryResultsFormat::Json),
            ("sparql-results+xml", QueryResultsFormat::Xml),
            ("tab-separated-values", QueryResultsFormat::Tsv),
            ("tsv", QueryResultsFormat::Tsv),
            ("xml", QueryResultsFormat::Xml),
        ];

        let (r#type, subtype) = media_type
            .split_once(';')
            .unwrap_or((media_type, ""))
            .0
            .trim()
            .split_once('/')?;
        let r#type = r#type.trim();
        if !r#type.eq_ignore_ascii_case("application") && !r#type.eq_ignore_ascii_case("text") {
            return None;
        }
        let subtype = subtype.trim();
        let subtype = subtype.strip_prefix("x-").unwrap_or(subtype);
        for (candidate_subtype, candidate_id) in MEDIA_SUBTYPES {
            if candidate_subtype.eq_ignore_ascii_case(subtype) {
                return Some(candidate_id);
            }
        }
        None
    }

    /// Looks for a known format from an extension.
    ///
    /// It supports some aliases.
    ///
    /// Example:
    /// ```
    /// use sparesults::QueryResultsFormat;
    ///
    /// assert_eq!(
    ///     QueryResultsFormat::from_extension("json"),
    ///     Some(QueryResultsFormat::Json)
    /// )
    /// ```
    #[inline]
    pub fn from_extension(extension: &str) -> Option<Self> {
        const MEDIA_TYPES: [(&str, QueryResultsFormat); 7] = [
            ("csv", QueryResultsFormat::Csv),
            ("json", QueryResultsFormat::Json),
            ("srj", QueryResultsFormat::Json),
            ("srx", QueryResultsFormat::Xml),
            ("tsv", QueryResultsFormat::Tsv),
            ("txt", QueryResultsFormat::Csv),
            ("xml", QueryResultsFormat::Xml),
        ];
        for (candidate_extension, candidate_id) in MEDIA_TYPES {
            if candidate_extension.eq_ignore_ascii_case(extension) {
                return Some(candidate_id);
            }
        }
        None
    }
}

impl fmt::Display for QueryResultsFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}