1#![deny(missing_docs)]
2
3use crate::{DateStr, errors::DateErrors};
4use std::ops::{Add, Sub};
5
6pub trait Into<DateStr> {
10 fn to_datestr(&self) -> DateStr;
12
13 fn try_to_datestr(&self) -> Result<DateStr, crate::errors::DateErrors>;
16}
17
18impl Into<DateStr> for String {
20 fn to_datestr(&self) -> DateStr {
21 DateStr::from_iso_str(self)
22 }
23
24 fn try_to_datestr(&self) -> Result<DateStr, crate::errors::DateErrors> {
25 DateStr::try_from_iso_str(self)
26 }
27}
28
29impl Into<DateStr> for str {
31 fn to_datestr(&self) -> DateStr {
32 DateStr::from_iso_str(self)
33 }
34
35 fn try_to_datestr(&self) -> Result<DateStr, crate::errors::DateErrors> {
36 DateStr::try_from_iso_str(self)
37 }
38}
39
40impl TryFrom<String> for DateStr {
41 type Error = DateErrors;
42
43 fn try_from(value: String) -> Result<Self, Self::Error> {
44 let split: Vec<String> = value.split('-').map(|s| s.to_string()).collect();
45 let year = match split[0].parse::<u64>() {
46 Ok(y) => crate::Year::new(y),
47 Err(_e) => return Err(DateErrors::InvalidParsing(value)),
48 };
49 let month = match split[1].parse::<u8>() {
50 Ok(y) => crate::Month::new(y)?,
51 Err(_e) => return Err(DateErrors::InvalidParsing(value)),
52 };
53 let day = match split[2].parse::<u8>() {
54 Ok(y) => crate::Day::new(y)?,
55 Err(_e) => return Err(DateErrors::InvalidParsing(value)),
56 };
57 Ok(DateStr { year, month, day })
58 }
59}
60
61impl From<DateStr> for String {
62 fn from(value: DateStr) -> Self {
63 value.to_string()
64 }
65}
66
67impl Add for DateStr {
68 type Output = Self;
69 fn add(self, rhs: Self) -> Self::Output {
70 let (day, months_from_day) = self.day + rhs.day;
71 let (months, years) = self.month + rhs.month;
72 let (month, more_years) = months + months_from_day;
73 let year = self.year + rhs.year + years + more_years;
74 DateStr { day, month, year }
75 }
76}
77
78impl Sub for DateStr {
79 type Output = Self;
80 fn sub(self, rhs: Self) -> Self::Output {
81 let (day, months_from_day) = self.day - rhs.day;
82 let (months, years) = self.month - rhs.month;
83 let (month, more_years) = months - months_from_day;
84 let year = self.year - rhs.year - years - more_years;
85 DateStr { day, month, year }
86 }
87}