@@ -36,34 +36,15 @@ pub enum Event<'a> {
36
36
DownloadDataReceived ( & ' a [ u8 ] ) ,
37
37
}
38
38
39
- fn download_with_backend (
39
+ async fn download_with_backend (
40
40
backend : Backend ,
41
41
url : & Url ,
42
42
resume_from : u64 ,
43
43
callback : & dyn Fn ( Event < ' _ > ) -> Result < ( ) > ,
44
44
) -> Result < ( ) > {
45
45
match backend {
46
46
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 ,
67
48
}
68
49
}
69
50
@@ -131,17 +112,43 @@ pub fn download_to_path_with_backend(
131
112
132
113
let file = RefCell :: new ( file) ;
133
114
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
+ } )
139
131
}
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
+ ) )
143
150
}
144
- } ) ?;
151
+ } ?;
145
152
146
153
file. borrow_mut ( )
147
154
. sync_data ( )
0 commit comments