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
use crate::io::cache::CacheReader;
use crate::io::AsyncCacheRead;

use std::borrow::BorrowMut;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io;
use tokio::io::{AsyncRead, ReadBuf};

impl<R: AsyncRead> AsyncRead for CacheReader<R> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<Result<(), io::Error>> {
        let mut this = self.project();
        if !this.cache.is_empty() {
            let remaining = usize::min(buf.remaining(), this.cache.len());
            buf.put_slice(&this.cache[..remaining]);
            this.cache.drain(..remaining);
            return Poll::Ready(Ok(()));
        }
        this.reader.poll_read(cx, buf)
    }
}

impl<R: AsyncRead> AsyncCacheRead for CacheReader<R> {
    fn poll_reader(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        self.project().reader.poll_read(cx, buf)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        self.project().borrow_mut().cache.drain(..amt);
    }

    fn restore(self: Pin<&mut Self>, data: &[u8]) {
        self.project().borrow_mut().cache.extend_from_slice(data)
    }
}