1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
use std::collections::VecDeque;
use std::convert::Infallible;
use std::sync::Arc;
use crate::CoordNum;
use crate::LogEntry;
use crate::RoundNum;
pub trait Buffer: Send + 'static {
type RoundNum: RoundNum;
type CoordNum: CoordNum;
type Entry: LogEntry;
type Error: std::error::Error + Send + Sync + 'static;
fn insert(
&mut self,
round_num: Self::RoundNum,
coord_num: Self::CoordNum,
entry: Arc<Self::Entry>,
);
#[allow(clippy::type_complexity)]
fn get(
&self,
round_num: Self::RoundNum,
) -> Result<Option<(Self::CoordNum, Arc<Self::Entry>)>, Self::Error>;
}
pub struct InMemoryBuffer<R, C, E: LogEntry> {
capacity: usize,
buffer: VecDeque<(R, C, Arc<E>)>,
}
impl<R, C, E: LogEntry> InMemoryBuffer<R, C, E> {
pub fn new(capacity: usize) -> Self {
assert!(capacity > 0);
Self {
capacity,
buffer: VecDeque::new(),
}
}
}
impl<R, C, E> Buffer for InMemoryBuffer<R, C, E>
where
R: RoundNum,
C: CoordNum,
E: LogEntry,
{
type RoundNum = R;
type CoordNum = C;
type Entry = E;
type Error = Infallible;
fn insert(
&mut self,
round_num: Self::RoundNum,
coord_num: Self::CoordNum,
entry: Arc<Self::Entry>,
) {
if self.capacity <= self.buffer.len() {
self.buffer.pop_front();
}
self.buffer.push_back((round_num, coord_num, entry));
}
#[allow(clippy::type_complexity)]
fn get(
&self,
round_num: Self::RoundNum,
) -> Result<Option<(Self::CoordNum, Arc<Self::Entry>)>, Self::Error> {
if let Some((r, _, _)) = self.buffer.get(0) {
if round_num >= *r {
if let Some(delta) = crate::util::try_usize_delta(round_num, *r) {
if let Some((r, c, e)) = self.buffer.get(delta) {
if *r == round_num {
return Ok(Some((*c, Arc::clone(e))));
}
}
}
}
}
Ok(self
.buffer
.iter()
.find(|(r, _, _)| *r == round_num)
.map(|(_, c, e)| (*c, Arc::clone(e))))
}
}