casper_node/components/block_synchronizer/block_builder/
latch.rs

1use datasize::DataSize;
2
3use tracing::warn;
4
5use casper_types::{TimeDiff, Timestamp};
6
7#[derive(Debug, Default, DataSize)]
8pub(super) struct Latch {
9    #[data_size(skip)]
10    latch: u8,
11    timestamp: Option<Timestamp>,
12}
13
14impl Latch {
15    pub(super) fn increment(&mut self, increment_by: u8) {
16        match self.latch.checked_add(increment_by) {
17            Some(val) => {
18                self.latch = val;
19                self.touch();
20            }
21            None => {
22                warn!("latch increment overflowed.");
23            }
24        }
25    }
26
27    pub(super) fn decrement(&mut self, decrement_by: u8) {
28        match self.latch.checked_sub(decrement_by) {
29            Some(val) => {
30                self.latch = val;
31            }
32            None => {
33                self.latch = 0;
34            }
35        }
36        self.touch();
37    }
38
39    pub(super) fn unlatch(&mut self) {
40        self.latch = 0;
41        self.timestamp = None;
42    }
43
44    pub(super) fn check_latch(&mut self, interval: TimeDiff, checked: Timestamp) -> bool {
45        match self.timestamp {
46            None => false,
47            Some(timestamp) => {
48                if checked > timestamp + interval {
49                    self.unlatch()
50                }
51                self.count() > 0
52            }
53        }
54    }
55
56    pub(super) fn count(&self) -> u8 {
57        self.latch
58    }
59
60    pub(super) fn touch(&mut self) {
61        self.timestamp = Some(Timestamp::now());
62    }
63}