1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
pub mod engines;

pub mod prelude {
    pub use super::{engines::prelude::*, engines::*};
}

use crate::{id::ID, Scalar};
use std::{
    mem::replace,
    sync::{Arc, Mutex},
};

pub type FetchProcessID = ID<FetchProcess>;

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum FetchCancelReason {
    User,
    Error,
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum FetchStatus {
    Empty,
    InProgress(Scalar),
    Done,
    Canceled(FetchCancelReason),
    Read,
}

pub trait FetchProcessReader: Send + Sync {
    fn status(&self) -> FetchStatus;
    fn read(&self) -> Option<Vec<u8>>;
    fn byte_size(&self) -> Option<usize>;
    fn box_clone(&self) -> Box<dyn FetchProcessReader>;
}

impl Clone for Box<dyn FetchProcessReader> {
    fn clone(&self) -> Self {
        self.box_clone()
    }
}

#[derive(Clone)]
pub struct FetchProcess {
    id: FetchProcessID,
    inner: Arc<Mutex<(FetchStatus, Option<Vec<u8>>)>>,
}

impl Default for FetchProcess {
    fn default() -> Self {
        Self::new()
    }
}

impl FetchProcess {
    #[inline]
    pub fn new() -> Self {
        Self {
            id: FetchProcessID::new(),
            inner: Arc::new(Mutex::new((FetchStatus::Empty, None))),
        }
    }

    #[inline]
    pub fn new_start() -> Self {
        Self {
            id: FetchProcessID::new(),
            inner: Arc::new(Mutex::new((FetchStatus::InProgress(0.0), None))),
        }
    }

    #[inline]
    pub fn new_done(data: Vec<u8>) -> Self {
        Self {
            id: FetchProcessID::new(),
            inner: Arc::new(Mutex::new((FetchStatus::Done, Some(data)))),
        }
    }

    #[inline]
    pub fn new_cancel(reason: FetchCancelReason) -> Self {
        Self {
            id: FetchProcessID::new(),
            inner: Arc::new(Mutex::new((FetchStatus::Canceled(reason), None))),
        }
    }

    #[inline]
    pub fn id(&self) -> FetchProcessID {
        self.id
    }

    pub fn start(&mut self) {
        if let Ok(mut meta) = self.inner.lock() {
            *meta = (FetchStatus::InProgress(0.0), None);
        }
    }

    pub fn progress(&mut self, value: Scalar) {
        if let Ok(mut meta) = self.inner.lock() {
            *meta = (FetchStatus::InProgress(value), None);
        }
    }

    pub fn done(&mut self, data: Vec<u8>) {
        if let Ok(mut meta) = self.inner.lock() {
            *meta = (FetchStatus::Done, Some(data));
        }
    }

    pub fn cancel(&mut self, reason: FetchCancelReason) {
        if let Ok(mut meta) = self.inner.lock() {
            *meta = (FetchStatus::Canceled(reason), None);
        }
    }

    pub fn readers_count(&self) -> usize {
        Arc::strong_count(&self.inner) + Arc::weak_count(&self.inner) - 1
    }
}

impl FetchProcessReader for FetchProcess {
    fn status(&self) -> FetchStatus {
        if let Ok(meta) = self.inner.lock() {
            meta.0
        } else {
            FetchStatus::Empty
        }
    }

    fn read(&self) -> Option<Vec<u8>> {
        if let Ok(mut meta) = self.inner.lock() {
            if meta.0 == FetchStatus::Done {
                let old: (FetchStatus, Option<Vec<u8>>) =
                    replace(&mut meta, (FetchStatus::Read, None));
                return old.1;
            }
        }
        None
    }

    fn byte_size(&self) -> Option<usize> {
        if let Ok(meta) = self.inner.lock() {
            if meta.0 == FetchStatus::Done {
                if let Some(bytes) = &meta.1 {
                    return Some(bytes.len());
                }
            }
        }
        None
    }

    fn box_clone(&self) -> Box<dyn FetchProcessReader> {
        Box::new((*self).clone())
    }
}

pub trait FetchEngine: Send + Sync {
    fn fetch(&mut self, path: &str) -> Result<Box<dyn FetchProcessReader>, FetchStatus>;

    fn cancel(&mut self, reader: Box<dyn FetchProcessReader>) {
        #[allow(clippy::cast_ptr_alignment)]
        let ptr = Box::into_raw(reader) as *mut FetchProcess;
        unsafe {
            (*ptr).cancel(FetchCancelReason::User);
            Box::from_raw(ptr);
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    #[cfg(not(feature = "web"))]
    fn test_general() {
        let mut engine = engines::fs::FsFetchEngine::new(&".");
        let reader = engine.fetch("Cargo.toml").unwrap();
        let reader2 = reader.clone();
        #[cfg(feature = "parallel")]
        {
            assert_eq!(reader.status(), FetchStatus::InProgress(0.0));
            assert_eq!(reader2.status(), FetchStatus::InProgress(0.0));
        }
        loop {
            match reader.status() {
                FetchStatus::InProgress(_) => continue,
                _ => break,
            }
        }
        assert_eq!(reader.status(), FetchStatus::Done);
        assert_eq!(reader2.status(), FetchStatus::Done);
        assert!(!reader.read().unwrap().is_empty());
        assert_eq!(reader.status(), FetchStatus::Empty);
        assert_eq!(reader2.status(), FetchStatus::Empty);
        drop(reader);
        drop(reader2);
    }
}