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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use alloc::string::ToString;
use core::fmt;

use serde::{
	de::{
		self,
		Visitor,
	},
	Deserialize,
	Serialize,
	Serializer,
};

use crate::{
	serde_impl::de::Deserializer,
	Duration,
};

impl Serialize for Duration {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		let s = self.format_exact().to_string();
		serializer.serialize_str(&s)
	}
}

struct DurationVisitor;

impl<'de> Visitor<'de> for DurationVisitor {
	type Value = Duration;

	fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.write_str("a non-negative integer or a string describing a duration")
	}

	fn visit_u8<E>(self, n: u8) -> Result<Duration, E>
	where
		E: de::Error,
	{
		Ok(Duration::from_millis(n as u128))
	}

	fn visit_u16<E>(self, n: u16) -> Result<Duration, E>
	where
		E: de::Error,
	{
		Ok(Duration::from_millis(n as u128))
	}

	fn visit_u32<E>(self, n: u32) -> Result<Duration, E>
	where
		E: de::Error,
	{
		Ok(Duration::from_millis(n as u128))
	}

	fn visit_u64<E>(self, n: u64) -> Result<Duration, E>
	where
		E: de::Error,
	{
		Ok(Duration::from_millis(n as u128))
	}

	fn visit_u128<E>(self, n: u128) -> Result<Duration, E>
	where
		E: de::Error,
	{
		Ok(Duration::from_millis(n))
	}

	fn visit_str<E>(self, s: &str) -> Result<Duration, E>
	where
		E: de::Error,
	{
		crate::parse(s).map_err(|e| E::custom(e.to_string()))
	}
}

impl<'de> Deserialize<'de> for Duration {
	fn deserialize<D>(deserializer: D) -> Result<Duration, D::Error>
	where
		D: Deserializer<'de>,
	{
		deserializer.deserialize_str(DurationVisitor)
	}
}