use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serializer};
use serde_json::Value;
use crate::error::{Error, Result};
pub(crate) fn take_field<T: DeserializeOwned>(value: Value, field: &str) -> Result<T> {
let inner = match value {
Value::Object(mut map) => map
.remove(field)
.ok_or_else(|| Error::Decode(format!("the response has no `{field}` field")))?,
other => {
return Err(Error::Decode(format!(
"expected an object with `{field}`, got {other}"
)))
}
};
serde_json::from_value(inner).map_err(|error| Error::decode(field, error))
}
pub(crate) fn number<S: Serializer>(
value: &Option<f64>,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
match value {
Some(number) => whole_number(*number, serializer),
None => serializer.serialize_none(),
}
}
pub(crate) fn required_number<S: Serializer>(
value: &f64,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
whole_number(*value, serializer)
}
fn whole_number<S: Serializer>(number: f64, serializer: S) -> std::result::Result<S::Ok, S::Error> {
if number.fract() == 0.0 && number.abs() < 9_007_199_254_740_992.0 {
serializer.serialize_i64(number as i64)
} else {
serializer.serialize_f64(number)
}
}
pub(crate) fn u64_lenient<'de, D: Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<Option<u64>, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Lenient {
Number(u64),
Float(f64),
Text(String),
}
Ok(match Option::<Lenient>::deserialize(deserializer)? {
None => None,
Some(Lenient::Number(value)) => Some(value),
Some(Lenient::Float(value)) if value >= 0.0 => Some(value as u64),
Some(Lenient::Float(_)) => None,
Some(Lenient::Text(text)) => text.trim().parse().ok(),
})
}
pub(crate) fn null_default<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
where
D: Deserializer<'de>,
T: Default + Deserialize<'de>,
{
Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}
pub(crate) fn content_type_for(filename: &str) -> &'static str {
let extension = filename
.rsplit_once('.')
.map(|(_, extension)| extension.to_ascii_lowercase())
.unwrap_or_default();
match extension.as_str() {
"pdf" => "application/pdf",
"jpg" | "jpeg" | "jfif" => "image/jpeg",
"png" => "image/png",
"webp" => "image/webp",
"gif" => "image/gif",
"tif" | "tiff" => "image/tiff",
"bmp" => "image/bmp",
"avif" => "image/avif",
"heic" => "image/heic",
"svg" => "image/svg+xml",
"doc" => "application/msword",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xls" => "application/vnd.ms-excel",
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"ppt" => "application/vnd.ms-powerpoint",
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"odt" => "application/vnd.oasis.opendocument.text",
"ods" => "application/vnd.oasis.opendocument.spreadsheet",
"odp" => "application/vnd.oasis.opendocument.presentation",
"rtf" => "application/rtf",
"csv" => "text/csv",
"tsv" => "text/tab-separated-values",
"txt" | "text" => "text/plain",
"md" | "markdown" => "text/markdown",
"html" | "htm" => "text/html",
"url" => "text/plain",
"json" => "application/json",
"xml" => "application/xml",
"epub" => "application/epub+zip",
"zip" => "application/zip",
_ => "application/octet-stream",
}
}
pub(crate) fn extension_for(content_type: &str) -> &'static str {
match content_type.split(';').next().unwrap_or_default().trim() {
"application/pdf" => "pdf",
"image/jpeg" => "jpg",
"image/png" => "png",
"image/webp" => "webp",
"image/gif" => "gif",
"image/tiff" => "tiff",
"image/bmp" => "bmp",
"image/avif" => "avif",
"text/plain" => "txt",
"text/markdown" => "md",
"text/html" => "html",
"text/csv" => "csv",
"application/json" => "json",
"application/zip" => "zip",
"application/epub+zip" => "epub",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx",
_ => "bin",
}
}
pub(crate) fn safe_file_name(name: &str) -> Option<String> {
let last = name.rsplit(['/', '\\']).next().unwrap_or_default().trim();
let cleaned: String = last.chars().filter(|c| !c.is_control()).collect();
if cleaned.is_empty() || cleaned == "." || cleaned == ".." {
None
} else {
Some(cleaned)
}
}
pub(crate) fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push(DIGITS[(byte >> 4) as usize] as char);
out.push(DIGITS[(byte & 0x0f) as usize] as char);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_content_types_from_extensions() {
assert_eq!(content_type_for("scan.PDF"), "application/pdf");
assert_eq!(content_type_for("photo.jpeg"), "image/jpeg");
assert_eq!(
content_type_for("sheet.xlsx"),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
assert_eq!(content_type_for("noextension"), "application/octet-stream");
}
#[test]
fn strips_paths_from_server_file_names() {
assert_eq!(
safe_file_name("../../etc/passwd").as_deref(),
Some("passwd")
);
assert_eq!(safe_file_name("a\\b\\c.pdf").as_deref(), Some("c.pdf"));
assert_eq!(safe_file_name(".."), None);
}
#[test]
fn writes_whole_numbers_without_a_fraction() {
#[derive(serde::Serialize)]
struct S {
#[serde(serialize_with = "number")]
a: Option<f64>,
#[serde(serialize_with = "number")]
b: Option<f64>,
}
assert_eq!(
serde_json::to_string(&S {
a: Some(5.0),
b: Some(7.5)
})
.unwrap(),
r#"{"a":5,"b":7.5}"#
);
}
#[test]
fn reads_sizes_sent_as_strings() {
#[derive(serde::Deserialize)]
struct S {
#[serde(default, deserialize_with = "u64_lenient")]
size: Option<u64>,
}
let s: S = serde_json::from_str(r#"{"size":"2215244"}"#).unwrap();
assert_eq!(s.size, Some(2_215_244));
let s: S = serde_json::from_str(r#"{"size":12}"#).unwrap();
assert_eq!(s.size, Some(12));
}
}