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
pub mod engines;

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

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,
}

impl Default for FetchStatus {
    fn default() -> Self {
        Self::Empty
    }
}

#[derive(Clone)]
pub struct FetchProcess {
    id: FetchProcessId,
    inner: Arc<RwLock<(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(RwLock::new((FetchStatus::Empty, None))),
        }
    }

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

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

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

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

    pub fn status(&self) -> FetchStatus {
        self.inner.read().map(|meta| meta.0).unwrap_or_default()
    }

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

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

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

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

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

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

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

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

    fn cancel(&mut self, mut reader: FetchProcess) {
        reader.cancel(FetchCancelReason::User)
    }
}

#[cfg(test)]
mod tests {
    #[allow(unused_imports)]
    use super::*;

    #[test]
    #[cfg(not(feature = "web"))]
    fn test_fetch() {
        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::Read);
        assert_eq!(reader2.status(), FetchStatus::Read);
    }
}