summaryrefslogtreecommitdiffstats
path: root/third_party/rust/authenticator/src/statecallback.rs
blob: ce1caf3e7c2cfd59de5c0301ecb747369319dab0 (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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use std::sync::{Arc, Condvar, Mutex};

pub struct StateCallback<T> {
    callback: Arc<Mutex<Option<Box<dyn Fn(T) + Send>>>>,
    observer: Arc<Mutex<Option<Box<dyn Fn() + Send>>>>,
    condition: Arc<(Mutex<bool>, Condvar)>,
}

impl<T> StateCallback<T> {
    // This is used for the Condvar, which requires this kind of construction
    #[allow(clippy::mutex_atomic)]
    pub fn new(cb: Box<dyn Fn(T) + Send>) -> Self {
        Self {
            callback: Arc::new(Mutex::new(Some(cb))),
            observer: Arc::new(Mutex::new(None)),
            condition: Arc::new((Mutex::new(true), Condvar::new())),
        }
    }

    pub fn add_uncloneable_observer(&mut self, obs: Box<dyn Fn() + Send>) {
        let mut opt = self.observer.lock().unwrap();
        if opt.is_some() {
            error!("Replacing an already-set observer.")
        }
        opt.replace(obs);
    }

    pub fn call(&self, rv: T) {
        if let Some(cb) = self.callback.lock().unwrap().take() {
            cb(rv);

            if let Some(obs) = self.observer.lock().unwrap().take() {
                obs();
            }
        }

        let (lock, cvar) = &*self.condition;
        let mut pending = lock.lock().unwrap();
        *pending = false;
        cvar.notify_all();
    }

    pub fn wait(&self) {
        let (lock, cvar) = &*self.condition;
        let _useless_guard = cvar
            .wait_while(lock.lock().unwrap(), |pending| *pending)
            .unwrap();
    }
}

impl<T> Clone for StateCallback<T> {
    fn clone(&self) -> Self {
        Self {
            callback: self.callback.clone(),
            observer: Arc::new(Mutex::new(None)),
            condition: self.condition.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::StateCallback;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Barrier};
    use std::thread;

    #[test]
    fn test_statecallback_is_single_use() {
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = counter.clone();
        let sc = StateCallback::new(Box::new(move |_| {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        }));

        assert_eq!(counter.load(Ordering::SeqCst), 0);
        for _ in 0..10 {
            sc.call(());
            assert_eq!(counter.load(Ordering::SeqCst), 1);
        }

        for _ in 0..10 {
            sc.clone().call(());
            assert_eq!(counter.load(Ordering::SeqCst), 1);
        }
    }

    #[test]
    fn test_statecallback_observer_is_single_use() {
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = counter.clone();
        let mut sc = StateCallback::<()>::new(Box::new(move |_| {}));

        sc.add_uncloneable_observer(Box::new(move || {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        }));

        assert_eq!(counter.load(Ordering::SeqCst), 0);
        for _ in 0..10 {
            sc.call(());
            assert_eq!(counter.load(Ordering::SeqCst), 1);
        }

        for _ in 0..10 {
            sc.clone().call(());
            assert_eq!(counter.load(Ordering::SeqCst), 1);
        }
    }

    #[test]
    fn test_statecallback_observer_only_runs_for_completing_callback() {
        let cb_counter = Arc::new(AtomicUsize::new(0));
        let cb_counter_clone = cb_counter.clone();
        let sc = StateCallback::new(Box::new(move |_| {
            cb_counter_clone.fetch_add(1, Ordering::SeqCst);
        }));

        let obs_counter = Arc::new(AtomicUsize::new(0));

        for _ in 0..10 {
            let obs_counter_clone = obs_counter.clone();
            let mut c = sc.clone();
            c.add_uncloneable_observer(Box::new(move || {
                obs_counter_clone.fetch_add(1, Ordering::SeqCst);
            }));

            c.call(());

            assert_eq!(cb_counter.load(Ordering::SeqCst), 1);
            assert_eq!(obs_counter.load(Ordering::SeqCst), 1);
        }
    }

    #[test]
    #[allow(clippy::redundant_clone)]
    fn test_statecallback_observer_unclonable() {
        let mut sc = StateCallback::<()>::new(Box::new(move |_| {}));
        sc.add_uncloneable_observer(Box::new(move || {}));

        assert!(sc.observer.lock().unwrap().is_some());
        // This is deliberate, to force an extra clone
        assert!(sc.clone().observer.lock().unwrap().is_none());
    }

    #[test]
    fn test_statecallback_wait() {
        let sc = StateCallback::<()>::new(Box::new(move |_| {}));
        let barrier = Arc::new(Barrier::new(2));

        {
            let c = sc.clone();
            let b = barrier.clone();
            thread::spawn(move || {
                b.wait();
                c.call(());
            });
        }

        barrier.wait();
        sc.wait();
    }
}