use crate::haystack::val::{ConversionError, Value};
use chrono::NaiveDate;
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter};
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub struct Date {
value: NaiveDate,
}
impl Date {
pub fn from_ymd(year: i32, month: u32, day: u32) -> Result<Date, String> {
let date = NaiveDate::from_ymd_opt(year, month, day);
if let Some(value) = date {
Ok(Date { value })
} else {
Err("Invalid parameters".into())
}
}
}
impl PartialOrd for Date {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Date {
fn cmp(&self, other: &Self) -> Ordering {
self.value.cmp(&other.value)
}
}
impl Deref for Date {
type Target = NaiveDate;
#[inline]
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl DerefMut for Date {
#[inline]
fn deref_mut(&mut self) -> &mut NaiveDate {
&mut self.value
}
}
impl FromStr for Date {
type Err = chrono::format::ParseError;
fn from_str(val: &str) -> Result<Self, Self::Err> {
Ok(Date {
value: NaiveDate::from_str(val)?,
})
}
}
impl Display for Date {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
Debug::fmt(&self.value, f)
}
}
impl From<NaiveDate> for Date {
fn from(value: NaiveDate) -> Self {
Self { value }
}
}
impl From<Date> for Value {
fn from(value: Date) -> Self {
Value::Date(value)
}
}
impl TryFrom<&Value> for Date {
type Error = ConversionError;
fn try_from(value: &Value) -> Result<Self, Self::Error> {
match value {
Value::Date(v) => Ok(*v),
_ => Err("Value is not an `Date`"),
}
}
}