pub const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream";
pub trait ContentTypeResolver: Send + Sync {
fn resolve(&self, data: &[u8]) -> String;
}
impl<F> ContentTypeResolver for F
where
F: Fn(&[u8]) -> String + Send + Sync,
{
fn resolve(&self, data: &[u8]) -> String {
(self)(data)
}
}
#[derive(Debug, Clone, Copy)]
#[deprecated(
since = "0.5.0",
note = "please use the new `default_resolver` fn to implement `ContentTypeResolver`"
)]
pub struct DefaultContentTypeResolver;
#[allow(deprecated)]
impl ContentTypeResolver for DefaultContentTypeResolver {
#[cfg(not(feature = "file-format"))]
fn resolve(&self, _bytes: &[u8]) -> String {
"application/octet-stream".into()
}
#[cfg(feature = "file-format")]
fn resolve(&self, bytes: &[u8]) -> String {
infer::get(bytes)
.map(|ty| ty.mime_type().to_owned())
.unwrap_or(file_format::FileFormat::from_bytes(bytes).media_type().to_owned())
}
}
#[cfg(feature = "file-format")]
pub fn default_resolver(data: &[u8]) -> String {
#[cfg(feature = "serde_json")]
if serde_json::from_slice::<()>(data).is_ok() {
return String::from("application/json; charset=utf-8");
}
#[cfg(feature = "serde_yaml")]
if serde_yaml::from_slice::<()>(data).is_ok() {
return String::from("application/yaml; charset=utf-8");
}
infer::get(data)
.map(|ty| ty.mime_type().to_owned())
.unwrap_or(file_format::FileFormat::from_bytes(data).media_type().to_owned())
}
#[cfg(not(feature = "file-format"))]
pub fn default_resolver(data: &[u8]) -> String {
#[cfg(feature = "serde_json")]
if serde_json::from_slice::<()>(data).is_ok() {
return String::from("application/json; charset=utf-8");
}
#[cfg(feature = "serde_yaml")]
if serde_yaml::from_slice::<()>(data).is_ok() {
return String::from("application/yaml; charset=utf-8");
}
DEFAULT_CONTENT_TYPE.into()
}