use super::*;
impl ContentType {
fn get_application_json<T>(data: &T) -> String
where
T: Serialize + Display,
{
serde_json::to_string(data).unwrap_or_default()
}
fn get_application_xml<T>(data: &T) -> String
where
T: Serialize + Display,
{
serde_xml_rs::to_string(data).unwrap_or_default()
}
fn get_text_plain<T>(data: &T) -> String
where
T: Serialize + Debug + Clone + Default + Display,
{
data.to_string()
}
fn get_text_html<T>(data: &T) -> String
where
T: Serialize + Debug + Clone + Default,
{
let mut html: String = String::with_capacity(64);
html.push_str(HTML_TABLE_OPEN);
let _: fmt::Result = write!(&mut html, "{data:?}");
html.push_str(HTML_TABLE_CLOSE);
html
}
fn get_form_url_encoded<T>(data: &T) -> String
where
T: Serialize + Display,
{
serde_urlencoded::to_string(data).unwrap_or_default()
}
fn get_binary<T>(data: &T) -> String
where
T: Serialize + Debug + Clone + Default + Display,
{
encode(data.to_string())
}
pub fn get_body_string<T>(&self, data: &T) -> String
where
T: Serialize + Debug + Clone + Default + Display,
{
match self {
Self::ApplicationJson => Self::get_application_json(data),
Self::ApplicationXml => Self::get_application_xml(data),
Self::TextPlain => Self::get_text_plain(data),
Self::TextHtml => Self::get_text_html(data),
Self::FormUrlEncoded => Self::get_form_url_encoded(data),
Self::Unknown => Self::get_binary(data),
}
}
pub fn format_content_type_with_charset<T, S>(content_type: T, charset: S) -> String
where
T: AsRef<str>,
S: AsRef<str>,
{
let content_type_ref: &str = content_type.as_ref();
let charset_ref: &str = charset.as_ref();
let mut result: String = String::with_capacity(
content_type_ref.len()
+ SEMICOLON_SPACE.len()
+ CHARSET_EQUAL.len()
+ charset_ref.len(),
);
result.push_str(content_type_ref);
result.push_str(SEMICOLON_SPACE);
result.push_str(CHARSET_EQUAL);
result.push_str(charset_ref);
result
}
pub fn format_content_type_with_charset_declaration<T, S>(
content_type: T,
charset_with_key: S,
) -> String
where
T: AsRef<str>,
S: AsRef<str>,
{
let content_type_ref: &str = content_type.as_ref();
let charset_with_key_ref: &str = charset_with_key.as_ref();
let mut result: String = String::with_capacity(
content_type_ref.len() + SEMICOLON_SPACE.len() + charset_with_key_ref.len(),
);
result.push_str(content_type_ref);
result.push_str(SEMICOLON_SPACE);
result.push_str(charset_with_key_ref);
result
}
}
impl FromStr for ContentType {
type Err = ();
#[inline(always)]
fn from_str(data: &str) -> Result<Self, Self::Err> {
let variant: Self = if data.eq_ignore_ascii_case(APPLICATION_JSON) {
Self::ApplicationJson
} else if data.eq_ignore_ascii_case(APPLICATION_XML) {
Self::ApplicationXml
} else if data.eq_ignore_ascii_case(TEXT_PLAIN) {
Self::TextPlain
} else if data.eq_ignore_ascii_case(TEXT_HTML) {
Self::TextHtml
} else if data.eq_ignore_ascii_case(FORM_URLENCODED) {
Self::FormUrlEncoded
} else {
Self::Unknown
};
Ok(variant)
}
}