twilight_model/channel/thread/
auto_archive_duration.rs

1use serde::{Deserialize, Serialize};
2use std::time::Duration;
3
4#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
5#[serde(from = "u16", into = "u16")]
6pub enum AutoArchiveDuration {
7    Hour,
8    Day,
9    ThreeDays,
10    Week,
11    Unknown { value: u16 },
12}
13
14impl AutoArchiveDuration {
15    /// Retrieve the length of the duration in minutes, used by the API
16    ///
17    /// # Examples
18    ///
19    /// ```
20    /// use twilight_model::channel::thread::AutoArchiveDuration;
21    ///
22    /// assert_eq!(60, AutoArchiveDuration::Hour.number());
23    /// ```
24    pub const fn number(self) -> u16 {
25        match self {
26            Self::Hour => 60,
27            Self::Day => 1440,
28            Self::ThreeDays => 4320,
29            Self::Week => 10080,
30            Self::Unknown { value } => value,
31        }
32    }
33}
34
35impl From<u16> for AutoArchiveDuration {
36    fn from(value: u16) -> Self {
37        match value {
38            60 => Self::Hour,
39            1440 => Self::Day,
40            4320 => Self::ThreeDays,
41            10080 => Self::Week,
42            value => Self::Unknown { value },
43        }
44    }
45}
46
47impl From<AutoArchiveDuration> for u16 {
48    fn from(value: AutoArchiveDuration) -> Self {
49        value.number()
50    }
51}
52
53impl From<AutoArchiveDuration> for Duration {
54    fn from(value: AutoArchiveDuration) -> Self {
55        Self::from_secs(u64::from(value.number()) * 60)
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::AutoArchiveDuration;
62    use serde_test::Token;
63    use std::time::Duration;
64
65    const MAP: &[(AutoArchiveDuration, u16)] = &[
66        (AutoArchiveDuration::Hour, 60),
67        (AutoArchiveDuration::Day, 1440),
68        (AutoArchiveDuration::ThreeDays, 4320),
69        (AutoArchiveDuration::Week, 10080),
70    ];
71
72    #[test]
73    fn variants() {
74        for (kind, num) in MAP {
75            serde_test::assert_tokens(kind, &[Token::U16(*num)]);
76            assert_eq!(*kind, AutoArchiveDuration::from(*num));
77            assert_eq!(*num, kind.number());
78        }
79    }
80
81    #[test]
82    fn unknown_conversion() {
83        assert_eq!(
84            AutoArchiveDuration::Unknown { value: 250 },
85            AutoArchiveDuration::from(250)
86        );
87    }
88
89    #[test]
90    fn std_time_duration() {
91        for (kind, _) in MAP {
92            let std_duration = Duration::from(*kind);
93            assert_eq!(u64::from(kind.number()) * 60, std_duration.as_secs());
94        }
95    }
96}