summaryrefslogtreecommitdiff
path: root/learn_7/src/main.rs
blob: e950bacc1a0825b9221f0e089957f51a3cb15665 (plain)
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
struct Job {
    id: u64,
    description: String,
    payload: Vec<u8>,
}

struct WorkQueue {
    jobs: Vec<Job>,
}

impl WorkQueue {
    pub fn new() -> Self {
        Self {
            jobs: Vec::new(),
        }
    }

    pub fn submit(&mut self, job: Job) {
        self.jobs.push(job)
    }

    pub fn next(&mut self) -> Option<Job> {
        if self.jobs.len() != 0 {
            return Some(self.jobs.remove(0));
        }
        None
    }

    pub fn len(&self) -> usize {
        self.jobs.len()
    }

    pub fn drain_descriptions(&mut self) -> Vec<String> {
        self.jobs.drain(..).map(|job| job.description).collect()
    }
}

fn main() {
    ()
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    pub fn test_new() {
        assert_eq!(WorkQueue::new().jobs.len(), 0);
    }

    #[test]
    pub fn test_submit() {
        let mut wq = WorkQueue::new();
        assert_eq!(wq.jobs.len(), 0);
        wq.submit(Job{id:1, description:String::from("1"), payload: Vec::new()});
        assert_eq!(wq.jobs.len(), 1);
    }

    #[test]
    pub fn test_next() {
        let mut wq = WorkQueue::new();
        assert_eq!(wq.jobs.len(), 0);
        wq.submit(Job{id:1, description:String::from("1"), payload: Vec::new()});
        assert_eq!(wq.jobs.len(), 1);
        wq.submit(Job{id:2, description:String::from("2"), payload: Vec::new()});
        assert_eq!(wq.jobs.len(), 2);
        assert!(wq.next().is_some_and(|x| x.id == 1));
        assert!(wq.next().is_some_and(|x| x.id == 2));
        assert!(wq.next().is_none());
    }

    #[test]
    pub fn test_len() {
        let mut wq = WorkQueue::new();
        assert_eq!(wq.len(), 0);
        wq.submit(Job{id:1, description:String::from("1"), payload: Vec::new()});
        assert_eq!(wq.len(), 1);
        wq.submit(Job{id:2, description:String::from("2"), payload: Vec::new()});
        assert_eq!(wq.len(), 2);
        assert!(wq.next().is_some_and(|x| x.id == 1));
        assert_eq!(wq.len(), 1);
        assert!(wq.next().is_some_and(|x| x.id == 2));
        assert_eq!(wq.len(), 0);
        assert!(wq.next().is_none());
    }

    #[test]
    pub fn test_drain_descriptions() {
        let mut wq = WorkQueue::new();
        assert_eq!(wq.drain_descriptions().len(), 0);
        wq.submit(Job{id:1, description:String::from("1"), payload: Vec::new()});
        wq.submit(Job{id:2, description:String::from("2"), payload: Vec::new()});
        let descriptions = wq.drain_descriptions();
        assert_eq!(descriptions.as_slice(), &["1", "2"]);
    }
}