use chrono::{Datelike, NaiveDate};
use serde::{self, Deserialize, Serialize};
use std::ops::Deref;
use crate::error::TypeError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BirthDate(NaiveDate);
impl BirthDate {
pub const FORMAT: &'static str = "%Y-%m-%d";
pub fn parse(value: impl AsRef<str>) -> Result<Self, TypeError> {
let raw = value.as_ref().trim();
let date =
NaiveDate::parse_from_str(raw, Self::FORMAT).map_err(|_| BirthDateError::Date)?;
Self::from_naive_date(date)
}
pub fn from_naive_date(date: NaiveDate) -> Result<Self, TypeError> {
let today = chrono::Local::now().date_naive();
if date > today {
return Err(BirthDateError::FutureDate.into());
}
Ok(Self(date))
}
#[inline]
pub fn as_naive_date(&self) -> &NaiveDate {
&self.0
}
#[inline]
pub fn into_inner(self) -> NaiveDate {
self.0
}
#[inline]
pub fn year(&self) -> i32 {
self.0.year()
}
#[inline]
pub fn month(&self) -> u32 {
self.0.month()
}
#[inline]
pub fn day(&self) -> u32 {
self.0.day()
}
}
impl Deref for BirthDate {
type Target = NaiveDate;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl AsRef<NaiveDate> for BirthDate {
#[inline]
fn as_ref(&self) -> &NaiveDate {
&self.0
}
}
impl std::fmt::Display for BirthDate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.format(Self::FORMAT))
}
}
impl TryFrom<&str> for BirthDate {
type Error = TypeError;
fn try_from(value: &str) -> Result<Self, TypeError> {
Self::parse(value)
}
}
impl TryFrom<String> for BirthDate {
type Error = TypeError;
fn try_from(value: String) -> Result<Self, TypeError> {
Self::parse(value)
}
}
impl TryFrom<NaiveDate> for BirthDate {
type Error = TypeError;
fn try_from(value: NaiveDate) -> Result<Self, TypeError> {
Self::from_naive_date(value)
}
}
impl From<BirthDate> for NaiveDate {
fn from(value: BirthDate) -> Self {
value.into_inner()
}
}
impl From<BirthDate> for String {
fn from(value: BirthDate) -> Self {
value.to_string()
}
}
impl Serialize for BirthDate {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
#[allow(unknown_lints)]
impl<'de> Deserialize<'de> for BirthDate {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = <&str>::deserialize(deserializer)?;
Self::parse(s).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum BirthDateError {
#[error("invalid birth date format or value, expected YYYY-MM-DD")]
Date,
#[error("birth date cannot be in the future")]
FutureDate,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_valid_birth_date() {
let date = BirthDate::parse("1990-05-15").unwrap();
assert_eq!(date.to_string(), "1990-05-15");
assert_eq!(date.year(), 1990);
assert_eq!(date.month(), 5);
assert_eq!(date.day(), 15);
}
#[test]
fn parse_should_fail_for_invalid_format() {
assert!(matches!(
BirthDate::parse("15-05-1990").unwrap_err(),
TypeError::BirthDate(BirthDateError::Date)
));
assert!(matches!(
BirthDate::parse("1990/05/15").unwrap_err(),
TypeError::BirthDate(BirthDateError::Date)
));
}
#[test]
fn parse_should_fail_for_invalid_month() {
assert!(matches!(
BirthDate::parse("1990-13-01").unwrap_err(),
TypeError::BirthDate(BirthDateError::Date)
));
}
#[test]
fn parse_should_fail_for_invalid_day() {
assert!(matches!(
BirthDate::parse("1990-01-32").unwrap_err(),
TypeError::BirthDate(BirthDateError::Date)
));
}
#[test]
fn parse_should_validate_leap_year() {
assert!(BirthDate::parse("2000-02-29").is_ok());
assert!(matches!(
BirthDate::parse("1999-02-29").unwrap_err(),
TypeError::BirthDate(BirthDateError::Date)
));
}
#[test]
fn parse_should_fail_for_future_date() {
assert!(matches!(
BirthDate::parse("2100-01-01").unwrap_err(),
TypeError::BirthDate(BirthDateError::FutureDate)
));
}
#[test]
fn parse_should_trim_whitespace() {
let date = BirthDate::parse(" 1990-05-15 ").unwrap();
assert_eq!(date.to_string(), "1990-05-15");
}
#[test]
fn display_and_deref_should_work() {
let date = BirthDate::parse("2000-01-01").unwrap();
assert_eq!(format!("{}", date), "2000-01-01");
assert!(date.leap_year()); assert_eq!(date.as_naive_date(), &date.into_inner());
}
#[test]
fn birth_date_should_implement_copy() {
let first = BirthDate::parse("1985-03-20").unwrap();
let second = first; assert_eq!(first, second);
}
#[test]
fn test_try_from_and_from_conversions() {
let date_str = BirthDate::try_from("1990-05-15").unwrap();
let date_string = BirthDate::try_from(String::from("1990-05-15")).unwrap();
assert_eq!(date_str, date_string);
let naive = NaiveDate::from_ymd_opt(1990, 5, 15).unwrap();
let date_naive = BirthDate::try_from(naive).unwrap();
assert_eq!(date_str, date_naive);
let value_string: String = date_str.into();
assert_eq!(value_string, "1990-05-15");
let value_naive: NaiveDate = date_str.into();
assert_eq!(value_naive, naive);
}
#[test]
fn birth_date_should_support_serde_roundtrip() {
let date = BirthDate::parse("1990-05-15").unwrap();
let json = serde_json::to_string(&date).unwrap();
assert_eq!(json, "\"1990-05-15\"");
let restored: BirthDate = serde_json::from_str(&json).unwrap();
assert_eq!(date, restored);
}
#[test]
fn deserialize_should_validate_format_and_future_dates() {
let valid_json = "\"2025-01-01\"";
let date: BirthDate = serde_json::from_str(valid_json).unwrap();
assert_eq!(date.to_string(), "2025-01-01");
let invalid_json = "\"2100-01-01\"";
assert!(serde_json::from_str::<BirthDate>(invalid_json).is_err());
}
}