coder/models/
duration.rs

1use serde::{Deserialize, Serialize};
2use serde::{Deserializer, Serializer};
3
4/// Duration is a wrapper around chrono::Duration that Serializes into and Deserializes from
5/// millisecond precision integers.
6#[derive(Debug, Clone, PartialEq)]
7pub struct Duration(chrono::Duration);
8
9// Allow Duration to be used as a chrono::Duration.
10impl std::ops::Deref for Duration {
11    type Target = chrono::Duration;
12
13    fn deref(&self) -> &Self::Target {
14        &self.0
15    }
16}
17
18impl<'de> Deserialize<'de> for Duration {
19    fn deserialize<D>(deserializer: D) -> Result<Duration, D::Error>
20    where
21        D: Deserializer<'de>,
22    {
23        let u = i64::deserialize(deserializer)?;
24        Ok(Duration(chrono::Duration::milliseconds(u)))
25    }
26}
27
28impl Serialize for Duration {
29    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
30    where
31        S: Serializer,
32    {
33        serializer.serialize_i64(self.0.num_milliseconds())
34    }
35}
36
37#[cfg(test)]
38mod test {
39    use super::Duration;
40    use serde_json;
41
42    #[test]
43    fn test_serialize_duration() {
44        let ms = 86400000i64;
45        let d = Duration(chrono::Duration::milliseconds(ms));
46        assert_eq!(serde_json::to_string(&d).unwrap(), ms.to_string());
47    }
48
49    #[test]
50    fn test_deserialize_duration() {
51        let ms = 86400000i64;
52        let d: Duration = serde_json::from_str(&ms.to_string()).unwrap();
53        assert_eq!(d.num_milliseconds(), ms);
54    }
55}