Skip to main content

rs_plugin_common_interfaces/domain/
progress.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, PartialOrd, Default)]
4#[serde(rename_all = "camelCase")]
5pub struct RsProgress {
6    pub id: String,
7    pub total: Option<u64>,
8    pub current: Option<u64>,
9    pub filename: Option<String>,
10    #[serde(rename = "type")]
11    pub kind: RsProgressType,
12}
13
14#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, PartialOrd, Default)]
15#[serde(rename_all = "camelCase")]
16pub enum RsProgressType {
17    Download,
18    #[default]
19    Transfert,
20    Analysing,
21    Finished,
22    Duplicate(String),
23    Failed(String),
24}
25
26impl RsProgress {
27    pub fn percent(&self) -> Option<f32> {
28        if let (Some(total), Some(current)) = (self.total, self.current) {
29            if total == 0 {
30                return None;
31            }
32            Some(current as f32 / total as f32)
33        } else {
34            None
35        }
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn failed_progress_serializes_as_failed_payload() {
45        let progress = RsProgress {
46            id: "upload-1".to_string(),
47            total: Some(1),
48            current: Some(1),
49            filename: Some("photo.jpg".to_string()),
50            kind: RsProgressType::Failed("network error".to_string()),
51        };
52
53        let json = serde_json::to_string(&progress).unwrap();
54        assert!(json.contains("\"failed\":\"network error\""));
55    }
56
57    #[test]
58    fn percent_ignores_zero_total() {
59        let progress = RsProgress {
60            total: Some(0),
61            current: Some(0),
62            ..Default::default()
63        };
64
65        assert_eq!(progress.percent(), None);
66    }
67}