glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Casting text parameters into typed fields, as Ecto's `cast` does.
//!
//! Form fields arrive as text. Casting turns them into the field's type,
//! and a value that doesn't fit becomes a changeset error ("is invalid")
//! the form can show, rather than a `400 Bad Request`.

use super::value::Timestamp;

/// Types a request parameter can be cast into.
#[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 {
    /// Parses `raw`, or returns the error message for the field.
    fn cast(raw: &str) -> Result<Self, String>;
}

impl Cast for String {
    fn cast(raw: &str) -> Result<Self, String> {
        Ok(raw.to_owned())
    }
}

/// An empty (or whitespace-only) value is `None`.
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);

/// Checkbox-friendly: `true`/`on`/`1`/`yes` and `false`/`off`/`0`/`no`/empty.
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()),
        }
    }
}

/// RFC 3339 (`2026-10-03T12:00:00Z`), an HTML `datetime-local` value
/// (`2026-10-03T12:00`, read as UTC), or a timestamp as Rust displays one
/// (`2026-10-03 12:00:00.25`, with ` UTC` or without).
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())
    }
}

/// `2026-10-03`, as an HTML `date` input sends it.
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());
        // As a timestamp displays, so one round-trips through a form.
        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"
        );
    }
}