-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathring_buffer.rs
More file actions
288 lines (236 loc) · 10.6 KB
/
ring_buffer.rs
File metadata and controls
288 lines (236 loc) · 10.6 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use std::io::{self, IoSlice, IoSliceMut, Read, Write};
pub(super) struct RingBuffer {
storage: Box<[u8; Self::LEN]>,
// The start index of the non-empty section of the buffer.
start: usize,
// The length of the non-empty section of the buffer.
len: usize,
}
impl RingBuffer {
/// The size of the internal storage of the ring buffer.
pub(super) const LEN: usize = 8 * 1024;
/// Create a new, empty buffer.
pub(super) fn new() -> Self {
Self {
storage: Box::new([0; Self::LEN]),
start: 0,
len: 0,
}
}
pub(super) fn is_full(&self) -> bool {
self.len == self.storage.len()
}
pub(super) fn insert<R: Read>(&mut self, read: &mut R) -> io::Result<usize> {
let inserted_len = if self.is_empty() {
// Case 1.1. The buffer is empty, meaning that there are two unfilled slices in
// `storage`:`start..` and `..start`.
let (second_slice, first_slice) = self.storage.split_at_mut(self.start);
read.read_vectored(&mut [first_slice, second_slice].map(IoSliceMut::new))?
} else {
let &mut Self { start, len, .. } = self;
let end = start + len;
if end >= self.storage.len() {
// Case 1.2. The buffer is not empty and the filled section wraps around `storage`.
// Meaning that there is only one unfilled slice in `storage`: `end..start`.
let end = end % self.storage.len();
read.read(&mut self.storage[end..start])?
} else {
// Case 1.3. The buffer is not empty and the filled section is a contiguous slice
// of `storage`. Meaning that there are two unfilled slices in `storage`: `..start`
// and `end..`.
let (mid, first_slice) = self.storage.split_at_mut(end);
let second_slice = &mut mid[..start];
read.read_vectored(&mut [first_slice, second_slice].map(IoSliceMut::new))?
}
};
self.len += inserted_len;
debug_assert!(self.start < Self::LEN);
debug_assert!(self.len <= Self::LEN);
Ok(inserted_len)
}
pub(super) fn is_empty(&self) -> bool {
self.len == 0
}
pub(super) fn remove<W: Write>(&mut self, write: &mut W) -> io::Result<usize> {
let removed_len = if self.is_full() {
// Case 2.1. The buffer is full, meaning that there are two filled slices in `storage`:
// `start..` and `..start`.
let (second_slice, first_slice) = self.storage.split_at(self.start);
write.write_vectored(&[first_slice, second_slice].map(IoSlice::new))?
} else {
let end = self.start + self.len;
if end >= self.storage.len() {
// Case 2.2. The buffer is not full and the filled section wraps around `storage`.
// Meaning that there are two non-empty slices in `storage`: `start..` and `..end`.
let end = end % self.storage.len();
let first_slice = &self.storage[self.start..];
let second_slice = &self.storage[..end];
write.write_vectored(&[first_slice, second_slice].map(IoSlice::new))?
} else {
// Case 2.3. The buffer is not full and the filled section is a contiguous slice
// of `storage.` Meaning that there is only one filled slice in `storage`:
// `start..end`.
write.write(&self.storage[self.start..end])?
}
};
self.start += removed_len;
self.start %= Self::LEN;
self.len -= removed_len;
debug_assert!(self.start < Self::LEN);
debug_assert!(self.len <= Self::LEN);
Ok(removed_len)
}
}
#[cfg(test)]
mod tests {
use super::RingBuffer;
#[test]
fn empty_buffer_is_empty() {
let buf = RingBuffer::new();
assert!(buf.is_empty());
}
#[test]
fn full_buffer_is_full() {
let mut buf = RingBuffer::new();
let inserted_len = buf.insert(&mut [0x45; RingBuffer::LEN].as_slice()).unwrap();
assert_eq!(inserted_len, RingBuffer::LEN);
assert!(buf.is_full());
}
#[test]
fn buffer_is_fifo() {
let mut buf = RingBuffer::new();
let expected = (0..=u8::MAX).collect::<Vec<u8>>();
let inserted_len = buf.insert(&mut expected.as_slice()).unwrap();
assert_eq!(inserted_len, expected.len());
let mut found = vec![];
let removed_len = buf.remove(&mut found).unwrap();
assert_eq!(removed_len, expected.len());
assert_eq!(expected, found);
}
#[test]
fn insert_into_empty_buffer_with_offset() {
const HALF_LEN: usize = RingBuffer::LEN / 2;
let mut buf = RingBuffer::new();
// This should leave the buffer empty but with the start field pointing to the middle of
// the buffer.
// ┌───────────────────┐
// │ │
// └───────────────────┘
// ▲
// │
// start
buf.insert(&mut [0u8; HALF_LEN].as_slice()).unwrap();
buf.remove(&mut vec![]).unwrap();
assert_eq!(buf.start, HALF_LEN);
assert_eq!(buf.len, 0);
// Then we fill the first half of the buffer with ones and the second one with twos in a
// single insertion. This tests case 1.1.
// ┌─────────┬─────────┐
// │ 2 │ 1 │
// └─────────┴─────────┘
// ▲
// │
// start
let mut expected = vec![1; HALF_LEN];
expected.extend_from_slice(&[2; HALF_LEN]);
buf.insert(&mut expected.as_slice()).unwrap();
assert_eq!(buf.start, HALF_LEN);
assert_eq!(buf.len, RingBuffer::LEN);
// When we remove all the elements of the buffer we should find them in the same order we
// inserted them. This tests case 2.1.
let mut found = vec![];
let removed_len = buf.remove(&mut found).unwrap();
assert_eq!(removed_len, expected.len());
assert_eq!(expected, found);
assert_eq!(buf.start, HALF_LEN);
assert_eq!(buf.len, 0);
}
#[test]
fn insert_into_non_empty_wrapping_buffer() {
const QUARTER_LEN: usize = RingBuffer::LEN / 4;
let mut buf = RingBuffer::new();
// This should leave the buffer empty but with the start field pointing to the middle of
// the buffer.
// ┌───────────────────────┐
// │ │
// └───────────────────────┘
// ▲
// │
// start
buf.insert(&mut [0; 2 * QUARTER_LEN].as_slice()).unwrap();
buf.remove(&mut vec![]).unwrap();
assert_eq!(buf.start, 2 * QUARTER_LEN);
assert_eq!(buf.len, 0);
// Then we fill one quarter of the buffer with ones. This gives us a non-empty buffer whose
// empty section is not contiguous.
// ┌───────────┬─────┬─────┐
// │ │ 1 │ │
// └───────────┴─────┴─────┘
// ▲
// │
// start
let mut expected = vec![1; QUARTER_LEN];
buf.insert(&mut expected.as_slice()).unwrap();
assert_eq!(buf.start, 2 * QUARTER_LEN);
assert_eq!(buf.len, QUARTER_LEN);
// Then we fill one quarter of the buffer with twos and another quarter of the buffer with
// threes in a single insertion. This tests case 1.2.
// ┌─────┬─────┬─────┬─────┐
// │ 3 │ │ 1 │ 2 │
// └─────┴─────┴─────┴─────┘
// ▲
// │
// start
let mut second_half = vec![2; QUARTER_LEN];
second_half.extend_from_slice(&[3; QUARTER_LEN]);
buf.insert(&mut second_half.as_slice()).unwrap();
expected.extend(second_half);
assert_eq!(buf.start, 2 * QUARTER_LEN);
assert_eq!(buf.len, 3 * QUARTER_LEN);
// When we remove all the elements of the buffer we should find them in the same order we
// inserted them. This tests case 2.2.
let mut found = vec![];
let removed_len = buf.remove(&mut found).unwrap();
assert_eq!(removed_len, expected.len());
assert_eq!(expected, found);
assert_eq!(buf.start, QUARTER_LEN);
assert_eq!(buf.len, 0);
}
#[test]
fn insert_into_non_empty_non_wrapping_buffer() {
const QUARTER_LEN: usize = RingBuffer::LEN / 4;
let mut buf = RingBuffer::new();
// We fill one quarter of the buffer with ones. This gives us a non-empty buffer whose
// empty section is contiguous.
// ┌─────┬────────────────┐
// │ 1 │ │
// └─────┴────────────────┘
// ▲
// │
// └ start
let mut expected = vec![1; QUARTER_LEN];
buf.insert(&mut expected.as_slice()).unwrap();
assert_eq!(buf.start, 0);
assert_eq!(buf.len, QUARTER_LEN);
// Then we fill one quarter of the buffer with twos. This tests case 1.3.
// ┌─────┬─────┬──────────┐
// │ 1 │ 2 │ │
// └─────┴─────┴──────────┘
// ▲
// │
// └ start
let second_half = vec![2; QUARTER_LEN];
buf.insert(&mut second_half.as_slice()).unwrap();
expected.extend(second_half);
assert_eq!(buf.start, 0);
assert_eq!(buf.len, 2 * QUARTER_LEN);
// When we remove all the elements of the buffer we should find them in the same order we
// inserted them. This tests case 2.3.
let mut found = vec![];
let removed_len = buf.remove(&mut found).unwrap();
assert_eq!(removed_len, expected.len());
assert_eq!(expected, found);
assert_eq!(buf.start, 2 * QUARTER_LEN);
assert_eq!(buf.len, 0);
}
}