Skip to main content

rsiot/executor/
instant.rs

1use std::time::Duration;
2
3use serde::{Deserialize, Serialize, de::Visitor};
4
5/// Монолитно увеличивающееся время
6///
7/// Обертка над `std::time::Instant`. Может работать на платформе WebAssembly. Реализованы трейты
8/// Default, Serialize и Deserialize
9#[derive(Clone, Debug, PartialEq)]
10pub struct Instant {
11    inst: web_time::Instant,
12}
13
14impl Instant {
15    /// Returns an instant corresponding to “now”.
16    pub fn now() -> Self {
17        Self {
18            inst: web_time::Instant::now(),
19        }
20    }
21
22    /// Returns the amount of time elapsed from another instant to this one, or zero duration if
23    /// that instant is later than this one.
24    pub fn duration_since(&self, earlier: Self) -> Duration {
25        self.inst.duration_since(earlier.inst)
26    }
27
28    /// Returns the amount of time elapsed since this instant.
29    pub fn elapsed(&self) -> Duration {
30        self.inst.elapsed()
31    }
32}
33
34impl Default for Instant {
35    fn default() -> Self {
36        Self {
37            inst: web_time::Instant::now(),
38        }
39    }
40}
41
42impl Serialize for Instant {
43    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
44    where
45        S: serde::Serializer,
46    {
47        serializer.serialize_u128(self.inst.elapsed().as_millis())
48    }
49}
50
51struct InstantVisitor;
52
53impl Visitor<'_> for InstantVisitor {
54    type Value = Instant;
55
56    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
57        formatter.write_str("an integer for TimeInstant")
58    }
59
60    fn visit_u128<E>(self, _v: u128) -> Result<Self::Value, E>
61    where
62        E: serde::de::Error,
63    {
64        Ok(Instant::now())
65    }
66}
67
68impl<'de> Deserialize<'de> for Instant {
69    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
70    where
71        D: serde::Deserializer<'de>,
72    {
73        deserializer.deserialize_u128(InstantVisitor)
74    }
75}