1use std::cell::{Cell, Ref, RefCell};
2use std::cmp::Ordering;
3use std::collections::{HashMap, HashSet};
4use std::fmt;
5use std::hash;
6use std::mem;
7use std::path::{Path, PathBuf};
8use std::time::{Duration, Instant};
9
10use bytesize::ByteSize;
11use curl::easy::{Easy, HttpVersion};
12use curl::multi::{EasyHandle, Multi};
13use failure::ResultExt;
14use lazycell::LazyCell;
15use log::{debug, warn};
16use semver::Version;
17use serde::ser;
18use serde::Serialize;
19
20use crate::core::interning::InternedString;
21use crate::core::source::MaybePackage;
22use crate::core::{Dependency, Manifest, PackageId, SourceId, Target};
23use crate::core::{FeatureMap, SourceMap, Summary};
24use crate::ops;
25use crate::util::errors::{CargoResult, CargoResultExt, HttpNot200};
26use crate::util::network::Retry;
27use crate::util::{self, internal, lev_distance, Config, Progress, ProgressStyle};
28
29#[derive(Clone)]
34pub struct Package {
35 manifest: Manifest,
37 manifest_path: PathBuf,
39}
40
41impl Ord for Package {
42 fn cmp(&self, other: &Package) -> Ordering {
43 self.package_id().cmp(&other.package_id())
44 }
45}
46
47impl PartialOrd for Package {
48 fn partial_cmp(&self, other: &Package) -> Option<Ordering> {
49 Some(self.cmp(other))
50 }
51}
52
53#[derive(Serialize)]
55struct SerializedPackage<'a> {
56 name: &'a str,
57 version: &'a Version,
58 id: PackageId,
59 license: Option<&'a str>,
60 license_file: Option<&'a str>,
61 description: Option<&'a str>,
62 source: SourceId,
63 dependencies: &'a [Dependency],
64 targets: Vec<&'a Target>,
65 features: &'a FeatureMap,
66 manifest_path: &'a Path,
67 metadata: Option<&'a toml::Value>,
68 authors: &'a [String],
69 categories: &'a [String],
70 keywords: &'a [String],
71 readme: Option<&'a str>,
72 repository: Option<&'a str>,
73 edition: &'a str,
74 links: Option<&'a str>,
75 #[serde(skip_serializing_if = "Option::is_none")]
76 metabuild: Option<&'a Vec<String>>,
77}
78
79impl ser::Serialize for Package {
80 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
81 where
82 S: ser::Serializer,
83 {
84 let summary = self.manifest.summary();
85 let package_id = summary.package_id();
86 let manmeta = self.manifest.metadata();
87 let license = manmeta.license.as_ref().map(String::as_ref);
88 let license_file = manmeta.license_file.as_ref().map(String::as_ref);
89 let description = manmeta.description.as_ref().map(String::as_ref);
90 let authors = manmeta.authors.as_ref();
91 let categories = manmeta.categories.as_ref();
92 let keywords = manmeta.keywords.as_ref();
93 let readme = manmeta.readme.as_ref().map(String::as_ref);
94 let repository = manmeta.repository.as_ref().map(String::as_ref);
95 let targets: Vec<&Target> = self
99 .manifest
100 .targets()
101 .iter()
102 .filter(|t| t.src_path().is_path())
103 .collect();
104
105 SerializedPackage {
106 name: &*package_id.name(),
107 version: &package_id.version(),
108 id: package_id,
109 license,
110 license_file,
111 description,
112 source: summary.source_id(),
113 dependencies: summary.dependencies(),
114 targets,
115 features: summary.features(),
116 manifest_path: &self.manifest_path,
117 metadata: self.manifest.custom_metadata(),
118 authors,
119 categories,
120 keywords,
121 readme,
122 repository,
123 edition: &self.manifest.edition().to_string(),
124 links: self.manifest.links(),
125 metabuild: self.manifest.metabuild(),
126 }
127 .serialize(s)
128 }
129}
130
131impl Package {
132 pub fn new(manifest: Manifest, manifest_path: &Path) -> Package {
134 Package {
135 manifest,
136 manifest_path: manifest_path.to_path_buf(),
137 }
138 }
139
140 pub fn dependencies(&self) -> &[Dependency] {
142 self.manifest.dependencies()
143 }
144 pub fn manifest(&self) -> &Manifest {
146 &self.manifest
147 }
148 pub fn manifest_path(&self) -> &Path {
150 &self.manifest_path
151 }
152 pub fn name(&self) -> InternedString {
154 self.package_id().name()
155 }
156 pub fn package_id(&self) -> PackageId {
158 self.manifest.package_id()
159 }
160 pub fn root(&self) -> &Path {
162 self.manifest_path.parent().unwrap()
163 }
164 pub fn summary(&self) -> &Summary {
166 self.manifest.summary()
167 }
168 pub fn targets(&self) -> &[Target] {
170 self.manifest.targets()
171 }
172 pub fn version(&self) -> &Version {
174 self.package_id().version()
175 }
176 pub fn authors(&self) -> &Vec<String> {
178 &self.manifest.metadata().authors
179 }
180 pub fn publish(&self) -> &Option<Vec<String>> {
182 self.manifest.publish()
183 }
184
185 pub fn has_custom_build(&self) -> bool {
187 self.targets().iter().any(|t| t.is_custom_build())
188 }
189
190 pub fn find_closest_target(
191 &self,
192 target: &str,
193 is_expected_kind: fn(&Target) -> bool,
194 ) -> Option<&Target> {
195 let targets = self.targets();
196
197 let matches = targets
198 .iter()
199 .filter(|t| is_expected_kind(t))
200 .map(|t| (lev_distance(target, t.name()), t))
201 .filter(|&(d, _)| d < 4);
202 matches.min_by_key(|t| t.0).map(|t| t.1)
203 }
204
205 pub fn map_source(self, to_replace: SourceId, replace_with: SourceId) -> Package {
206 Package {
207 manifest: self.manifest.map_source(to_replace, replace_with),
208 manifest_path: self.manifest_path,
209 }
210 }
211
212 pub fn to_registry_toml(&self, config: &Config) -> CargoResult<String> {
213 let manifest = self.manifest().original().prepare_for_publish(config)?;
214 let toml = toml::to_string(&manifest)?;
215 Ok(format!(
216 "\
217 # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO\n\
218 #\n\
219 # When uploading crates to the registry Cargo will automatically\n\
220 # \"normalize\" Cargo.toml files for maximal compatibility\n\
221 # with all versions of Cargo and also rewrite `path` dependencies\n\
222 # to registry (e.g. crates.io) dependencies\n\
223 #\n\
224 # If you believe there's an error in this file please file an\n\
225 # issue against the rust-lang/cargo repository. If you're\n\
226 # editing this file be aware that the upstream Cargo.toml\n\
227 # will likely look very different (and much more reasonable)\n\
228 \n\
229 {}\
230 ",
231 toml
232 ))
233 }
234}
235
236impl fmt::Display for Package {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 write!(f, "{}", self.summary().package_id())
239 }
240}
241
242impl fmt::Debug for Package {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 f.debug_struct("Package")
245 .field("id", &self.summary().package_id())
246 .field("..", &"..")
247 .finish()
248 }
249}
250
251impl PartialEq for Package {
252 fn eq(&self, other: &Package) -> bool {
253 self.package_id() == other.package_id()
254 }
255}
256
257impl Eq for Package {}
258
259impl hash::Hash for Package {
260 fn hash<H: hash::Hasher>(&self, into: &mut H) {
261 self.package_id().hash(into)
262 }
263}
264
265pub struct PackageSet<'cfg> {
266 packages: HashMap<PackageId, LazyCell<Package>>,
267 sources: RefCell<SourceMap<'cfg>>,
268 config: &'cfg Config,
269 multi: Multi,
270 downloading: Cell<bool>,
271 multiplexing: bool,
272}
273
274pub struct Downloads<'a, 'cfg: 'a> {
275 set: &'a PackageSet<'cfg>,
276 pending: HashMap<usize, (Download<'cfg>, EasyHandle)>,
277 pending_ids: HashSet<PackageId>,
278 results: Vec<(usize, Result<(), curl::Error>)>,
279 next: usize,
280 progress: RefCell<Option<Progress<'cfg>>>,
281 downloads_finished: usize,
282 downloaded_bytes: u64,
283 largest: (u64, String),
284 start: Instant,
285 success: bool,
286
287 timeout: ops::HttpTimeout, updated_at: Cell<Instant>, next_speed_check: Cell<Instant>, next_speed_check_bytes_threshold: Cell<u64>, }
298
299struct Download<'cfg> {
300 token: usize,
303
304 id: PackageId,
306
307 data: RefCell<Vec<u8>>,
309
310 url: String,
313
314 descriptor: String,
316
317 total: Cell<u64>,
319 current: Cell<u64>,
320
321 start: Instant,
323 timed_out: Cell<Option<String>>,
324
325 retry: Retry<'cfg>,
327}
328
329impl<'cfg> PackageSet<'cfg> {
330 pub fn new(
331 package_ids: &[PackageId],
332 sources: SourceMap<'cfg>,
333 config: &'cfg Config,
334 ) -> CargoResult<PackageSet<'cfg>> {
335 let mut multi = Multi::new();
345 let multiplexing = config
346 .get::<Option<bool>>("http.multiplexing")?
347 .unwrap_or(true);
348 multi
349 .pipelining(false, multiplexing)
350 .chain_err(|| "failed to enable multiplexing/pipelining in curl")?;
351
352 multi.set_max_host_connections(2)?;
354
355 Ok(PackageSet {
356 packages: package_ids
357 .iter()
358 .map(|&id| (id, LazyCell::new()))
359 .collect(),
360 sources: RefCell::new(sources),
361 config,
362 multi,
363 downloading: Cell::new(false),
364 multiplexing,
365 })
366 }
367
368 pub fn package_ids<'a>(&'a self) -> impl Iterator<Item = PackageId> + 'a {
369 self.packages.keys().cloned()
370 }
371
372 pub fn enable_download<'a>(&'a self) -> CargoResult<Downloads<'a, 'cfg>> {
373 assert!(!self.downloading.replace(true));
374 let timeout = ops::HttpTimeout::new(self.config)?;
375 Ok(Downloads {
376 start: Instant::now(),
377 set: self,
378 next: 0,
379 pending: HashMap::new(),
380 pending_ids: HashSet::new(),
381 results: Vec::new(),
382 progress: RefCell::new(Some(Progress::with_style(
383 "Downloading",
384 ProgressStyle::Ratio,
385 self.config,
386 ))),
387 downloads_finished: 0,
388 downloaded_bytes: 0,
389 largest: (0, String::new()),
390 success: false,
391 updated_at: Cell::new(Instant::now()),
392 timeout,
393 next_speed_check: Cell::new(Instant::now()),
394 next_speed_check_bytes_threshold: Cell::new(0),
395 })
396 }
397
398 pub fn get_one(&self, id: PackageId) -> CargoResult<&Package> {
399 Ok(self.get_many(Some(id))?.remove(0))
400 }
401
402 pub fn get_many(&self, ids: impl IntoIterator<Item = PackageId>) -> CargoResult<Vec<&Package>> {
403 let mut pkgs = Vec::new();
404 let mut downloads = self.enable_download()?;
405 for id in ids {
406 pkgs.extend(downloads.start(id)?);
407 }
408 while downloads.remaining() > 0 {
409 pkgs.push(downloads.wait()?);
410 }
411 downloads.success = true;
412 Ok(pkgs)
413 }
414
415 pub fn sources(&self) -> Ref<'_, SourceMap<'cfg>> {
416 self.sources.borrow()
417 }
418}
419
420macro_rules! try_old_curl {
423 ($e:expr, $msg:expr) => {
424 let result = $e;
425 if cfg!(target_os = "macos") {
426 if let Err(e) = result {
427 warn!("ignoring libcurl {} error: {}", $msg, e);
428 }
429 } else {
430 result.with_context(|_| {
431 failure::format_err!("failed to enable {}, is curl not built right?", $msg)
432 })?;
433 }
434 };
435}
436
437impl<'a, 'cfg> Downloads<'a, 'cfg> {
438 pub fn start(&mut self, id: PackageId) -> CargoResult<Option<&'a Package>> {
444 let slot = self
447 .set
448 .packages
449 .get(&id)
450 .ok_or_else(|| internal(format!("couldn't find `{}` in package set", id)))?;
451 if let Some(pkg) = slot.borrow() {
452 return Ok(Some(pkg));
453 }
454
455 let mut sources = self.set.sources.borrow_mut();
459 let source = sources
460 .get_mut(id.source_id())
461 .ok_or_else(|| internal(format!("couldn't find source for `{}`", id)))?;
462 let pkg = source
463 .download(id)
464 .chain_err(|| failure::format_err!("unable to get packages from source"))?;
465 let (url, descriptor) = match pkg {
466 MaybePackage::Ready(pkg) => {
467 debug!("{} doesn't need a download", id);
468 assert!(slot.fill(pkg).is_ok());
469 return Ok(Some(slot.borrow().unwrap()));
470 }
471 MaybePackage::Download { url, descriptor } => (url, descriptor),
472 };
473
474 let token = self.next;
479 self.next += 1;
480 debug!("downloading {} as {}", id, token);
481 assert!(self.pending_ids.insert(id));
482
483 let (mut handle, _timeout) = ops::http_handle_and_timeout(self.set.config)?;
484 handle.get(true)?;
485 handle.url(&url)?;
486 handle.follow_location(true)?; if self.set.multiplexing {
501 try_old_curl!(handle.http_version(HttpVersion::V2), "HTTP2");
502 } else {
503 handle.http_version(HttpVersion::V11)?;
504 }
505
506 try_old_curl!(handle.pipewait(true), "pipewait");
514
515 handle.write_function(move |buf| {
516 debug!("{} - {} bytes of data", token, buf.len());
517 tls::with(|downloads| {
518 if let Some(downloads) = downloads {
519 downloads.pending[&token]
520 .0
521 .data
522 .borrow_mut()
523 .extend_from_slice(buf);
524 }
525 });
526 Ok(buf.len())
527 })?;
528
529 handle.progress(true)?;
530 handle.progress_function(move |dl_total, dl_cur, _, _| {
531 tls::with(|downloads| match downloads {
532 Some(d) => d.progress(token, dl_total as u64, dl_cur as u64),
533 None => false,
534 })
535 })?;
536
537 if self.downloads_finished == 0
541 && self.pending.is_empty()
542 && !self.progress.borrow().as_ref().unwrap().is_enabled()
543 {
544 self.set
545 .config
546 .shell()
547 .status("Downloading", "crates ...")?;
548 }
549
550 let dl = Download {
551 token,
552 data: RefCell::new(Vec::new()),
553 id,
554 url,
555 descriptor,
556 total: Cell::new(0),
557 current: Cell::new(0),
558 start: Instant::now(),
559 timed_out: Cell::new(None),
560 retry: Retry::new(self.set.config)?,
561 };
562 self.enqueue(dl, handle)?;
563 self.tick(WhyTick::DownloadStarted)?;
564
565 Ok(None)
566 }
567
568 pub fn remaining(&self) -> usize {
570 self.pending.len()
571 }
572
573 pub fn wait(&mut self) -> CargoResult<&'a Package> {
582 let (dl, data) = loop {
583 assert_eq!(self.pending.len(), self.pending_ids.len());
584 let (token, result) = self.wait_for_curl()?;
585 debug!("{} finished with {:?}", token, result);
586
587 let (mut dl, handle) = self
588 .pending
589 .remove(&token)
590 .expect("got a token for a non-in-progress transfer");
591 let data = mem::replace(&mut *dl.data.borrow_mut(), Vec::new());
592 let mut handle = self.set.multi.remove(handle)?;
593 self.pending_ids.remove(&dl.id);
594
595 let ret = {
599 let timed_out = &dl.timed_out;
600 let url = &dl.url;
601 dl.retry
602 .r#try(|| {
603 if let Err(e) = result {
604 if !e.is_aborted_by_callback() {
612 return Err(e.into());
613 }
614
615 return Err(match timed_out.replace(None) {
616 Some(msg) => {
617 let code = curl_sys::CURLE_OPERATION_TIMEDOUT;
618 let mut err = curl::Error::new(code);
619 err.set_extra(msg);
620 err
621 }
622 None => e,
623 }
624 .into());
625 }
626
627 let code = handle.response_code()?;
628 if code != 200 && code != 0 {
629 let url = handle.effective_url()?.unwrap_or(url);
630 return Err(HttpNot200 {
631 code,
632 url: url.to_string(),
633 }
634 .into());
635 }
636 Ok(())
637 })
638 .chain_err(|| format!("failed to download from `{}`", dl.url))?
639 };
640 match ret {
641 Some(()) => break (dl, data),
642 None => {
643 self.pending_ids.insert(dl.id);
644 self.enqueue(dl, handle)?
645 }
646 }
647 };
648
649 self.progress.borrow_mut().as_mut().unwrap().clear();
653 self.set
654 .config
655 .shell()
656 .status("Downloaded", &dl.descriptor)?;
657
658 self.downloads_finished += 1;
659 self.downloaded_bytes += dl.total.get();
660 if dl.total.get() > self.largest.0 {
661 self.largest = (dl.total.get(), dl.id.name().to_string());
662 }
663
664 if dl.total.get() < ByteSize::kb(400).0 {
670 self.tick(WhyTick::DownloadFinished)?;
671 } else {
672 self.tick(WhyTick::Extracting(&dl.id.name()))?;
673 }
674
675 let mut sources = self.set.sources.borrow_mut();
678 let source = sources
679 .get_mut(dl.id.source_id())
680 .ok_or_else(|| internal(format!("couldn't find source for `{}`", dl.id)))?;
681 let start = Instant::now();
682 let pkg = source.finish_download(dl.id, data)?;
683
684 let finish_dur = start.elapsed();
689 self.updated_at.set(self.updated_at.get() + finish_dur);
690 self.next_speed_check
691 .set(self.next_speed_check.get() + finish_dur);
692
693 let slot = &self.set.packages[&dl.id];
694 assert!(slot.fill(pkg).is_ok());
695 Ok(slot.borrow().unwrap())
696 }
697
698 fn enqueue(&mut self, dl: Download<'cfg>, handle: Easy) -> CargoResult<()> {
699 let mut handle = self.set.multi.add(handle)?;
700 let now = Instant::now();
701 handle.set_token(dl.token)?;
702 self.updated_at.set(now);
703 self.next_speed_check.set(now + self.timeout.dur);
704 self.next_speed_check_bytes_threshold
705 .set(u64::from(self.timeout.low_speed_limit));
706 dl.timed_out.set(None);
707 dl.current.set(0);
708 dl.total.set(0);
709 self.pending.insert(dl.token, (dl, handle));
710 Ok(())
711 }
712
713 fn wait_for_curl(&mut self) -> CargoResult<(usize, Result<(), curl::Error>)> {
714 loop {
730 let n = tls::set(self, || {
731 self.set
732 .multi
733 .perform()
734 .chain_err(|| "failed to perform http requests")
735 })?;
736 debug!("handles remaining: {}", n);
737 let results = &mut self.results;
738 let pending = &self.pending;
739 self.set.multi.messages(|msg| {
740 let token = msg.token().expect("failed to read token");
741 let handle = &pending[&token].1;
742 if let Some(result) = msg.result_for(&handle) {
743 results.push((token, result));
744 } else {
745 debug!("message without a result (?)");
746 }
747 });
748
749 if let Some(pair) = results.pop() {
750 break Ok(pair);
751 }
752 assert!(!self.pending.is_empty());
753 let timeout = self
754 .set
755 .multi
756 .get_timeout()?
757 .unwrap_or_else(|| Duration::new(5, 0));
758 self.set
759 .multi
760 .wait(&mut [], timeout)
761 .chain_err(|| "failed to wait on curl `Multi`")?;
762 }
763 }
764
765 fn progress(&self, token: usize, total: u64, cur: u64) -> bool {
766 let dl = &self.pending[&token].0;
767 dl.total.set(total);
768 let now = Instant::now();
769 if cur != dl.current.get() {
770 let delta = cur - dl.current.get();
771 let threshold = self.next_speed_check_bytes_threshold.get();
772
773 dl.current.set(cur);
774 self.updated_at.set(now);
775
776 if delta >= threshold {
777 self.next_speed_check.set(now + self.timeout.dur);
778 self.next_speed_check_bytes_threshold
779 .set(u64::from(self.timeout.low_speed_limit));
780 } else {
781 self.next_speed_check_bytes_threshold.set(threshold - delta);
782 }
783 }
784 if self.tick(WhyTick::DownloadUpdate).is_err() {
785 return false;
786 }
787
788 if now - self.updated_at.get() > self.timeout.dur {
790 self.updated_at.set(now);
791 let msg = format!(
792 "failed to download any data for `{}` within {}s",
793 dl.id,
794 self.timeout.dur.as_secs()
795 );
796 dl.timed_out.set(Some(msg));
797 return false;
798 }
799
800 if now >= self.next_speed_check.get() {
805 self.next_speed_check.set(now + self.timeout.dur);
806 assert!(self.next_speed_check_bytes_threshold.get() > 0);
807 let msg = format!(
808 "download of `{}` failed to transfer more \
809 than {} bytes in {}s",
810 dl.id,
811 self.timeout.low_speed_limit,
812 self.timeout.dur.as_secs()
813 );
814 dl.timed_out.set(Some(msg));
815 return false;
816 }
817
818 true
819 }
820
821 fn tick(&self, why: WhyTick<'_>) -> CargoResult<()> {
822 let mut progress = self.progress.borrow_mut();
823 let progress = progress.as_mut().unwrap();
824
825 if let WhyTick::DownloadUpdate = why {
826 if !progress.update_allowed() {
827 return Ok(());
828 }
829 }
830 let pending = self.pending.len();
831 let mut msg = if pending == 1 {
832 format!("{} crate", pending)
833 } else {
834 format!("{} crates", pending)
835 };
836 match why {
837 WhyTick::Extracting(krate) => {
838 msg.push_str(&format!(", extracting {} ...", krate));
839 }
840 _ => {
841 let mut dur = Duration::new(0, 0);
842 let mut remaining = 0;
843 for (dl, _) in self.pending.values() {
844 dur += dl.start.elapsed();
845 if dl.total.get() >= dl.current.get() {
849 remaining += dl.total.get() - dl.current.get();
850 }
851 }
852 if remaining > 0 && dur > Duration::from_millis(500) {
853 msg.push_str(&format!(", remaining bytes: {}", ByteSize(remaining)));
854 }
855 }
856 }
857 progress.print_now(&msg)
858 }
859}
860
861#[derive(Copy, Clone)]
862enum WhyTick<'a> {
863 DownloadStarted,
864 DownloadUpdate,
865 DownloadFinished,
866 Extracting(&'a str),
867}
868
869impl<'a, 'cfg> Drop for Downloads<'a, 'cfg> {
870 fn drop(&mut self) {
871 self.set.downloading.set(false);
872 let progress = self.progress.get_mut().take().unwrap();
873 if !progress.is_enabled() {
876 return;
877 }
878 if self.downloads_finished == 0 {
880 return;
881 }
882 if !self.success {
884 return;
885 }
886 let mut status = format!(
887 "{} crates ({}) in {}",
888 self.downloads_finished,
889 ByteSize(self.downloaded_bytes),
890 util::elapsed(self.start.elapsed())
891 );
892 if self.largest.0 > ByteSize::mb(1).0 {
893 status.push_str(&format!(
894 " (largest was `{}` at {})",
895 self.largest.1,
896 ByteSize(self.largest.0),
897 ));
898 }
899 drop(progress);
901 drop(self.set.config.shell().status("Downloaded", status));
902 }
903}
904
905mod tls {
906 use std::cell::Cell;
907
908 use super::Downloads;
909
910 thread_local!(static PTR: Cell<usize> = Cell::new(0));
911
912 pub(crate) fn with<R>(f: impl FnOnce(Option<&Downloads<'_, '_>>) -> R) -> R {
913 let ptr = PTR.with(|p| p.get());
914 if ptr == 0 {
915 f(None)
916 } else {
917 unsafe { f(Some(&*(ptr as *const Downloads<'_, '_>))) }
918 }
919 }
920
921 pub(crate) fn set<R>(dl: &Downloads<'_, '_>, f: impl FnOnce() -> R) -> R {
922 struct Reset<'a, T: Copy>(&'a Cell<T>, T);
923
924 impl<'a, T: Copy> Drop for Reset<'a, T> {
925 fn drop(&mut self) {
926 self.0.set(self.1);
927 }
928 }
929
930 PTR.with(|p| {
931 let _reset = Reset(p, p.get());
932 p.set(dl as *const Downloads<'_, '_> as usize);
933 f()
934 })
935 }
936}