pubhubs/misc/defer.rs
1//! Implementation of [`defer`]
2
3/// Defers the execution of `f` until the return value is dropped.
4#[must_use]
5pub fn defer(f: impl FnOnce()) -> impl Drop {
6 Deferred { callback: Some(f) }
7}
8
9struct Deferred<F: FnOnce()> {
10 callback: Option<F>,
11}
12
13impl<F: FnOnce()> Drop for Deferred<F> {
14 fn drop(&mut self) {
15 let f = self
16 .callback
17 .take()
18 .expect("drop called twice, or `Deferred` initialized with `None`");
19 f();
20 }
21}