From 191fd6e981f83f6f3358c9089f2df4887ccfa04d Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Wed, 8 Jun 2022 20:11:01 +1000 Subject: [PATCH] Use `AsyncFileWriter` in `helpers::download` so that writing to file will not block the download. Signed-off-by: Jiahao XU --- src/helpers.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/helpers.rs b/src/helpers.rs index 55e7a8df..e37cf89e 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -7,6 +7,7 @@ use std::{ use bytes::Bytes; use cargo_toml::Manifest; use flate2::read::GzDecoder; +use futures_util::stream::StreamExt; use log::{debug, info}; use reqwest::Method; use serde::Serialize; @@ -56,13 +57,19 @@ pub async fn download>(url: &str, path: P) -> Result<(), Binstall err, })?; - let bytes = resp.bytes().await?; - let path = path.as_ref(); - debug!("Download OK, writing to file: '{}'", path.display()); + debug!("Downloading to file: '{}'", path.display()); - fs::create_dir_all(path.parent().unwrap())?; - fs::write(&path, bytes)?; + let mut bytes_stream = resp.bytes_stream(); + let writer = AsyncFileWriter::new(path)?; + + while let Some(res) = bytes_stream.next().await { + writer.write(res?).await; + } + + writer.done().await?; + + debug!("Download OK, written to file: '{}'", path.display()); Ok(()) }