Skip to main content

glacier/db/
cast.rs

1//! Casting text parameters into typed fields, as Ecto's `cast` does.
2//!
3//! Form fields arrive as text. Casting turns them into the field's type,
4//! and a value that doesn't fit becomes a changeset error ("is invalid")
5//! the form can show, rather than a `400 Bad Request`.
6
7use super::value::Timestamp;
8
9/// Types a request parameter can be cast into.
10#[diagnostic::on_unimplemented(
11    message = "`{Self}` can't be cast from a request parameter",
12    note = "mark the field `#[glacier(protected)]` to keep it out of params, \
13            or implement `glacier::db::Cast` for it"
14)]
15pub trait Cast: Sized {
16    /// Parses `raw`, or returns the error message for the field.
17    fn cast(raw: &str) -> Result<Self, String>;
18}
19
20impl Cast for String {
21    fn cast(raw: &str) -> Result<Self, String> {
22        Ok(raw.to_owned())
23    }
24}
25
26/// An empty (or whitespace-only) value is `None`.
27impl<T: Cast> Cast for Option<T> {
28    fn cast(raw: &str) -> Result<Self, String> {
29        if raw.trim().is_empty() {
30            Ok(None)
31        } else {
32            T::cast(raw).map(Some)
33        }
34    }
35}
36
37macro_rules! cast_numbers {
38    ($($t:ty),*) => {$(
39        impl Cast for $t {
40            fn cast(raw: &str) -> Result<Self, String> {
41                raw.trim().parse().map_err(|_| "is not a number".to_owned())
42            }
43        }
44    )*};
45}
46
47cast_numbers!(i8, i16, i32, i64, u8, u16, u32, f32, f64);
48
49/// Checkbox-friendly: `true`/`on`/`1`/`yes` and `false`/`off`/`0`/`no`/empty.
50impl Cast for bool {
51    fn cast(raw: &str) -> Result<Self, String> {
52        match raw.trim().to_ascii_lowercase().as_str() {
53            "true" | "on" | "1" | "yes" => Ok(true),
54            "false" | "off" | "0" | "no" | "" => Ok(false),
55            _ => Err("is invalid".to_owned()),
56        }
57    }
58}
59
60/// RFC 3339 (`2026-10-03T12:00:00Z`), an HTML `datetime-local` value
61/// (`2026-10-03T12:00`, read as UTC), or a timestamp as Rust displays one
62/// (`2026-10-03 12:00:00.25`, with ` UTC` or without).
63impl Cast for Timestamp {
64    fn cast(raw: &str) -> Result<Self, String> {
65        let raw = raw.trim();
66        if let Ok(t) = chrono::DateTime::parse_from_rfc3339(raw) {
67            return Ok(t.with_timezone(&chrono::Utc));
68        }
69        let raw = raw.strip_suffix(" UTC").unwrap_or(raw);
70        [
71            "%Y-%m-%dT%H:%M",
72            "%Y-%m-%dT%H:%M:%S%.f",
73            "%Y-%m-%d %H:%M",
74            "%Y-%m-%d %H:%M:%S%.f",
75        ]
76        .iter()
77        .find_map(|format| chrono::NaiveDateTime::parse_from_str(raw, format).ok())
78        .map(|naive| naive.and_utc())
79        .ok_or_else(|| "is not a valid date and time".to_owned())
80    }
81}
82
83/// `2026-10-03`, as an HTML `date` input sends it.
84impl Cast for crate::db::Date {
85    fn cast(raw: &str) -> Result<Self, String> {
86        chrono::NaiveDate::parse_from_str(raw.trim(), "%Y-%m-%d")
87            .map_err(|_| "is not a valid date".to_owned())
88    }
89}
90
91impl Cast for crate::db::Uuid {
92    fn cast(raw: &str) -> Result<Self, String> {
93        raw.trim()
94            .parse()
95            .map_err(|_| "is not a valid UUID".to_owned())
96    }
97}
98
99impl Cast for crate::db::Decimal {
100    fn cast(raw: &str) -> Result<Self, String> {
101        raw.parse().map_err(|_| "is not a number".to_owned())
102    }
103}
104
105impl Cast for crate::db::NaiveTimestamp {
106    fn cast(raw: &str) -> Result<Self, String> {
107        Timestamp::cast(raw).map(|t| t.naive_utc())
108    }
109}
110
111impl Cast for crate::db::JsonValue {
112    fn cast(raw: &str) -> Result<Self, String> {
113        serde_json::from_str(raw).map_err(|_| "is not valid JSON".to_owned())
114    }
115}
116
117impl Cast for Vec<u8> {
118    fn cast(raw: &str) -> Result<Self, String> {
119        Ok(raw.as_bytes().to_vec())
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn casts_common_types() {
129        assert_eq!(i32::cast(" 42 "), Ok(42));
130        assert_eq!(i32::cast("4x"), Err("is not a number".into()));
131        assert_eq!(Option::<i64>::cast(""), Ok(None));
132        assert_eq!(Option::<String>::cast("  "), Ok(None));
133        assert_eq!(Option::<String>::cast("hi"), Ok(Some("hi".into())));
134        assert_eq!(bool::cast("on"), Ok(true));
135        assert_eq!(bool::cast(""), Ok(false));
136        assert!(bool::cast("maybe").is_err());
137        assert_eq!(
138            Timestamp::cast("2026-10-03T12:30").unwrap().to_rfc3339(),
139            "2026-10-03T12:30:00+00:00"
140        );
141        assert!(Timestamp::cast("yesterday").is_err());
142        // As a timestamp displays, so one round-trips through a form.
143        let at = chrono::NaiveDate::from_ymd_opt(2026, 10, 3)
144            .unwrap()
145            .and_hms_nano_opt(12, 30, 5, 123_456_789)
146            .unwrap();
147        assert_eq!(crate::db::NaiveTimestamp::cast(&at.to_string()), Ok(at));
148        assert_eq!(Timestamp::cast(&at.and_utc().to_string()), Ok(at.and_utc()));
149        assert_eq!(
150            Timestamp::cast("2026-10-03 12:30").unwrap().to_rfc3339(),
151            "2026-10-03T12:30:00+00:00"
152        );
153    }
154}