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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//! Async stream adapter that replays leftover bytes.
//!
//! `RewindStream` emits any bytes buffered from a preamble read before
//! delegating reads and writes to the underlying stream.
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
/// A stream adapter that replays buffered bytes before reading
/// from the underlying stream.
pub struct RewindStream<S> {
/// Bytes already read with the preamble that must precede socket reads.
leftover: Vec<u8>,
/// Cursor into `leftover`; reset when the buffered prefix is exhausted.
pos: usize,
/// Underlying stream used after buffered bytes have been replayed.
inner: S,
}
impl<S> RewindStream<S> {
/// Create a new `RewindStream` that will yield `leftover` before
/// delegating to `inner`.
pub const fn new(leftover: Vec<u8>, inner: S) -> Self {
Self {
leftover,
pos: 0,
inner,
}
}
/// Return a reference to the underlying stream.
pub const fn inner(&self) -> &S { &self.inner }
/// Return a mutable reference to the underlying stream.
pub const fn inner_mut(&mut self) -> &mut S { &mut self.inner }
/// Consume the wrapper and return the underlying stream.
///
/// Note: any unread leftover bytes will be discarded.
pub fn into_inner(self) -> S { self.inner }
}
#[cfg(test)]
impl<S> RewindStream<S> {
pub(crate) fn set_pos_for_tests(&mut self, pos: usize) { self.pos = pos; }
pub(crate) fn pos_for_tests(&self) -> usize { self.pos }
pub(crate) fn leftover_len_for_tests(&self) -> usize { self.leftover.len() }
}
impl<S: AsyncRead + Unpin> AsyncRead for RewindStream<S> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
if self.pos != self.leftover.len() {
let remaining = self.leftover.len().saturating_sub(self.pos);
let to_copy = remaining.min(buf.remaining());
let start = self.pos;
let end = start + to_copy;
if let Some(slice) = self.leftover.get(start..end) {
buf.put_slice(slice);
} else {
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"rewind buffer slice out of bounds",
)));
}
self.pos += to_copy;
if self.pos < self.leftover.len() || to_copy > 0 {
return Poll::Ready(Ok(()));
}
}
if self.pos >= self.leftover.len() && !self.leftover.is_empty() {
self.leftover.clear();
self.pos = 0;
}
Pin::new(&mut self.inner).poll_read(cx, buf)
}
}
impl<S: AsyncWrite + Unpin> AsyncWrite for RewindStream<S> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
impl<S: Unpin> Unpin for RewindStream<S> {}
#[cfg(test)]
mod tests {
//! Coverage for rewind-buffer bounds and poll sequencing.
//!
//! Three `poll_read` mutants are equivalent and deliberately left
//! unannotated. Mutating the replay-completion guard's `<` to `<=` cannot
//! change behaviour because `pos == len` with `to_copy == 0` is
//! unreachable after a successful copy; the second disjunct already
//! covers the completing copy. Mutating its `>` to `>=` is equivalent
//! because `to_copy` is a `usize`, so `to_copy >= 0` always holds.
//! Mutating the cleanup guard's `&&` to `||` only clears an already empty
//! vector, because the cleanup guard is reached only with
//! `pos == len`.
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
use futures::task::noop_waker_ref;
use tokio::io::{AsyncRead, ReadBuf};
use super::*;
/// Inner stream that records how often `poll_read` reaches it.
///
/// The reader is always ready: it yields `data` until exhausted and then
/// reports end-of-file. Counting polls lets a test prove that
/// `RewindStream` did not fall through to the inner stream while replay
/// was still pending.
struct CountingReader {
data: &'static [u8],
polls: usize,
}
impl CountingReader {
const fn new(data: &'static [u8]) -> Self { Self { data, polls: 0 } }
}
impl AsyncRead for CountingReader {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
self.polls += 1;
Pin::new(&mut self.data).poll_read(cx, buf)
}
}
/// Poll `stream` once with a buffer of `capacity` bytes.
///
/// Returns the bytes delivered by that single poll. Panics when the poll
/// is not immediately ready with `Ok`, because these tests model an
/// always-ready inner reader driven by a no-op waker.
fn poll_once(stream: &mut RewindStream<CountingReader>, capacity: usize) -> Vec<u8> {
let waker = noop_waker_ref();
let mut cx = Context::from_waker(waker);
let mut buffer = vec![0_u8; capacity];
let mut read_buf = ReadBuf::new(&mut buffer);
match RewindStream::poll_read(Pin::new(stream), &mut cx, &mut read_buf) {
Poll::Ready(Ok(())) => read_buf.filled().to_vec(),
other => panic!("expected a ready Ok poll, got {other:?}"),
}
}
/// Expected observable state after a single poll.
#[derive(Clone, Copy)]
struct PollExpectation {
/// Bytes delivered by the poll.
bytes: &'static [u8],
/// Total number of times the inner stream has been polled.
inner_polls: usize,
/// Cursor into the leftover buffer.
pos: usize,
/// Number of bytes still held in the leftover buffer.
leftover_len: usize,
}
/// Poll `stream` once and assert the delivered bytes and replay state.
///
/// Grouping the expectations keeps each test focused on its scenario
/// while still checking every observable dimension of the replay state.
fn assert_poll(
stream: &mut RewindStream<CountingReader>,
capacity: usize,
expected: PollExpectation,
) {
assert_eq!(poll_once(stream, capacity).as_slice(), expected.bytes);
assert_eq!(stream.inner().polls, expected.inner_polls);
assert_eq!(stream.pos_for_tests(), expected.pos);
assert_eq!(stream.leftover_len_for_tests(), expected.leftover_len);
}
#[test]
fn poll_read_returns_error_for_invalid_leftover_slice_bounds() {
let mut stream = RewindStream::new(vec![1_u8, 2, 3], tokio::io::empty());
stream.set_pos_for_tests(stream.leftover_len_for_tests() + 1);
let waker = noop_waker_ref();
let mut cx = Context::from_waker(waker);
let mut buffer = [0_u8; 2];
let mut read_buf = ReadBuf::new(&mut buffer);
let mut pinned = Pin::new(&mut stream);
let result = RewindStream::poll_read(Pin::as_mut(&mut pinned), &mut cx, &mut read_buf);
match result {
Poll::Ready(Err(err)) => assert_eq!(
err.kind(),
io::ErrorKind::UnexpectedEof,
"err.kind() should equal io::ErrorKind::UnexpectedEof"
),
other => panic!("expected UnexpectedEof, got {other:?}"),
}
}
#[test]
fn poll_read_replays_leftover_across_split_reads() {
let mut stream = RewindStream::new(b"abcde".to_vec(), CountingReader::new(b"XYZ"));
// Successive small buffers split the leftover into `ab`, `c` and `de`
// without reaching the inner stream. Kills `||` -> `&&` on the
// replay-completion guard, and `>=` -> `<` and `!` deletion on the
// cleanup guard, each of which would either append inner bytes to the
// completing read or retain the cleared leftover.
assert_poll(
&mut stream,
2,
PollExpectation {
bytes: b"ab",
inner_polls: 0,
pos: 2,
leftover_len: 5,
},
);
assert_poll(
&mut stream,
1,
PollExpectation {
bytes: b"c",
inner_polls: 0,
pos: 3,
leftover_len: 5,
},
);
assert_poll(
&mut stream,
2,
PollExpectation {
bytes: b"de",
inner_polls: 0,
pos: 5,
leftover_len: 5,
},
);
// Replay is complete, so this poll clears it before reading the inner
// stream. A retained leftover or stale cursor fails here.
assert_poll(
&mut stream,
8,
PollExpectation {
bytes: b"XYZ",
inner_polls: 1,
pos: 0,
leftover_len: 0,
},
);
// The inner reader is now exhausted; a further poll reports EOF.
assert_poll(
&mut stream,
8,
PollExpectation {
bytes: b"",
inner_polls: 2,
pos: 0,
leftover_len: 0,
},
);
}
#[test]
fn poll_read_reports_completion_without_appending_inner_bytes() {
let mut stream = RewindStream::new(b"abc".to_vec(), CountingReader::new(b"XYZ"));
// A buffer larger than the leftover must deliver exactly the leftover.
// Kills `>` -> `==` and `||` -> `&&` on the replay-completion guard:
// both fall through when the copy exhausts the leftover, clearing it
// and polling the inner stream within the same read.
assert_poll(
&mut stream,
8,
PollExpectation {
bytes: b"abc",
inner_polls: 0,
pos: 3,
leftover_len: 3,
},
);
assert_poll(
&mut stream,
8,
PollExpectation {
bytes: b"XYZ",
inner_polls: 1,
pos: 0,
leftover_len: 0,
},
);
}
#[test]
fn poll_read_makes_no_progress_while_zero_capacity_replay_is_pending() {
let mut stream = RewindStream::new(b"abc".to_vec(), CountingReader::new(b"XYZ"));
// A zero-capacity poll cannot copy, so it must report readiness
// without touching the inner stream or the cursor. Kills `<` -> `==`
// and `<` -> `>` on the replay-completion guard, which would both fall
// through to the inner stream.
assert_poll(
&mut stream,
0,
PollExpectation {
bytes: b"",
inner_polls: 0,
pos: 0,
leftover_len: 3,
},
);
assert_poll(
&mut stream,
8,
PollExpectation {
bytes: b"abc",
inner_polls: 0,
pos: 3,
leftover_len: 3,
},
);
}
#[test]
fn poll_read_clears_replayed_leftover_before_polling_inner() {
let mut stream = RewindStream::new(b"abc".to_vec(), CountingReader::new(b"XYZ"));
assert_poll(
&mut stream,
3,
PollExpectation {
bytes: b"abc",
inner_polls: 0,
pos: 3,
leftover_len: 3,
},
);
// Replay is complete, so the next poll clears it before delegating.
// With no buffer space the inner read yields nothing, but it must be
// reached exactly once. Kills `>=` -> `<` and `!` deletion on the
// cleanup guard, which would retain the leftover and cursor.
assert_poll(
&mut stream,
0,
PollExpectation {
bytes: b"",
inner_polls: 1,
pos: 0,
leftover_len: 0,
},
);
assert_poll(
&mut stream,
8,
PollExpectation {
bytes: b"XYZ",
inner_polls: 2,
pos: 0,
leftover_len: 0,
},
);
}
}