base_web_content/content_format.rs
1// Released under the MIT License.
2// Copyright, 2026, by Samuel Williams.
3
4use base_web_media_type::MediaType;
5
6/// A format of request content this crate parses, chosen by the request's media type.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum ContentFormat {
10 /// `multipart/form-data`, as RFC 7578 defines it.
11 MultipartFormData,
12 /// `application/x-www-form-urlencoded`, as the WHATWG URL Standard defines it.
13 UrlEncoded,
14}
15
16impl ContentFormat {
17 /// The format of content with this media type, by its essence, or `None` for a type this crate does not parse.
18 ///
19 /// ```
20 /// use base_web_content::ContentFormat;
21 /// use base_web_media_type::MediaType;
22 ///
23 /// let media_type = MediaType::parse("multipart/form-data; boundary=x")?;
24 /// assert_eq!(ContentFormat::from_media_type(&media_type), Some(ContentFormat::MultipartFormData));
25 /// assert_eq!(ContentFormat::from_media_type(&MediaType::APPLICATION_JSON), None);
26 /// # Ok::<(), base_web_media_type::MediaTypeError>(())
27 /// ```
28 pub fn from_media_type(media_type: &MediaType) -> Option<Self> {
29 [Self::MultipartFormData, Self::UrlEncoded]
30 .into_iter()
31 .find(|format| format.media_type().essence() == media_type.essence())
32 }
33
34 /// The format's media type, without parameters.
35 pub fn media_type(self) -> MediaType {
36 match self {
37 Self::MultipartFormData => MediaType::MULTIPART_FORM_DATA,
38 Self::UrlEncoded => MediaType::APPLICATION_X_WWW_FORM_URLENCODED,
39 }
40 }
41}