rama-http-headers 0.3.0

typed http headers for rama
Documentation
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::{fmt, str::FromStr};

use rama_core::telemetry::tracing;
use rama_http_types::{
    HeaderName, HeaderValue,
    mime::{self, Mime},
};

use crate::{Error, HeaderDecode, HeaderEncode, TypedHeader};

/// `Content-Type` header, defined in
/// [RFC7231](https://datatracker.ietf.org/doc/html/rfc7231#section-3.1.1.5)
///
/// The `Content-Type` header field indicates the media type of the
/// associated representation: either the representation enclosed in the
/// message payload or the selected representation, as determined by the
/// message semantics.  The indicated media type defines both the data
/// format and how that data is intended to be processed by a recipient,
/// within the scope of the received message semantics, after any content
/// codings indicated by Content-Encoding are decoded.
///
/// Although the `mime` crate allows the mime options to be any slice, this crate
/// forces the use of Vec. This is to make sure the same header can't have more than 1 type. If
/// this is an issue, it's possible to implement `Header` on a custom struct.
///
/// # ABNF
///
/// ```text
/// Content-Type = media-type
/// ```
///
/// # Example values
///
/// * `text/html; charset=utf-8`
/// * `application/json`
///
/// # Examples
///
/// ```
/// use rama_http_headers::ContentType;
///
/// let ct = ContentType::json();
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct ContentType(Mime);

impl ContentType {
    /// Create a new [`ContentType`] from any [`Mime`].
    #[inline]
    #[must_use]
    pub fn new(mime: Mime) -> Self {
        Self(mime)
    }

    /// A constructor to easily create a `Content-Type: application/json` header.
    #[inline]
    #[must_use]
    pub fn json() -> Self {
        Self(mime::APPLICATION_JSON)
    }

    #[inline]
    #[must_use]
    pub fn ndjson() -> Self {
        #[expect(
            clippy::expect_used,
            reason = "static value which is expected to work, and validated with a unit-test"
        )]
        Self(
            Mime::from_str("application/x-ndjson")
                .expect("application/x-ndjson to be a valid mime"),
        )
    }

    /// A constructor to easily create a `Content-Type: text/plain` header.
    #[inline]
    #[must_use]
    pub fn text() -> Self {
        Self(mime::TEXT_PLAIN)
    }

    /// A constructor to easily create a `Content-Type: text/plain; charset=utf-8` header.
    #[inline]
    #[must_use]
    pub fn text_utf8() -> Self {
        Self(mime::TEXT_PLAIN_UTF_8)
    }

    /// A constructor to easily create a `Content-Type: text/event-stream` header.
    #[inline]
    #[must_use]
    pub fn text_event_stream() -> Self {
        Self(mime::TEXT_EVENT_STREAM)
    }

    /// A constructor to easily create a `Content-Type: text/html` header.
    #[inline]
    #[must_use]
    pub fn html() -> Self {
        Self(mime::TEXT_HTML)
    }

    /// A constructor to easily create a `Content-Type: text/html; charset=utf-8` header.
    #[inline]
    #[must_use]
    pub fn html_utf8() -> Self {
        Self(mime::TEXT_HTML_UTF_8)
    }

    /// A constructor to easily create a `Content-Type: text/css` header.
    #[inline]
    #[must_use]
    pub fn css() -> Self {
        Self(mime::TEXT_CSS)
    }

    /// A constructor to easily create a `text/css; charset=utf-8` header.
    #[inline]
    #[must_use]
    pub fn css_utf8() -> Self {
        Self(mime::TEXT_CSS_UTF_8)
    }

    /// A constructor to easily create a `Content-Type: text/xml` header.
    #[inline]
    #[must_use]
    pub fn xml() -> Self {
        Self(mime::TEXT_XML)
    }

    /// A constructor to easily create a `Content-Type: text/csv` header.
    #[inline]
    #[must_use]
    pub fn csv() -> Self {
        Self(mime::TEXT_CSV)
    }

    /// A constructor to easily create a `Content-Type: text/csv; charset=utf-8` header.
    #[inline]
    #[must_use]
    pub fn csv_utf8() -> Self {
        Self(mime::TEXT_CSV_UTF_8)
    }

    /// A constructor to easily create a `Content-Type: application/x-www-form-url-encoded` header.
    #[inline]
    #[must_use]
    pub fn form_url_encoded() -> Self {
        Self(mime::APPLICATION_WWW_FORM_URLENCODED)
    }
    /// A constructor to easily create a `Content-Type: image/jpeg` header.
    #[inline]
    #[must_use]
    pub fn jpeg() -> Self {
        Self(mime::IMAGE_JPEG)
    }

    /// A constructor to easily create a `Content-Type: image/png` header.
    #[inline]
    #[must_use]
    pub fn png() -> Self {
        Self(mime::IMAGE_PNG)
    }

    /// A constructor to easily create a `Content-Type: application/octet-stream` header.
    #[inline]
    #[must_use]
    pub fn octet_stream() -> Self {
        Self(mime::APPLICATION_OCTET_STREAM)
    }

    /// A constructor to easily create a `Content-Type: application/javascript` header.
    #[inline]
    #[must_use]
    pub fn javascript() -> Self {
        Self(mime::APPLICATION_JAVASCRIPT)
    }

    /// A constructor to easily create a `Content-Type: application/grpc` header.
    #[inline]
    #[must_use]
    pub fn grpc() -> Self {
        // TOOD: we need to invest in mime, either contribute,
        // or fork it, to support all our mime needs better...
        // e.g. we also have similar issues for ndjson and more
        #[expect(
            clippy::expect_used,
            reason = "valid mim,e in future this should be better"
        )]
        Self(Mime::from_str("application/grpc").expect("application/grpc to be a valid mime"))
    }

    /// A constructor to easily create a `Content-Type: application/javascript; charset=utf-8` header.
    #[inline]
    #[must_use]
    pub fn javascript_utf8() -> Self {
        Self(mime::APPLICATION_JAVASCRIPT_UTF_8)
    }

    /// A constructor to easily create a `Content-Type: application/rss+xml` header.
    #[inline]
    #[must_use]
    pub fn rss() -> Self {
        #[expect(
            clippy::expect_used,
            reason = "static value which is expected to work, and validated with a unit-test"
        )]
        Self(Mime::from_str("application/rss+xml").expect("application/rss+xml to be a valid mime"))
    }

    /// A constructor to easily create a `Content-Type: application/atom+xml` header.
    #[inline]
    #[must_use]
    pub fn atom() -> Self {
        #[expect(
            clippy::expect_used,
            reason = "static value which is expected to work, and validated with a unit-test"
        )]
        Self(
            Mime::from_str("application/atom+xml")
                .expect("application/atom+xml to be a valid mime"),
        )
    }

    /// A constructor to easily create a `Content-Type: application/jose+json` header.
    #[inline]
    #[must_use]
    pub fn jose_json() -> Self {
        #[expect(
            clippy::expect_used,
            reason = "static value which is expected to work, and validated with a unit-test"
        )]
        Self(
            Mime::from_str("application/jose+json")
                .expect("application/jose+json to be a valid mime"),
        )
    }

    /// A constructor to easily create a `Content-Type: application/manifest+json` header,
    /// as defined by the [W3C Web App Manifest spec](https://www.w3.org/TR/appmanifest/#media-type-registration).
    #[inline]
    #[must_use]
    pub fn manifest_json() -> Self {
        #[expect(
            clippy::expect_used,
            reason = "static value which is expected to work, and validated with a unit-test"
        )]
        Self(
            Mime::from_str("application/manifest+json")
                .expect("application/manifest+json to be a valid mime"),
        )
    }

    /// A constructor to easily create a `Content-Type: image/svg+xml` header.
    ///
    /// ```
    /// use rama_http_headers::ContentType;
    ///
    /// assert_eq!(ContentType::svg().to_string(), "image/svg+xml");
    /// ```
    #[inline]
    #[must_use]
    pub fn svg() -> Self {
        Self(mime::IMAGE_SVG)
    }

    /// A constructor to easily create a `Content-Type: application/xml; charset=utf-8` header.
    ///
    /// Distinct from [`Self::xml`] (which is `text/xml`): per
    /// [RFC 7303](https://datatracker.ietf.org/doc/html/rfc7303) `application/xml`
    /// is preferred for sitemaps/RSS/Atom, and the charset is stated explicitly
    /// so the document's XML prolog and the HTTP `Content-Type` agree.
    ///
    /// ```
    /// use rama_http_headers::ContentType;
    ///
    /// assert_eq!(
    ///     ContentType::xml_utf8().to_string(),
    ///     "application/xml; charset=utf-8",
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub fn xml_utf8() -> Self {
        #[expect(
            clippy::expect_used,
            reason = "static value which is expected to work, and validated with a unit-test"
        )]
        Self(
            Mime::from_str("application/xml; charset=utf-8")
                .expect("application/xml; charset=utf-8 to be a valid mime"),
        )
    }

    /// A constructor to easily create a `Content-Type: application/wasm` header.
    ///
    /// The spec mandates this exact value for `WebAssembly.instantiateStreaming`
    /// to accept the response.
    ///
    /// ```
    /// use rama_http_headers::ContentType;
    ///
    /// assert_eq!(ContentType::wasm().to_string(), "application/wasm");
    /// ```
    #[inline]
    #[must_use]
    pub fn wasm() -> Self {
        #[expect(
            clippy::expect_used,
            reason = "static value which is expected to work, and validated with a unit-test"
        )]
        Self(Mime::from_str("application/wasm").expect("application/wasm to be a valid mime"))
    }

    /// A constructor to easily create a `Content-Type: font/woff2` header.
    ///
    /// ```
    /// use rama_http_headers::ContentType;
    ///
    /// assert_eq!(ContentType::woff2().to_string(), "font/woff2");
    /// ```
    #[inline]
    #[must_use]
    pub fn woff2() -> Self {
        Self(mime::FONT_WOFF2)
    }

    /// A constructor to easily create a `Content-Type: application/manifest+json` header.
    ///
    /// Alias of [`Self::manifest_json`], named after the `.webmanifest` file
    /// extension that web app manifests actually use; both coexist.
    ///
    /// ```
    /// use rama_http_headers::ContentType;
    ///
    /// assert_eq!(
    ///     ContentType::webmanifest().to_string(),
    ///     "application/manifest+json",
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub fn webmanifest() -> Self {
        Self::manifest_json()
    }

    /// Reference to the internal [`Mime`].
    #[must_use]
    pub fn mime(&self) -> &Mime {
        &self.0
    }

    /// Consume `self` into the inner [`Mime`].
    #[must_use]
    pub fn into_mime(self) -> Mime {
        self.0
    }
}

impl TypedHeader for ContentType {
    fn name() -> &'static HeaderName {
        &::rama_http_types::header::CONTENT_TYPE
    }
}

impl HeaderDecode for ContentType {
    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
        values
            .next()
            .and_then(|v| v.to_str().ok()?.parse().ok())
            .map(ContentType)
            .ok_or_else(Error::invalid)
    }
}

impl HeaderEncode for ContentType {
    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        match self.0.as_ref().parse() {
            Ok(value) => values.extend(::std::iter::once(value)),
            Err(err) => {
                tracing::debug!("failed to encode content-type's mime as header value: {err}");
            }
        }
    }
}

impl From<mime::Mime> for ContentType {
    fn from(m: mime::Mime) -> Self {
        Self(m)
    }
}

impl From<ContentType> for mime::Mime {
    fn from(ct: ContentType) -> Self {
        ct.0
    }
}

impl fmt::Display for ContentType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl std::str::FromStr for ContentType {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse::<Mime>()
            .map(|m| m.into())
            .map_err(|_e| Error::invalid())
    }
}

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

    #[test]
    fn jose_json_is_valid() {
        _ = ContentType::jose_json();
    }

    #[test]
    fn ndjson_is_valid() {
        _ = ContentType::ndjson();
    }

    #[test]
    fn manifest_json_is_valid() {
        _ = ContentType::manifest_json();
    }

    #[test]
    fn manifest_json_roundtrip() {
        assert_eq!(
            test_decode::<ContentType>(&["application/manifest+json"]),
            Some(ContentType::manifest_json()),
        );
    }

    #[test]
    fn xml_utf8_is_valid() {
        _ = ContentType::xml_utf8();
    }

    #[test]
    fn xml_utf8_roundtrip() {
        assert_eq!(
            test_decode::<ContentType>(&["application/xml; charset=utf-8"]),
            Some(ContentType::xml_utf8()),
        );
    }

    #[test]
    fn wasm_is_valid() {
        _ = ContentType::wasm();
    }

    #[test]
    fn webmanifest_matches_manifest_json() {
        assert_eq!(ContentType::webmanifest(), ContentType::manifest_json());
    }

    #[test]
    fn rss_is_valid() {
        _ = ContentType::rss();
    }

    #[test]
    fn atom_is_valid() {
        _ = ContentType::atom();
    }

    #[test]
    fn json() {
        assert_eq!(
            test_decode::<ContentType>(&["application/json"]),
            Some(ContentType::json()),
        );
    }

    #[test]
    fn from_str() {
        assert_eq!(
            "application/json".parse::<ContentType>().unwrap(),
            ContentType::json(),
        );
        "invalid-mimetype".parse::<ContentType>().unwrap_err();
    }

    bench_header!(bench_plain, ContentType, "text/plain");
    bench_header!(bench_json, ContentType, "application/json");
    bench_header!(
        bench_formdata,
        ContentType,
        "multipart/form-data; boundary=---------------abcd"
    );
}