Last active
September 7, 2018 08:23
-
-
Save yaymukund/0eb3780ccb9423e2eab8801c6d4ec96b to your computer and use it in GitHub Desktop.
This file contains 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 super::downloader::HttpClient; | |
use hyper; | |
use hyper::rt::{Future, Stream}; | |
use std::error::Error; | |
use std::io::{Error as IOError, Read}; | |
use std::sync::{atomic, mpsc, Arc}; | |
pub struct Download { | |
uri: String, | |
body: mpsc::Receiver<hyper::Chunk>, | |
downloaded_bytes: Arc<atomic::AtomicUsize>, | |
buffer: Vec<u8>, | |
} | |
fn log_error(err: impl Error) { | |
println!("Error: {}", err.to_string()); | |
} | |
impl Download { | |
pub fn fetch(uri: &str, client: &HttpClient) -> (Download, impl Future<Item = (), Error = ()>) { | |
let (sender, receiver) = mpsc::channel(); | |
let download = Download { | |
uri: uri.to_owned(), | |
body: receiver, | |
downloaded_bytes: Arc::new(atomic::AtomicUsize::new(0)), | |
buffer: Vec::new(), | |
}; | |
let uri = download.uri.parse().unwrap(); | |
let future = client.get(uri).map_err(log_error).and_then(move |res| { | |
res.into_body() | |
.map_err(log_error) | |
.for_each(move |chunk| sender.send(chunk).map_err(log_error)) | |
}); | |
(download, future) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment