laravel-casts 0.2.0

Eloquent-style attribute casts for laravel-rust models: DateCast and DateTimeCast read, write and serialize a date column in a PHP format
Documentation
//! A date cast stored as data, not shown to people: in a JSON column, a cache or a queued job.
//!
//! `Serialize` on a date cast writes its display pattern (`31/01/26`), which is what a response shows and which loses
//! information: the century, the seconds. With this module a field is written in the storage format (`2026-01-31`,
//! `2026-01-31 10:05:00`), whatever [`configure`](crate::configure) says. A date and time with a fraction of a second
//! is written with its six digits of microseconds (`2026-01-31 10:05:00.500000`), which is what a column keeps at most:
//! nanoseconds below that are not written.
//!
//! ```
//! use laravel_casts::{DateCast, DateTimeCast};
//!
//! #[derive(serde::Serialize, serde::Deserialize)]
//! struct Contract {
//!     #[serde(with = "laravel_casts::canonical")]
//!     signed_on: DateCast,
//!     #[serde(default, with = "laravel_casts::canonical::option")]
//!     closed_at: Option<DateTimeCast>,
//! }
//!
//! let contract: Contract = serde_json::from_str(r#"{"signed_on":"1965-05-01"}"#)?;
//! assert_eq!(
//!     serde_json::to_string(&contract)?,
//!     r#"{"signed_on":"1965-05-01","closed_at":null}"#
//! );
//! # Ok::<_, serde_json::Error>(())
//! ```
//!
//! The storage format is tried first. It also reads the display pattern, so JSON that was persisted without this module
//! can still be loaded, as long as the configuration is the one it was written with. What that text had already lost
//! stays lost: `01/05/65` is 2065.

use crate::{Cast, Format, Storage};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serializer};

/// Writes the storage format.
///
/// # Errors
/// Whatever the serializer says.
pub fn serialize<S: Storage, F: Format, Z: Serializer>(
    cast: &Cast<S, F>,
    serializer: Z,
) -> Result<Z::Ok, Z::Error> {
    serializer.serialize_str(&cast.canonical())
}

/// Reads the storage format, or the display pattern of the cast.
///
/// # Errors
/// A value that is neither.
pub fn deserialize<'de, S: Storage, F: Format, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Cast<S, F>, D::Error> {
    let text = String::deserialize(deserializer)?;
    Cast::from_canonical(&text).map_err(D::Error::custom)
}

/// The same for `Option<DateCast>` and `Option<DateTimeCast>`. Add `#[serde(default)]` to accept a missing field.
pub mod option {
    use crate::{Cast, Format, Storage};
    use serde::de::Error as _;
    use serde::{Deserialize, Deserializer, Serializer};

    /// Writes the storage format, or `null`.
    ///
    /// # Errors
    /// Whatever the serializer says.
    pub fn serialize<S: Storage, F: Format, Z: Serializer>(
        cast: &Option<Cast<S, F>>,
        serializer: Z,
    ) -> Result<Z::Ok, Z::Error> {
        match cast {
            Some(cast) => serializer.serialize_some(&cast.canonical()),
            None => serializer.serialize_none(),
        }
    }

    /// Reads what [`serialize`] writes, or the display pattern of the cast.
    ///
    /// # Errors
    /// A value that is neither, nor `null`.
    pub fn deserialize<'de, S: Storage, F: Format, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Option<Cast<S, F>>, D::Error> {
        Option::<String>::deserialize(deserializer)?
            .map(|text| Cast::from_canonical(&text).map_err(D::Error::custom))
            .transpose()
    }
}