var_watcher/
watcher.rs

1use std::collections::HashSet;
2
3pub struct Watcher<T> {
4    value: T,
5    callbacks: HashSet<fn(*const T)>
6}
7
8impl<T> Watcher<T> {
9    pub fn new(value: T) -> Watcher<T> {
10        Watcher {
11            value: value,
12            callbacks: HashSet::new()
13        }
14    }
15
16    pub fn register_callback(&mut self, f: fn(*const T)) -> bool {
17        self.callbacks.insert(f)
18    }
19
20    pub fn get(&self) -> &T {
21        &self.value
22    }
23
24    pub fn set(&mut self, value: T) {
25        self.value = value;
26        for callback in &self.callbacks {
27            callback(&self.value);
28        }
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn initiate_callback() {
38        fn callback(val: *const u8) {
39            unsafe { assert_eq!(*val, 7); }
40        }
41        let mut watcher = Watcher::new(5);
42        watcher.register_callback(callback);
43
44        watcher.set(7);
45    }
46}