redux/action/
action_meta.rs

1use std::time::Duration;
2
3use crate::{SystemTime, Timestamp};
4
5use super::{ActionId, ActionWithMeta};
6
7pub type RecursionDepth = u32;
8
9/// Action with additional metadata like: id.
10#[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Clone)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct ActionMeta {
13    id: ActionId,
14    /// Previously applied action.
15    prev: ActionId,
16    /// Recursion depth of a given action.
17    depth: RecursionDepth,
18}
19
20impl ActionMeta {
21    pub const ZERO: Self = Self {
22        id: ActionId::ZERO,
23        prev: ActionId::ZERO,
24        depth: 0,
25    };
26
27    #[inline(always)]
28    pub(crate) fn new(id: ActionId, prev: ActionId, depth: RecursionDepth) -> Self {
29        Self { id, prev, depth }
30    }
31
32    #[inline(always)]
33    pub fn zero_custom(time: Timestamp) -> Self {
34        Self {
35            id: ActionId::new_unchecked(time.into()),
36            prev: ActionId::new_unchecked(time.into()),
37            depth: 0,
38        }
39    }
40
41    #[inline(always)]
42    pub fn id(&self) -> ActionId {
43        self.id
44    }
45
46    /// Recursion depth of a given action.
47    #[inline(always)]
48    pub fn depth(&self) -> RecursionDepth {
49        self.depth
50    }
51
52    /// Time of previously applied action.
53    #[inline(always)]
54    pub fn prev_time(&self) -> Timestamp {
55        self.prev.into()
56    }
57
58    #[inline(always)]
59    pub fn time(&self) -> Timestamp {
60        self.id.into()
61    }
62
63    #[inline(always)]
64    pub fn sys_time(&self) -> SystemTime {
65        SystemTime::UNIX_EPOCH + self.duration_since_epoch()
66    }
67
68    #[inline(always)]
69    pub fn time_as_nanos(&self) -> u64 {
70        self.id.into()
71    }
72
73    #[inline(always)]
74    pub fn duration_since_epoch(&self) -> Duration {
75        Duration::from_nanos(self.time_as_nanos())
76    }
77
78    #[inline(always)]
79    pub fn duration_since(&self, other: &ActionMeta) -> Duration {
80        self.id.duration_since(other.id)
81    }
82
83    #[inline(always)]
84    pub fn with_action<T>(self, action: T) -> ActionWithMeta<T> {
85        ActionWithMeta { meta: self, action }
86    }
87}