af_core/util/
defer.rs

1// Copyright © 2021 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use crate::prelude::*;
8
9/// A deferred function that will be called when dropped.
10#[must_use = "This deferred function runs immediately. Assign it to a guard to run it at the end of the block: `let _guard = defer(…);`"]
11pub struct Deferred<F>(ManuallyDrop<F>)
12where
13  F: FnOnce();
14
15/// Defers a function so that it is called when dropped.
16pub fn defer<F>(func: F) -> Deferred<F>
17where
18  F: FnOnce(),
19{
20  Deferred(ManuallyDrop::new(func))
21}
22
23impl<F> Drop for Deferred<F>
24where
25  F: FnOnce(),
26{
27  fn drop(&mut self) {
28    let func = unsafe { ManuallyDrop::take(&mut self.0) };
29
30    func();
31  }
32}