Debian Codegraph @

src/exec/use_pty/pipe/ring_buffer.rs

raw symbols SCIP
1 use std::io::{self, IoSlice, IoSliceMut, Read, Write};
2
3 pub(super) struct RingBuffer {
4 storage: Box<[u8; Self::LEN]>,
5 // The start index of the non-empty section of the buffer.
6 start: usize,
7 // The length of the non-empty section of the buffer.
8 len: usize,
9 }
10
11 impl RingBuffer {
12 /// The size of the internal storage of the ring buffer.
13 pub(super) const LEN: usize = 8 * 1024;
14
15 /// Create a new, empty buffer.
16 pub(super) fn new() -> Self {
17 Self {
18 storage: Box::new([0; Self::LEN]),
19 start: 0,
20 len: 0,
21 }
22 }
23
24 pub(super) fn is_full(&self) -> bool {
25 self.len == self.storage.len()
26 }
27
28 pub(super) fn insert<R: Read>(&mut self, read: &mut R) -> io::Result<usize> {
29 let inserted_len = if self.is_empty() {
30 // Case 1.1. The buffer is empty, meaning that there are two unfilled slices in
31 // `storage`:`start..` and `..start`.
32 let (second_slice, first_slice) = self.storage.split_at_mut(self.start);
33 read.read_vectored(&mut [first_slice, second_slice].map(IoSliceMut::new))?
34 } else {
35 let &mut Self { start, len, .. } = self;
36 let end = start + len;
37 if end >= self.storage.len() {
38 // Case 1.2. The buffer is not empty and the filled section wraps around `storage`.
39 // Meaning that there is only one unfilled slice in `storage`: `end..start`.
40 let end = end % self.storage.len();
41 read.read(&mut self.storage[end..start])?
42 } else {
43 // Case 1.3. The buffer is not empty and the filled section is a contiguous slice
44 // of `storage`. Meaning that there are two unfilled slices in `storage`: `..start`
45 // and `end..`.
46 let (mid, first_slice) = self.storage.split_at_mut(end);
47 let second_slice = &mut mid[..start];
48 read.read_vectored(&mut [first_slice, second_slice].map(IoSliceMut::new))?
49 }
50 };
51
52 self.len += inserted_len;
53
54 debug_assert!(self.start < Self::LEN);
55 debug_assert!(self.len <= Self::LEN);
56
57 Ok(inserted_len)
58 }
59
60 pub(super) fn is_empty(&self) -> bool {
61 self.len == 0
62 }
63
64 pub(super) fn remove<W: Write>(&mut self, write: &mut W) -> io::Result<usize> {
65 let removed_len = if self.is_full() {
66 // Case 2.1. The buffer is full, meaning that there are two filled slices in `storage`:
67 // `start..` and `..start`.
68 let (second_slice, first_slice) = self.storage.split_at(self.start);
69 write.write_vectored(&[first_slice, second_slice].map(IoSlice::new))?
70 } else {
71 let end = self.start + self.len;
72 if end >= self.storage.len() {
73 // Case 2.2. The buffer is not full and the filled section wraps around `storage`.
74 // Meaning that there are two non-empty slices in `storage`: `start..` and `..end`.
75 let end = end % self.storage.len();
76 let first_slice = &self.storage[self.start..];
77 let second_slice = &self.storage[..end];
78 write.write_vectored(&[first_slice, second_slice].map(IoSlice::new))?
79 } else {
80 // Case 2.3. The buffer is not full and the filled section is a contiguous slice
81 // of `storage.` Meaning that there is only one filled slice in `storage`:
82 // `start..end`.
83 write.write(&self.storage[self.start..end])?
84 }
85 };
86
87 self.start += removed_len;
88 self.start %= Self::LEN;
89
90 self.len -= removed_len;
91
92 debug_assert!(self.start < Self::LEN);
93 debug_assert!(self.len <= Self::LEN);
94
95 Ok(removed_len)
96 }
97 }
98
99 #[cfg(test)]
100 mod tests {
101 use super::RingBuffer;
102
103 #[test]
104 fn empty_buffer_is_empty() {
105 let buf = RingBuffer::new();
106
107 assert!(buf.is_empty());
108 }
109
110 #[test]
111 fn full_buffer_is_full() {
112 let mut buf = RingBuffer::new();
113
114 let inserted_len = buf.insert(&mut [0x45; RingBuffer::LEN].as_slice()).unwrap();
115 assert_eq!(inserted_len, RingBuffer::LEN);
116
117 assert!(buf.is_full());
118 }
119
120 #[test]
121 fn buffer_is_fifo() {
122 let mut buf = RingBuffer::new();
123
124 let expected = (0..=u8::MAX).collect::<Vec<u8>>();
125 let inserted_len = buf.insert(&mut expected.as_slice()).unwrap();
126 assert_eq!(inserted_len, expected.len());
127
128 let mut found = vec![];
129 let removed_len = buf.remove(&mut found).unwrap();
130 assert_eq!(removed_len, expected.len());
131
132 assert_eq!(expected, found);
133 }
134
135 #[test]
136 fn insert_into_empty_buffer_with_offset() {
137 const HALF_LEN: usize = RingBuffer::LEN / 2;
138 let mut buf = RingBuffer::new();
139
140 // This should leave the buffer empty but with the start field pointing to the middle of
141 // the buffer.
142 // ┌───────────────────┐
143 // │ │
144 // └───────────────────┘
145 // ▲
146 // │
147 // start
148 buf.insert(&mut [0u8; HALF_LEN].as_slice()).unwrap();
149 buf.remove(&mut vec![]).unwrap();
150
151 assert_eq!(buf.start, HALF_LEN);
152 assert_eq!(buf.len, 0);
153
154 // Then we fill the first half of the buffer with ones and the second one with twos in a
155 // single insertion. This tests case 1.1.
156 // ┌─────────┬─────────┐
157 // │ 2 │ 1 │
158 // └─────────┴─────────┘
159 // ▲
160 // │
161 // start
162 let mut expected = vec![1; HALF_LEN];
163 expected.extend_from_slice(&[2; HALF_LEN]);
164 buf.insert(&mut expected.as_slice()).unwrap();
165
166 assert_eq!(buf.start, HALF_LEN);
167 assert_eq!(buf.len, RingBuffer::LEN);
168
169 // When we remove all the elements of the buffer we should find them in the same order we
170 // inserted them. This tests case 2.1.
171 let mut found = vec![];
172 let removed_len = buf.remove(&mut found).unwrap();
173 assert_eq!(removed_len, expected.len());
174
175 assert_eq!(expected, found);
176
177 assert_eq!(buf.start, HALF_LEN);
178 assert_eq!(buf.len, 0);
179 }
180
181 #[test]
182 fn insert_into_non_empty_wrapping_buffer() {
183 const QUARTER_LEN: usize = RingBuffer::LEN / 4;
184 let mut buf = RingBuffer::new();
185
186 // This should leave the buffer empty but with the start field pointing to the middle of
187 // the buffer.
188 // ┌───────────────────────┐
189 // │ │
190 // └───────────────────────┘
191 // ▲
192 // │
193 // start
194 buf.insert(&mut [0; 2 * QUARTER_LEN].as_slice()).unwrap();
195 buf.remove(&mut vec![]).unwrap();
196
197 assert_eq!(buf.start, 2 * QUARTER_LEN);
198 assert_eq!(buf.len, 0);
199
200 // Then we fill one quarter of the buffer with ones. This gives us a non-empty buffer whose
201 // empty section is not contiguous.
202 // ┌───────────┬─────┬─────┐
203 // │ │ 1 │ │
204 // └───────────┴─────┴─────┘
205 // ▲
206 // │
207 // start
208 let mut expected = vec![1; QUARTER_LEN];
209 buf.insert(&mut expected.as_slice()).unwrap();
210
211 assert_eq!(buf.start, 2 * QUARTER_LEN);
212 assert_eq!(buf.len, QUARTER_LEN);
213
214 // Then we fill one quarter of the buffer with twos and another quarter of the buffer with
215 // threes in a single insertion. This tests case 1.2.
216 // ┌─────┬─────┬─────┬─────┐
217 // │ 3 │ │ 1 │ 2 │
218 // └─────┴─────┴─────┴─────┘
219 // ▲
220 // │
221 // start
222 let mut second_half = vec![2; QUARTER_LEN];
223 second_half.extend_from_slice(&[3; QUARTER_LEN]);
224 buf.insert(&mut second_half.as_slice()).unwrap();
225
226 expected.extend(second_half);
227
228 assert_eq!(buf.start, 2 * QUARTER_LEN);
229 assert_eq!(buf.len, 3 * QUARTER_LEN);
230
231 // When we remove all the elements of the buffer we should find them in the same order we
232 // inserted them. This tests case 2.2.
233 let mut found = vec![];
234 let removed_len = buf.remove(&mut found).unwrap();
235 assert_eq!(removed_len, expected.len());
236
237 assert_eq!(expected, found);
238
239 assert_eq!(buf.start, QUARTER_LEN);
240 assert_eq!(buf.len, 0);
241 }
242
243 #[test]
244 fn insert_into_non_empty_non_wrapping_buffer() {
245 const QUARTER_LEN: usize = RingBuffer::LEN / 4;
246 let mut buf = RingBuffer::new();
247
248 // We fill one quarter of the buffer with ones. This gives us a non-empty buffer whose
249 // empty section is contiguous.
250 // ┌─────┬────────────────┐
251 // │ 1 │ │
252 // └─────┴────────────────┘
253 // ▲
254 // │
255 // └ start
256 let mut expected = vec![1; QUARTER_LEN];
257 buf.insert(&mut expected.as_slice()).unwrap();
258
259 assert_eq!(buf.start, 0);
260 assert_eq!(buf.len, QUARTER_LEN);
261
262 // Then we fill one quarter of the buffer with twos. This tests case 1.3.
263 // ┌─────┬─────┬──────────┐
264 // │ 1 │ 2 │ │
265 // └─────┴─────┴──────────┘
266 // ▲
267 // │
268 // └ start
269 let second_half = vec![2; QUARTER_LEN];
270 buf.insert(&mut second_half.as_slice()).unwrap();
271
272 expected.extend(second_half);
273
274 assert_eq!(buf.start, 0);
275 assert_eq!(buf.len, 2 * QUARTER_LEN);
276
277 // When we remove all the elements of the buffer we should find them in the same order we
278 // inserted them. This tests case 2.3.
279 let mut found = vec![];
280 let removed_len = buf.remove(&mut found).unwrap();
281 assert_eq!(removed_len, expected.len());
282
283 assert_eq!(expected, found);
284
285 assert_eq!(buf.start, 2 * QUARTER_LEN);
286 assert_eq!(buf.len, 0);
287 }
288 }