use crate::util::uri;
use std::borrow::Cow;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq)]
pub enum ResourceContent {
Memory(Vec<u8>),
File(PathBuf),
}
impl ResourceContent {
pub fn memory(buffer: impl Into<Vec<u8>>) -> Self {
Self::Memory(buffer.into())
}
pub fn file(path: impl Into<PathBuf>) -> Self {
Self::File(path.into())
}
pub fn is_memory(&self) -> bool {
matches!(self, ResourceContent::Memory(_))
}
pub fn is_file(&self) -> bool {
matches!(self, ResourceContent::File(_))
}
}
impl From<Vec<u8>> for ResourceContent {
fn from(value: Vec<u8>) -> Self {
Self::Memory(value)
}
}
impl From<&[u8]> for ResourceContent {
fn from(value: &[u8]) -> Self {
Self::Memory(value.to_vec())
}
}
impl<const N: usize> From<&[u8; N]> for ResourceContent {
fn from(value: &[u8; N]) -> Self {
Self::Memory(value.to_vec())
}
}
impl From<Cow<'_, [u8]>> for ResourceContent {
fn from(value: Cow<'_, [u8]>) -> Self {
Self::Memory(value.into_owned())
}
}
impl From<String> for ResourceContent {
fn from(value: String) -> Self {
Self::Memory(value.into_bytes())
}
}
impl From<&str> for ResourceContent {
fn from(value: &str) -> Self {
Self::Memory(value.as_bytes().to_vec())
}
}
impl From<Cow<'_, str>> for ResourceContent {
fn from(value: Cow<'_, str>) -> Self {
Self::Memory(value.into_owned().into_bytes())
}
}
impl From<PathBuf> for ResourceContent {
fn from(path: PathBuf) -> Self {
Self::File(path)
}
}
impl From<&Path> for ResourceContent {
fn from(path: &Path) -> Self {
Self::File(path.to_path_buf())
}
}
pub(crate) fn infer_media_type(href: &str) -> String {
let extension = uri::file_extension(href).unwrap_or_default();
match extension {
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
"svg" => "image/svg+xml",
"gif" => "image/gif",
"webp" => "image/webp",
"xhtml" => "application/xhtml+xml",
"html" | "htm" => "text/html",
"css" => "text/css",
"js" => "text/javascript",
"smil" => "application/smil+xml",
"ncx" => "application/x-dtbncx+xml",
"xml" => "application/xml",
"ttf" => "font/ttf",
"otf" => "font/otf",
"woff" => "font/woff",
"woff2" => "font/woff2",
"mp3" => "audio/mpeg",
"m4a" => "audio/mp4",
"aac" => "audio/aac",
"mp4" | "m4v" => "video/mp4",
"webm" => "video/webm",
_ => "application/octet-stream",
}
.to_owned()
}