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
// Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::sync::Arc;
use std::sync::Mutex;

use base::error;

use crate::utils::FailHandle;

/// RingBufferStopCallback wraps a callback. The callback will be invoked when last instance of
/// RingBufferStopCallback and its clones is dropped.
///
/// The callback might not be invoked in certain cases. Don't depend this for safety.
#[derive(Clone)]
pub struct RingBufferStopCallback {
    _inner: Arc<Mutex<RingBufferStopCallbackInner>>,
}

impl RingBufferStopCallback {
    /// Create new callback from closure.
    pub fn new<C: 'static + FnMut() + Send>(cb: C) -> RingBufferStopCallback {
        RingBufferStopCallback {
            _inner: Arc::new(Mutex::new(RingBufferStopCallbackInner {
                callback: Box::new(cb),
            })),
        }
    }
}

struct RingBufferStopCallbackInner {
    callback: Box<dyn FnMut() + Send>,
}

impl Drop for RingBufferStopCallbackInner {
    fn drop(&mut self) {
        (self.callback)();
    }
}

/// Helper function to wrap up a closure with fail handle. The fail handle will be triggered if the
/// closure returns an error.
pub fn fallible_closure<E: std::fmt::Display, C: FnMut() -> Result<(), E> + 'static + Send>(
    fail_handle: Arc<dyn FailHandle>,
    mut callback: C,
) -> impl FnMut() + 'static + Send {
    move || match callback() {
        Ok(()) => {}
        Err(e) => {
            error!("callback failed {}", e);
            fail_handle.fail();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::Mutex;

    use super::*;

    fn task(_: RingBufferStopCallback) {}

    #[test]
    fn simple_raii_callback() {
        let a = Arc::new(Mutex::new(0));
        let ac = a.clone();
        let cb = RingBufferStopCallback::new(move || {
            *ac.lock().unwrap() = 1;
        });
        task(cb.clone());
        task(cb.clone());
        task(cb);
        assert_eq!(*a.lock().unwrap(), 1);
    }
}