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 enum DateFormat {
YmdHyphen,
DmyHyphen,
YmdDot,
DmyDot,
}
impl DateFormat {
pub const fn as_str(&self) -> &'static str {
match self {
Self::YmdHyphen => "%Y-%m-%d",
Self::DmyHyphen => "%d-%m-%Y",
Self::YmdDot => "%Y.%m.%d",
Self::DmyDot => "%d.%m.%Y",
}
}
pub fn reversed(&self) -> Self {
match self {
Self::YmdHyphen => Self::DmyHyphen,
Self::DmyHyphen => Self::YmdHyphen,
Self::YmdDot => Self::DmyDot,
Self::DmyDot => Self::YmdDot,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BirthDate(NaiveDate);
impl BirthDate {
pub const DEFAULT_FORMAT: DateFormat = DateFormat::YmdHyphen;
pub fn parse(value: impl AsRef<str>) -> Result<Self, TypeError> {
Self::parse_with_format(value, Self::DEFAULT_FORMAT)
}
pub fn parse_with_format(
value: impl AsRef<str>,
format: DateFormat,
) -> Result<Self, TypeError> {
let raw = value.as_ref().trim();
let date =
NaiveDate::parse_from_str(raw, format.as_str()).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))
}
pub fn format_as(&self, format: DateFormat) -> String {
self.0.format(format.as_str()).to_string()
}
pub fn format_reversed(&self, current_format: DateFormat) -> String {
let target_format = current_format.reversed();
self.format_as(target_format)
}
#[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::DEFAULT_FORMAT.as_str()))
}
}
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")]
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");
}
#[test]
fn test_format_state_hyphen_reversal() {
let date = BirthDate::parse_with_format("1990-05-15", DateFormat::YmdHyphen).unwrap();
let dmy = date.format_as(DateFormat::DmyHyphen);
assert_eq!(dmy, "15-05-1990");
let reversed_from_ymd = date.format_reversed(DateFormat::YmdHyphen);
assert_eq!(reversed_from_ymd, "15-05-1990");
let date_dmy = BirthDate::parse_with_format("15-05-1990", DateFormat::DmyHyphen).unwrap();
let reversed_from_dmy = date_dmy.format_reversed(DateFormat::DmyHyphen);
assert_eq!(reversed_from_dmy, "1990-05-15");
}
#[test]
fn test_format_state_dot_reversal() {
let date_ymd_dot = BirthDate::parse_with_format("1990.05.15", DateFormat::YmdDot).unwrap();
assert_eq!(
date_ymd_dot.format_reversed(DateFormat::YmdDot),
"15.05.1990"
);
let date_dmy_dot = BirthDate::parse_with_format("15.05.1990", DateFormat::DmyDot).unwrap();
assert_eq!(
date_dmy_dot.format_reversed(DateFormat::DmyDot),
"1990.05.15"
);
}
#[test]
fn parse_should_fail_for_invalid_format() {
assert!(BirthDate::parse_with_format("15-05-1990", DateFormat::YmdHyphen).is_err());
}
#[test]
fn birth_date_should_support_serde_roundtrip() {
let date = BirthDate::parse("1990-05-15").unwrap();
let json = serde_json::to_string(&date).unwrap();
let restored: BirthDate = serde_json::from_str(&json).unwrap();
assert_eq!(date, restored);
}
}