use super::value::Timestamp;
#[diagnostic::on_unimplemented(
message = "`{Self}` can't be cast from a request parameter",
note = "mark the field `#[glacier(protected)]` to keep it out of params, \
or implement `glacier::db::Cast` for it"
)]
pub trait Cast: Sized {
fn cast(raw: &str) -> Result<Self, String>;
}
impl Cast for String {
fn cast(raw: &str) -> Result<Self, String> {
Ok(raw.to_owned())
}
}
impl<T: Cast> Cast for Option<T> {
fn cast(raw: &str) -> Result<Self, String> {
if raw.trim().is_empty() {
Ok(None)
} else {
T::cast(raw).map(Some)
}
}
}
macro_rules! cast_numbers {
($($t:ty),*) => {$(
impl Cast for $t {
fn cast(raw: &str) -> Result<Self, String> {
raw.trim().parse().map_err(|_| "is not a number".to_owned())
}
}
)*};
}
cast_numbers!(i8, i16, i32, i64, u8, u16, u32, f32, f64);
impl Cast for bool {
fn cast(raw: &str) -> Result<Self, String> {
match raw.trim().to_ascii_lowercase().as_str() {
"true" | "on" | "1" | "yes" => Ok(true),
"false" | "off" | "0" | "no" | "" => Ok(false),
_ => Err("is invalid".to_owned()),
}
}
}
impl Cast for Timestamp {
fn cast(raw: &str) -> Result<Self, String> {
let raw = raw.trim();
if let Ok(t) = chrono::DateTime::parse_from_rfc3339(raw) {
return Ok(t.with_timezone(&chrono::Utc));
}
let raw = raw.strip_suffix(" UTC").unwrap_or(raw);
[
"%Y-%m-%dT%H:%M",
"%Y-%m-%dT%H:%M:%S%.f",
"%Y-%m-%d %H:%M",
"%Y-%m-%d %H:%M:%S%.f",
]
.iter()
.find_map(|format| chrono::NaiveDateTime::parse_from_str(raw, format).ok())
.map(|naive| naive.and_utc())
.ok_or_else(|| "is not a valid date and time".to_owned())
}
}
impl Cast for crate::db::Date {
fn cast(raw: &str) -> Result<Self, String> {
chrono::NaiveDate::parse_from_str(raw.trim(), "%Y-%m-%d")
.map_err(|_| "is not a valid date".to_owned())
}
}
impl Cast for crate::db::Uuid {
fn cast(raw: &str) -> Result<Self, String> {
raw.trim()
.parse()
.map_err(|_| "is not a valid UUID".to_owned())
}
}
impl Cast for crate::db::Decimal {
fn cast(raw: &str) -> Result<Self, String> {
raw.parse().map_err(|_| "is not a number".to_owned())
}
}
impl Cast for crate::db::NaiveTimestamp {
fn cast(raw: &str) -> Result<Self, String> {
Timestamp::cast(raw).map(|t| t.naive_utc())
}
}
impl Cast for crate::db::JsonValue {
fn cast(raw: &str) -> Result<Self, String> {
serde_json::from_str(raw).map_err(|_| "is not valid JSON".to_owned())
}
}
impl Cast for Vec<u8> {
fn cast(raw: &str) -> Result<Self, String> {
Ok(raw.as_bytes().to_vec())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn casts_common_types() {
assert_eq!(i32::cast(" 42 "), Ok(42));
assert_eq!(i32::cast("4x"), Err("is not a number".into()));
assert_eq!(Option::<i64>::cast(""), Ok(None));
assert_eq!(Option::<String>::cast(" "), Ok(None));
assert_eq!(Option::<String>::cast("hi"), Ok(Some("hi".into())));
assert_eq!(bool::cast("on"), Ok(true));
assert_eq!(bool::cast(""), Ok(false));
assert!(bool::cast("maybe").is_err());
assert_eq!(
Timestamp::cast("2026-10-03T12:30").unwrap().to_rfc3339(),
"2026-10-03T12:30:00+00:00"
);
assert!(Timestamp::cast("yesterday").is_err());
let at = chrono::NaiveDate::from_ymd_opt(2026, 10, 3)
.unwrap()
.and_hms_nano_opt(12, 30, 5, 123_456_789)
.unwrap();
assert_eq!(crate::db::NaiveTimestamp::cast(&at.to_string()), Ok(at));
assert_eq!(Timestamp::cast(&at.and_utc().to_string()), Ok(at.and_utc()));
assert_eq!(
Timestamp::cast("2026-10-03 12:30").unwrap().to_rfc3339(),
"2026-10-03T12:30:00+00:00"
);
}
}