atm0s_media_server_utils/
tracking.rs

1use std::collections::HashMap;
2
3#[derive(Default)]
4pub struct ResourceTracking {
5    resources: HashMap<String, i32>,
6}
7
8impl ResourceTracking {
9    /// Adding resource to list, first type is count as 1, if already exits => count++
10    pub fn add(&mut self, resource: &str) {
11        let entry = self.resources.entry(resource.to_string()).or_insert(0);
12        *entry += 1;
13    }
14
15    /// Remove resource from list, if count == 0 => remove from list, if count < 0 => panic
16    pub fn remove(&mut self, resource: &str) {
17        if let Some(entry) = self.resources.get_mut(resource) {
18            *entry -= 1;
19            if *entry == 0 {
20                self.resources.remove(resource);
21            } else if *entry < 0 {
22                panic!("ResourceTracking: entry < 0");
23            }
24        }
25    }
26
27    pub fn add2(&mut self, resource: &str, sub: &str) {
28        self.add(&format!("{}/{}", resource, sub));
29    }
30
31    pub fn remove2(&mut self, resource: &str, sub: &str) {
32        self.remove(&format!("{}/{}", resource, sub));
33    }
34
35    pub fn add3(&mut self, resource: &str, sub: &str, sub2: &str) {
36        self.add(&format!("{}/{}/{}", resource, sub, sub2));
37    }
38
39    pub fn remove3(&mut self, resource: &str, sub: &str, sub2: &str) {
40        self.remove(&format!("{}/{}/{}", resource, sub, sub2));
41    }
42
43    pub fn is_empty(&self) -> bool {
44        self.resources.is_empty()
45    }
46
47    pub fn dump(&self) -> String {
48        let mut res = String::new();
49        for (k, v) in self.resources.iter() {
50            res.push_str(&format!("{}: {}, ", k, v));
51        }
52        res
53    }
54}