archivist_lib/utils.rs
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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Rust equivalent of fbl::AutoCall
/// Automatically invokes a function when it goes
/// out of scope.
pub struct AutoCall<T>
where
T: FnOnce(),
{
val: Option<T>,
}
impl<T: FnOnce()> AutoCall<T> {
pub fn new(val: T) -> AutoCall<T> {
Self { val: Some(val) }
}
}
impl<T: FnOnce()> Drop for AutoCall<T> {
fn drop(&mut self) {
if let Some(value) = self.val.take() {
value();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[fuchsia::test]
fn drop_test() {
let mut called = false;
{
let _call = AutoCall::new(|| {
called = true;
});
}
assert!(called);
}
}