use crate::config;
use crate::kind::{DateAndTime, DateOnly, Format, Kind, Storage, midnight};
use crate::pattern::{Pattern, format_with};
use crate::{CastError, ColumnCast};
use laravel::db::{AnyRow, Decode, Nullable, Value};
use laravel::time::Timestamp;
use laravel::time::civil::{Date, DateTime, date};
use laravel::time::tz::TimeZone;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;
pub struct Cast<S, F = crate::Configured> {
value: DateTime,
kind: Kind,
marker: PhantomData<fn() -> (S, F)>,
}
pub type DateCast<F = crate::Configured> = Cast<DateOnly, F>;
pub type DateTimeCast<F = crate::Configured> = Cast<DateAndTime, F>;
impl<S: Storage, F: Format> Cast<S, F> {
#[must_use]
pub const fn new(value: DateTime) -> Self {
Self {
value,
kind: S::KIND,
marker: PhantomData,
}
}
#[must_use]
pub const fn datetime(&self) -> DateTime {
self.value
}
#[must_use]
pub fn date(&self) -> Date {
self.value.date()
}
pub fn format(&self, pattern: &str) -> crate::Result<String> {
format_with(pattern, &self.moment())
}
pub fn check_format() -> crate::Result<()> {
pattern_of(F::get(), S::KIND)?;
if F::PARSE_SET {
let set = pattern_of(F::set(), S::KIND)?;
let sample = date(2026, 11, 28).at(23, 45, 56, 0);
if set.parse(&set.format(&sample)).is_none() {
return Err(crate::Error::InvalidFormat(format!(
"the date pattern \"{}\" cannot read back what it prints",
set.source()
)));
}
}
Ok(())
}
fn display(&self) -> crate::Result<String> {
let moment = self.moment();
match F::get() {
Some(own) => format_with(own, &moment),
None => Ok(config::pattern(S::KIND).format(&moment)),
}
}
fn read(value: DateTime) -> Self {
Self::new(match S::KIND {
Kind::Date => midnight(value.date()),
Kind::DateTime => value,
})
}
pub(crate) fn canonical(&self) -> String {
let moment = self.moment();
let stored = config::storage(S::KIND).format(&moment);
match moment.subsec_nanosecond() / 1_000 {
0 => stored,
micros => format!("{stored}.{micros:06}"),
}
}
pub(crate) fn from_canonical(text: &str) -> Result<Self, CastError> {
let stored = config::storage(S::KIND);
let value = match stored
.parse(text)
.or_else(|| with_microseconds::<S>(text, stored))
{
Some(value) => Some(value),
None => pattern_of(F::get(), S::KIND)?.parse(text),
};
value.map(Self::read).ok_or_else(|| {
CastError::Rejected(format!(
"\"{text}\" is not a valid date in the format {}",
stored.source()
))
})
}
fn parse(text: &str) -> crate::Result<Option<Self>> {
let storage = config::storage(S::KIND);
let parsed = if F::PARSE_SET {
let set = pattern_of(F::set(), S::KIND)?;
set.parse(text)
.or_else(|| storage.parse(text))
.or_else(|| set.parse_typed(text))
} else {
storage.parse(text)
};
Ok(parsed.map(Self::read))
}
}
impl<S: Storage, F: Format> Decode for Cast<S, F> {
fn decode(row: &AnyRow, index: usize) -> laravel::Result<Self> {
Ok(match S::KIND {
Kind::Date => Self::new(midnight(Date::decode(row, index)?)),
Kind::DateTime => Self::new(DateTime::decode(row, index)?),
})
}
}
impl<S: Storage, F: Format> Nullable for Cast<S, F> {
fn null() -> Value<'static> {
match S::KIND {
Kind::Date => Value::Date(None),
Kind::DateTime => Value::DateTime(None),
}
}
}
impl<S: Storage, F: Format> From<Cast<S, F>> for Value<'_> {
fn from(cast: Cast<S, F>) -> Self {
match S::KIND {
Kind::Date => Value::Date(Some(cast.value.date())),
Kind::DateTime => Value::DateTime(Some(cast.value)),
}
}
}
impl<'a, S: Storage, F: Format> From<&'a Cast<S, F>> for Value<'a> {
fn from(cast: &'a Cast<S, F>) -> Self {
(*cast).into()
}
}
impl<'a, S: Storage, F: Format> From<&&'a Cast<S, F>> for Value<'a> {
fn from(cast: &&'a Cast<S, F>) -> Self {
(**cast).into()
}
}
impl<S: Storage, F: Format> Serialize for Cast<S, F> {
fn serialize<T: Serializer>(&self, serializer: T) -> Result<T::Ok, T::Error> {
serializer.serialize_str(&self.display().map_err(serde::ser::Error::custom)?)
}
}
impl<'de, S: Storage, F: Format> Deserialize<'de> for Cast<S, F> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
Self::parse(&text)
.map_err(de::Error::custom)?
.ok_or_else(|| {
de::Error::custom(format!("\"{text}\" is not a valid {}", Self::expected()))
})
}
}
impl<F: Format> ColumnCast for Cast<DateOnly, F> {
type Repr = Date;
fn from_repr(date: Date) -> Result<Self, CastError> {
Ok(date.into())
}
fn to_repr(&self) -> Date {
self.value.date()
}
}
impl<F: Format> ColumnCast for Cast<DateAndTime, F> {
type Repr = DateTime;
fn from_repr(value: DateTime) -> Result<Self, CastError> {
Ok(value.into())
}
fn to_repr(&self) -> DateTime {
self.value
}
}
impl<S: Storage, F: Format> Cast<S, F> {
fn expected() -> String {
let pattern = match (F::PARSE_SET, F::set()) {
(false, _) => S::KIND.storage().to_owned(),
(true, Some(own)) => own.to_owned(),
(true, None) => config::pattern(S::KIND).source().to_owned(),
};
format!("date in the format {pattern}")
}
}
fn with_microseconds<S: Storage>(text: &str, stored: &Pattern) -> Option<DateTime> {
let (seconds, fraction) = text.rsplit_once('.')?;
if S::KIND != Kind::DateTime
|| fraction.len() != 6
|| !fraction.bytes().all(|byte| byte.is_ascii_digit())
{
return None;
}
let nanoseconds = fraction.parse::<i32>().ok()? * 1_000;
stored
.parse(seconds)?
.with()
.subsec_nanosecond(nanoseconds)
.build()
.ok()
}
fn pattern_of(own: Option<&str>, kind: Kind) -> crate::Result<Arc<Pattern>> {
match own {
Some(own) => Pattern::compile(own).map(Arc::new),
None => Ok(config::pattern(kind)),
}
}
impl<F: Format> From<Date> for Cast<DateOnly, F> {
fn from(date: Date) -> Self {
Self::new(midnight(date))
}
}
impl<F: Format> From<DateTime> for Cast<DateAndTime, F> {
fn from(value: DateTime) -> Self {
Self::new(value)
}
}
impl<F: Format> From<Timestamp> for Cast<DateAndTime, F> {
fn from(moment: Timestamp) -> Self {
Self::new(TimeZone::UTC.to_datetime(moment))
}
}
impl<S, F> Cast<S, F> {
fn moment(&self) -> DateTime {
match self.kind {
Kind::Date => midnight(self.value.date()),
Kind::DateTime => self.value,
}
}
}
impl<S, F> Clone for Cast<S, F> {
fn clone(&self) -> Self {
*self
}
}
impl<S, F> Copy for Cast<S, F> {}
impl<S, F> PartialEq for Cast<S, F> {
fn eq(&self, other: &Self) -> bool {
self.moment() == other.moment()
}
}
impl<S, F> Eq for Cast<S, F> {}
impl<S, F> PartialOrd for Cast<S, F> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<S, F> Ord for Cast<S, F> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.moment().cmp(&other.moment())
}
}
impl<S, F> std::hash::Hash for Cast<S, F> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.moment().hash(state);
}
}
impl<S, F> fmt::Debug for Cast<S, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Cast").field(&self.moment()).finish()
}
}