dur/
serde_impl.rs

1use alloc::string::ToString;
2use core::fmt;
3
4use serde::{
5	de::{
6		self,
7		Visitor,
8	},
9	Deserialize,
10	Serialize,
11	Serializer,
12};
13
14use crate::{
15	serde_impl::de::Deserializer,
16	Duration,
17};
18
19impl Serialize for Duration {
20	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
21	where
22		S: Serializer,
23	{
24		let s = self.format_exact().to_string();
25		serializer.serialize_str(&s)
26	}
27}
28
29struct DurationVisitor;
30
31impl<'de> Visitor<'de> for DurationVisitor {
32	type Value = Duration;
33
34	fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
35		f.write_str("a non-negative integer or a string describing a duration")
36	}
37
38	fn visit_u8<E>(self, n: u8) -> Result<Duration, E>
39	where
40		E: de::Error,
41	{
42		Ok(Duration::from_millis(n as u128))
43	}
44
45	fn visit_u16<E>(self, n: u16) -> Result<Duration, E>
46	where
47		E: de::Error,
48	{
49		Ok(Duration::from_millis(n as u128))
50	}
51
52	fn visit_u32<E>(self, n: u32) -> Result<Duration, E>
53	where
54		E: de::Error,
55	{
56		Ok(Duration::from_millis(n as u128))
57	}
58
59	fn visit_u64<E>(self, n: u64) -> Result<Duration, E>
60	where
61		E: de::Error,
62	{
63		Ok(Duration::from_millis(n as u128))
64	}
65
66	fn visit_u128<E>(self, n: u128) -> Result<Duration, E>
67	where
68		E: de::Error,
69	{
70		Ok(Duration::from_millis(n))
71	}
72
73	fn visit_str<E>(self, s: &str) -> Result<Duration, E>
74	where
75		E: de::Error,
76	{
77		crate::parse(s).map_err(|e| E::custom(e.to_string()))
78	}
79}
80
81impl<'de> Deserialize<'de> for Duration {
82	fn deserialize<D>(deserializer: D) -> Result<Duration, D::Error>
83	where
84		D: Deserializer<'de>,
85	{
86		deserializer.deserialize_str(DurationVisitor)
87	}
88}