use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct MediaType(String);
impl MediaType {
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
#[must_use]
pub fn is_full(&self) -> bool {
match self.0.split_once('/') {
Some((top, sub)) => !top.is_empty() && !sub.is_empty() && sub != "*",
None => false,
}
}
#[must_use]
pub fn top_level(&self) -> String {
let top = self
.0
.split_once('/')
.map_or(self.0.as_str(), |(top, _)| top);
top.trim().to_ascii_lowercase()
}
#[must_use]
pub fn subtype(&self) -> Option<&str> {
let (_, sub) = self.0.split_once('/')?;
let sub = sub.split(';').next().unwrap_or(sub).trim();
(!sub.is_empty()).then_some(sub)
}
#[must_use]
pub fn normalize(&self) -> MediaType {
let without_params = self.0.split(';').next().unwrap_or(&self.0).trim();
let lower = without_params.to_ascii_lowercase();
match lower.split_once('/') {
Some((top, "*")) => MediaType(top.to_owned()),
Some((top, "")) => MediaType(top.to_owned()),
_ => MediaType(lower),
}
}
#[must_use]
pub fn matches(&self, pattern: &MediaType) -> bool {
let this = self.normalize();
let pattern = pattern.normalize();
if this == pattern {
return true;
}
if pattern.0.contains('/') {
return false;
}
this.top_level() == pattern.0
}
}
impl std::fmt::Display for MediaType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for MediaType {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for MediaType {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<MediaType> for String {
fn from(value: MediaType) -> Self {
value.0
}
}
impl AsRef<str> for MediaType {
fn as_ref(&self) -> &str {
&self.0
}
}
impl PartialEq<str> for MediaType {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for MediaType {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}