fast_down/core/
mod.rs

1use crate::Event;
2use std::sync::Arc;
3use tokio::{
4    sync::{mpsc::Receiver, Mutex},
5    task::{JoinError, JoinHandle},
6};
7
8pub mod auto;
9pub mod multi;
10pub mod prefetch;
11pub mod single;
12
13pub type CancelFn = Box<dyn FnOnce() + Send>;
14
15#[derive(Clone)]
16pub struct DownloadResult {
17    pub event_chain: Arc<Mutex<Receiver<Event>>>,
18    handle: Arc<Mutex<Option<JoinHandle<()>>>>,
19    cancel_fn: Arc<Mutex<Option<CancelFn>>>,
20}
21
22impl DownloadResult {
23    pub fn new(event_chain: Receiver<Event>, handle: JoinHandle<()>, cancel_fn: CancelFn) -> Self {
24        Self {
25            event_chain: Arc::new(Mutex::new(event_chain)),
26            handle: Arc::new(Mutex::new(Some(handle))),
27            cancel_fn: Arc::new(Mutex::new(Some(cancel_fn))),
28        }
29    }
30
31    pub async fn join(&self) -> Result<(), JoinError> {
32        if let Some(handle) = self.handle.lock().await.take() {
33            handle.await?
34        }
35        Ok(())
36    }
37
38    pub async fn cancel(&self) {
39        if let Some(cancel_fn) = self.cancel_fn.lock().await.take() {
40            cancel_fn()
41        }
42    }
43}