Skip to content

Commit c11f252

Browse files
committed
Make download_with_backend async
1 parent 7c549e0 commit c11f252

File tree

1 file changed

+37
-30
lines changed

1 file changed

+37
-30
lines changed

download/src/lib.rs

Lines changed: 37 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -36,34 +36,15 @@ pub enum Event<'a> {
3636
DownloadDataReceived(&'a [u8]),
3737
}
3838

39-
fn download_with_backend(
39+
async fn download_with_backend(
4040
backend: Backend,
4141
url: &Url,
4242
resume_from: u64,
4343
callback: &dyn Fn(Event<'_>) -> Result<()>,
4444
) -> Result<()> {
4545
match backend {
4646
Backend::Curl => curl::download(url, resume_from, callback),
47-
Backend::Reqwest(tls) => {
48-
// reqwest is async; this function is sync.
49-
match Handle::try_current() {
50-
Ok(current) => {
51-
// hide the asyncness for now.
52-
task::block_in_place(|| {
53-
current.block_on(reqwest_be::download(url, resume_from, callback, tls))
54-
})
55-
}
56-
Err(_) => {
57-
// Make a runtime to hide the asyncness.
58-
tokio::runtime::Runtime::new()?.block_on(reqwest_be::download(
59-
url,
60-
resume_from,
61-
callback,
62-
tls,
63-
))
64-
}
65-
}
66-
}
47+
Backend::Reqwest(tls) => reqwest_be::download(url, resume_from, callback, tls).await,
6748
}
6849
}
6950

@@ -131,17 +112,43 @@ pub fn download_to_path_with_backend(
131112

132113
let file = RefCell::new(file);
133114

134-
download_with_backend(backend, url, resume_from, &|event| {
135-
if let Event::DownloadDataReceived(data) = event {
136-
file.borrow_mut()
137-
.write_all(data)
138-
.context("unable to write download to disk")?;
115+
match Handle::try_current() {
116+
Ok(current) => {
117+
// hide the asyncness for now.
118+
task::block_in_place(|| {
119+
current.block_on(download_with_backend(backend, url, resume_from, &|event| {
120+
if let Event::DownloadDataReceived(data) = event {
121+
file.borrow_mut()
122+
.write_all(data)
123+
.context("unable to write download to disk")?;
124+
}
125+
match callback {
126+
Some(cb) => cb(event),
127+
None => Ok(()),
128+
}
129+
}))
130+
})
139131
}
140-
match callback {
141-
Some(cb) => cb(event),
142-
None => Ok(()),
132+
Err(_) => {
133+
// Make a runtime to hide the asyncness.
134+
tokio::runtime::Runtime::new()?.block_on(download_with_backend(
135+
backend,
136+
url,
137+
resume_from,
138+
&|event| {
139+
if let Event::DownloadDataReceived(data) = event {
140+
file.borrow_mut()
141+
.write_all(data)
142+
.context("unable to write download to disk")?;
143+
}
144+
match callback {
145+
Some(cb) => cb(event),
146+
None => Ok(()),
147+
}
148+
},
149+
))
143150
}
144-
})?;
151+
}?;
145152

146153
file.borrow_mut()
147154
.sync_data()

0 commit comments

Comments
 (0)