aboutsummaryrefslogtreecommitdiff
path: root/src/chunked_bufreader.rs
blob: 02c2bb824a57161f81b5e4cf2669d5fb22160588 (plain)
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
use std::pin::Pin;

use async_std::prelude::*;
use async_std::io::BufReader;
use async_std::io::Read;
use futures::task::{Context, Poll};
use pin_project::pin_project;

const CHUNK_SIZE: usize = 4096;

#[pin_project]
pub struct ChunkedBufReader<T>
    where T: Read + Unpin {
    #[pin]
    reader: BufReader<T>,
}

impl<T> ChunkedBufReader<T>
    where T: Read + Unpin {
    pub fn new(reader: BufReader<T>) -> Self {
        Self {
            reader,
        }
    }
}

impl<T> Stream for ChunkedBufReader<T>
    where T: Read + Unpin {
    type Item = Vec<u8>;
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.project();
        // This is quite wasteful, but perfomance is fine and the only real optimization (other
        // than some zero-copy shenanigans) would be to not initialize this vec, with unsafe{}
        let mut chunk = vec![0; CHUNK_SIZE];
        match this.reader.poll_read(cx, &mut chunk[0..(CHUNK_SIZE - 1)]) {
            Poll::Ready(Ok(size)) => {
                if size == 0 {
                    Poll::Ready(None)
                } else {
                    chunk.truncate(size);
                    Poll::Ready(Some(chunk))
                }
            },
            Poll::Ready(Err(_)) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}