casper_client/types/
time_diff.rs

1use std::{
2    fmt::{self, Display, Formatter},
3    str::FromStr,
4    time::Duration,
5};
6
7use humantime::DurationError;
8use serde::{de::Error as SerdeError, Deserialize, Deserializer, Serialize, Serializer};
9
10use casper_types::bytesrepr::{self, ToBytes};
11
12/// A time difference between two timestamps.
13#[derive(Copy, Clone, Default, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
14pub struct TimeDiff(u64);
15
16impl TimeDiff {
17    /// Returns a new `TimeDiff` from the specified millisecond count.
18    pub const fn from_millis(millis: u64) -> Self {
19        TimeDiff(millis)
20    }
21}
22
23impl Display for TimeDiff {
24    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
25        write!(
26            formatter,
27            "{}",
28            humantime::format_duration(Duration::from_millis(self.0))
29        )
30    }
31}
32
33impl FromStr for TimeDiff {
34    type Err = DurationError;
35
36    fn from_str(value: &str) -> Result<Self, Self::Err> {
37        let inner = humantime::parse_duration(value)?.as_millis() as u64;
38        Ok(TimeDiff(inner))
39    }
40}
41
42impl Serialize for TimeDiff {
43    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
44        if serializer.is_human_readable() {
45            self.to_string().serialize(serializer)
46        } else {
47            self.0.serialize(serializer)
48        }
49    }
50}
51
52impl<'de> Deserialize<'de> for TimeDiff {
53    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
54        if deserializer.is_human_readable() {
55            let value_as_string = String::deserialize(deserializer)?;
56            TimeDiff::from_str(&value_as_string).map_err(SerdeError::custom)
57        } else {
58            let inner = u64::deserialize(deserializer)?;
59            Ok(TimeDiff(inner))
60        }
61    }
62}
63
64impl ToBytes for TimeDiff {
65    fn write_bytes(&self, buffer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
66        self.0.write_bytes(buffer)
67    }
68
69    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
70        self.0.to_bytes()
71    }
72
73    fn serialized_length(&self) -> usize {
74        self.0.serialized_length()
75    }
76}