summaryrefslogtreecommitdiffstats
path: root/src/serde_duration.rs
blob: 50076b055a3d43b7efc7f4c3aaebc7fffb396f97 (plain) (blame)
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
use serde::de::{ Visitor, Error, Deserializer };
use std::time::Duration;
use std::fmt;

pub fn deserialize_duration<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>
{
    struct DurationVisitor;

    impl<'de> Visitor<'de> for DurationVisitor {
        type Value = Duration;
    
        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            write!(f, "duration in secs")
        }
    
        fn visit_f32<E: Error> (self, v: f32) -> Result<Self::Value, E> {
            Ok(Duration::from_secs_f32(v))
        }
    
        fn visit_f64<E: Error> (self, v: f64) -> Result<Self::Value, E> {
            Ok(Duration::from_secs_f64(v))
        }
    }
    
    deserializer.deserialize_any(DurationVisitor)
}