summaryrefslogtreecommitdiffstats
path: root/src/robo.rs
blob: f508879e2284a1381353bb42adb82849df377af5 (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
use std::collections::HashMap;
use std::sync::Mutex;

pub struct Robo {
    speed: Mutex<usize>,
}

//type InsKey = usize;
type InsKey = &'static str;
type InsMap<'a> = HashMap<InsKey, Box<dyn FnMut() + 'a>>;
// const KEY1: InsKey = 0;
// const KEY2: InsKey = 0;
const KEY1: InsKey = "mv1";
const KEY2: InsKey = "mv2";

pub struct Co<'a> {
    ins: InsMap<'a>,
}

impl<'a> Co<'a> {
    pub fn new(ins: InsMap<'a>) -> Self {
        Self { ins }
    }

    pub fn run(&mut self) {
        (self.ins.get_mut(&KEY1).expect("should have move word"))();
        (self.ins.get_mut(&KEY2).expect("should have move2 word"))();
    }
}

impl<'a> Robo {
    pub fn new() -> Self {
        Self {
            speed: Mutex::new(0),
        }
    }

    pub fn make_ins(&'a mut self) -> InsMap<'a> {
        let mut map = HashMap::new();
        let s = &mut self.speed;
        let op_speed = || {
            let mut x =
                s.lock().expect("couldn't get lock on speed");
            *x = 1;
        };
        let op_speed2 = || {
            let mut x =
                s.lock().expect("couldn't get lock on speed");
            *x = 2;
        };
        map.insert(KEY1, Box::new(op_speed) as Box<dyn FnMut()>);
        map.insert(KEY2, Box::new(op_speed2) as Box<dyn FnMut()>);
        map
    }
}

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

    #[test]
    fn can_run() {
        let mut r = Robo::new();
        let ins: InsMap = r.make_ins();
        let mut c: Co = Co::new(ins);
        c.run();
    }
}