Last active
October 14, 2020 19:09
-
-
Save ppamorim/7b1b78e8954f8cf0b4c0e620c4674f44 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use bytes::Bytes; | |
use std::pin::Pin; | |
use std::task::{Context, Poll}; | |
use std::io::BufReader; | |
use std::io::Read; | |
use futures_util::ready; | |
use futures_core::Future; | |
struct StreamBody { | |
reader: BufReader<File>, | |
buffer: Vec<u8>, | |
} | |
impl StreamBody { | |
fn new(file: File, chunk_size: usize) -> Self { | |
let mut reader = BufReader::new(file); | |
let mut buffer = vec![0u8; chunk_size]; | |
StreamBody { | |
reader, | |
buffer, | |
} | |
} | |
} | |
impl futures_core::stream::Stream for StreamBody { | |
type Item = Result<Bytes, ResponseError>; | |
fn poll_next( | |
mut self: Pin<&mut Self>, | |
cx: &mut Context<'_>, | |
) -> Poll<Option<Self::Item>> { | |
match self.reader.read(&mut self.buffer) { | |
Ok(count) => { | |
if count > 0 { | |
Poll::Ready(Some(Ok(Bytes::copy_from_slice(&self.buffer[..count])))) | |
} else { | |
Poll::Ready(None) | |
} | |
}, | |
Err(e) => Poll::Ready(None) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment