1 // Copyright 2019 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use crate::utils::FailHandle;
6 use base::error;
7 use std::sync::{Arc, Mutex};
8 
9 /// RingBufferStopCallback wraps a callback. The callback will be invoked when last instance of
10 /// RingBufferStopCallback and its clones is dropped.
11 ///
12 /// The callback might not be invoked in certain cases. Don't depend this for safety.
13 #[derive(Clone)]
14 pub struct RingBufferStopCallback {
15     inner: Arc<Mutex<RingBufferStopCallbackInner>>,
16 }
17 
18 impl RingBufferStopCallback {
19     /// Create new callback from closure.
new<C: 'static + FnMut() + Send>(cb: C) -> RingBufferStopCallback20     pub fn new<C: 'static + FnMut() + Send>(cb: C) -> RingBufferStopCallback {
21         RingBufferStopCallback {
22             inner: Arc::new(Mutex::new(RingBufferStopCallbackInner {
23                 callback: Box::new(cb),
24             })),
25         }
26     }
27 }
28 
29 struct RingBufferStopCallbackInner {
30     callback: Box<dyn FnMut() + Send>,
31 }
32 
33 impl Drop for RingBufferStopCallbackInner {
drop(&mut self)34     fn drop(&mut self) {
35         (self.callback)();
36     }
37 }
38 
39 /// Helper function to wrap up a closure with fail handle. The fail handle will be triggered if the
40 /// closure returns an error.
fallible_closure<E: std::fmt::Display, C: FnMut() -> Result<(), E> + 'static + Send>( fail_handle: Arc<dyn FailHandle>, mut callback: C, ) -> impl FnMut() + 'static + Send41 pub fn fallible_closure<E: std::fmt::Display, C: FnMut() -> Result<(), E> + 'static + Send>(
42     fail_handle: Arc<dyn FailHandle>,
43     mut callback: C,
44 ) -> impl FnMut() + 'static + Send {
45     move || match callback() {
46         Ok(()) => {}
47         Err(e) => {
48             error!("callback failed {}", e);
49             fail_handle.fail();
50         }
51     }
52 }
53 
54 #[cfg(test)]
55 mod tests {
56     use super::*;
57     use std::sync::{Arc, Mutex};
58 
task(_: RingBufferStopCallback)59     fn task(_: RingBufferStopCallback) {}
60 
61     #[test]
simple_raii_callback()62     fn simple_raii_callback() {
63         let a = Arc::new(Mutex::new(0));
64         let ac = a.clone();
65         let cb = RingBufferStopCallback::new(move || {
66             *ac.lock().unwrap() = 1;
67         });
68         task(cb.clone());
69         task(cb.clone());
70         task(cb);
71         assert_eq!(*a.lock().unwrap(), 1);
72     }
73 }
74