1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use time::{format_description, OffsetDateTime};

pub(crate) const MANGADEX_DATETIME_DE_FORMAT: &str =
    "[year]-[month]-[day]T[hour]:[minute]:[second][offset_hour sign:mandatory]:[offset_minute]";

pub(crate) const MANGADEX_DATETIME_SER_FORMAT: &str =
    "[year]-[month]-[day]T[hour]:[minute]:[second]";

/// Newtype struct for handling datetime fields in MangaDex.
#[derive(Debug, Clone, PartialEq)]
pub struct MangaDexDateTime(OffsetDateTime);

impl MangaDexDateTime {
    pub fn new(datetime: &OffsetDateTime) -> Self {
        Self(*datetime)
    }
}

impl From<OffsetDateTime> for MangaDexDateTime {
    fn from(datetime: OffsetDateTime) -> Self {
        Self(datetime)
    }
}

impl AsRef<OffsetDateTime> for MangaDexDateTime {
    fn as_ref(&self) -> &OffsetDateTime {
        &self.0
    }
}

impl Serialize for MangaDexDateTime {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let format = format_description::parse(MANGADEX_DATETIME_SER_FORMAT).unwrap();

        serializer.serialize_str(&self.as_ref().format(&format).unwrap())
    }
}

impl<'de> Deserialize<'de> for MangaDexDateTime {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s: String = Deserialize::deserialize(deserializer)?;

        let format = format_description::parse(MANGADEX_DATETIME_DE_FORMAT).unwrap();

        let datetime = OffsetDateTime::parse(&s, &format).unwrap();

        Ok(MangaDexDateTime(datetime))
    }
}

impl std::fmt::Display for MangaDexDateTime {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        let format = format_description::parse(MANGADEX_DATETIME_DE_FORMAT).unwrap();

        fmt.write_str(&self.as_ref().format(&format).unwrap())
    }
}