From 7db974665834bb3d8afae54b1d7598560edeb6bc Mon Sep 17 00:00:00 2001 From: Ashley Wulber Date: Mon, 25 Mar 2024 15:59:13 -0400 Subject: [PATCH] feat: add conversion from string for MimeType --- src/mime.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/mime.rs b/src/mime.rs index 1809094..e2a3e3a 100644 --- a/src/mime.rs +++ b/src/mime.rs @@ -49,6 +49,22 @@ impl Default for MimeType { } } +impl From> for MimeType { + fn from(value: Cow<'static, str>) -> Self { + if let Some(pos) = ALLOWED_TEXT_MIME_TYPES.into_iter().position(|allowed| allowed == value) + { + MimeType::Text(match pos { + 0 => Text::TextPlainUtf8, + 1 => Text::Utf8String, + 2 => Text::TextPlain, + _ => unreachable!(), + }) + } else { + MimeType::Other(value) + } + } +} + impl AsRef for MimeType { fn as_ref(&self) -> &str { match self { @@ -120,3 +136,26 @@ impl std::fmt::Display for MimeType { pub fn normalize_to_lf(text: String) -> String { text.replace("\r\n", "\n").replace('\r', "\n") } + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + + use crate::mime::{MimeType, ALLOWED_TEXT_MIME_TYPES}; + + #[test] + fn test_from_str() { + assert_eq!( + MimeType::from(Cow::Borrowed(ALLOWED_TEXT_MIME_TYPES[0])), + MimeType::Text(crate::mime::Text::TextPlainUtf8) + ); + assert_eq!( + MimeType::from(Cow::Borrowed(ALLOWED_TEXT_MIME_TYPES[1])), + MimeType::Text(crate::mime::Text::Utf8String) + ); + assert_eq!( + MimeType::from(Cow::Borrowed(ALLOWED_TEXT_MIME_TYPES[2])), + MimeType::Text(crate::mime::Text::TextPlain) + ); + } +}