Skip to content

Instantly share code, notes, and snippets.

@yaymukund
Last active September 7, 2018 08:23
Show Gist options
  • Save yaymukund/0eb3780ccb9423e2eab8801c6d4ec96b to your computer and use it in GitHub Desktop.
Save yaymukund/0eb3780ccb9423e2eab8801c6d4ec96b to your computer and use it in GitHub Desktop.
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