defer_heavy/lib.rs
1//! A versatile and easy to use defer statement for Rust. Similar to Go's or Zig's defer.
2//!
3//! This crate is compatible uses `no_std`.
4//! The default features use `alloc`
5//! To disable alloc set default-features to false in cargo.toml.
6//!
7//! This crates provides 6 macros for different use cases of deferment:
8//! 1. `defer!` simple deferment. Will execute when current scope ends.
9//!
10//! 2. `defer_move!` same as `defer!` but moves local variables into the closure.
11//!
12//! 3. `defer_guard!` Returns a guard that causes execution when its scope ends.
13//! - Execution can be canceled or preempted.
14//!
15//! 4. `defer_move_guard!` Same as `defer_guard!` but moves local variables into the closure.
16//!
17//! 5. `defer_arc!` Returns a reference counted guard than can be shared with other threads.
18//! - Execution can be canceled or preempted.
19//! - Closure must be `Send`
20//! - Target must support Arc & AtomicBool.
21//! - Target must support alloc
22//! - can be disabled with `default-features=false` in Cargo.toml
23//!
24//! 6. `defer_move_arc!` Same as `defer_arc!` but moves local variables into the closure.
25//! - All used local variables must be `Send`.
26//!
27//! # Usage
28//!
29//! Add the dependency in your `Cargo.toml`:
30//!
31//! ```toml
32//! [dependencies]
33//! defer-heavy = "0.1.0"
34//! ```
35//!
36//! # Order of execution
37//! Rust guarantees that the order in which the closures are dropped
38//! (and therefore executed) are in reverse order of creation.
39//! This means the last `defer!` in the scope executes first.
40//!
41//!
42
43#![no_std]
44
45#[cfg(target_has_atomic = "8")]
46#[cfg(target_has_atomic = "ptr")]
47#[cfg(feature = "mt")]
48mod mt {
49 extern crate alloc;
50 use crate::DeferGuard;
51 use alloc::sync::Arc;
52 use core::sync::atomic::AtomicBool;
53 use core::sync::atomic::Ordering::SeqCst;
54
55 #[doc(hidden)]
56 #[derive(Debug, Clone)]
57 pub struct ArcDeferGuard<F: FnOnce() + Send>(Arc<ArcDeferGuardInner<F>>);
58
59 #[doc(hidden)]
60 impl<F: FnOnce() + Send> ArcDeferGuard<F> {
61 #[inline(always)]
62 #[must_use]
63 pub fn new(func: F) -> Self {
64 Self(Arc::new(ArcDeferGuardInner(
65 AtomicBool::new(false),
66 Some(func),
67 )))
68 }
69
70 #[inline(always)]
71 pub(crate) fn new_opt(func: Option<F>) -> Self {
72 Self(Arc::new(ArcDeferGuardInner(
73 AtomicBool::new(func.is_none()),
74 func,
75 )))
76 }
77
78 ///
79 /// Utility function to ensure ownership is transferred to a thread/closure.
80 ///
81 #[inline(always)]
82 #[must_use]
83 pub fn own(self) -> Self {
84 self
85 }
86
87 ///
88 /// Downgrade the guard to a non reference counted guard.
89 ///
90 /// # Returns
91 /// * Ok: this was the only reference to the guard. The guard was downgraded.
92 /// * Err: there is still more than 1 reference to the guard.
93 ///
94 #[inline(always)]
95 pub fn try_downgrade(self) -> Result<DeferGuard<F>, Self> {
96 let mut inner = Arc::try_unwrap(self.0).map_err(|a| ArcDeferGuard(a))?;
97 if !inner.0.load(SeqCst) {
98 return Ok(DeferGuard(inner.1.take()));
99 }
100
101 Ok(DeferGuard(None))
102 }
103
104 ///
105 /// Try to call the closure.
106 /// This will succeed if no other references to it exist.
107 /// a return value of OK always indicates that the closure was dropped.
108 ///
109 /// # Returns
110 /// * Ok(true): closure was called
111 /// * Ok(false): closure was not called because it is already canceled.
112 /// * Err: there is still more than 1 reference to the guard.
113 ///
114 ///
115 pub fn try_destroy(self) -> Result<bool, Self> {
116 let inner = Arc::try_unwrap(self.0).map_err(|a| ArcDeferGuard(a))?;
117 //DROP inner which calls the closure if inner.0 (canceled flag) is not true.
118 Ok(!inner.0.load(SeqCst))
119 }
120
121 ///
122 /// Will cancel running the closure, so it cannot be called anymore.
123 /// The closure is dropped once no thread has a reference to it anymore,
124 /// however it is guaranteed to not get called anymore.
125 ///
126 #[inline(always)]
127 pub fn cancel(self) {
128 self.0 .0.store(true, SeqCst)
129 }
130
131 ///
132 /// Will cancel running the closure, so it cannot be called anymore.
133 /// The closure is dropped once no thread has a reference to it anymore,
134 /// however it is guaranteed to not get called anymore.
135 ///
136 #[inline(always)]
137 pub fn cancel_ref(&self) {
138 self.0 .0.store(true, SeqCst)
139 }
140 }
141
142 impl<T: FnOnce() + Send> TryFrom<ArcDeferGuard<T>> for DeferGuard<T> {
143 type Error = ArcDeferGuard<T>;
144
145 fn try_from(value: ArcDeferGuard<T>) -> Result<Self, Self::Error> {
146 value.try_downgrade()
147 }
148 }
149
150 impl<T: FnOnce() + Send> From<DeferGuard<T>> for ArcDeferGuard<T> {
151 fn from(value: DeferGuard<T>) -> Self {
152 value.upgrade()
153 }
154 }
155
156 #[derive(Debug)]
157 struct ArcDeferGuardInner<F: FnOnce() + Send>(AtomicBool, Option<F>);
158
159 impl<F: FnOnce() + Send> Drop for ArcDeferGuardInner<F> {
160 fn drop(&mut self) {
161 if !self.0.load(SeqCst) {
162 if let Some(f) = self.1.take() {
163 f()
164 }
165 }
166 }
167 }
168}
169
170#[doc(hidden)]
171#[derive(Debug)]
172pub struct DeferGuard<F: FnOnce()>(Option<F>);
173
174impl<F: FnOnce()> DeferGuard<F> {
175 #[inline(always)]
176 #[must_use]
177 pub fn new(func: F) -> Self {
178 Self(Some(func))
179 }
180
181 ///
182 /// Upgrade the guard to a reference counted one.
183 /// This function is only available if the closure is `Send`
184 ///
185 /// # Returns
186 /// The reference counted guard.
187 ///
188 #[cfg(target_has_atomic = "8")]
189 #[cfg(target_has_atomic = "ptr")]
190 #[cfg(feature = "mt")]
191 pub fn upgrade(mut self) -> ArcDeferGuard<F>
192 where
193 F: FnOnce() + Send,
194 {
195 ArcDeferGuard::new_opt(self.0.take())
196 }
197
198 ///
199 /// Will call the closure now.
200 ///
201 /// # Returns
202 /// * true: closure was called.
203 /// * false: closure was not called because `cancel_ref` or `destroy_ref` was called previously.
204 ///
205 #[inline(always)]
206 pub fn destroy(mut self) -> bool {
207 self.0.take().map(|f| f()).is_some()
208 }
209
210 ///
211 /// Will call the closure now.
212 /// This drops the closure.
213 ///
214 /// # Returns
215 /// * true: closure was called.
216 /// * false: closure was not called because `cancel_ref` or `destroy_ref` was called previously.
217 ///
218 #[inline(always)]
219 pub fn destroy_ref(&mut self) -> bool {
220 self.0.take().map(|f| f()).is_some()
221 }
222
223 ///
224 /// Will cancel running the closure, so it cannot be called anymore.
225 ///
226 /// # Returns
227 /// * true: closure was dropped and will not be called anymore.
228 /// * false: closure was already dropped previously because `cancel_ref` or `destroy_ref` was called previously.
229 ///
230 #[inline(always)]
231 pub fn cancel(mut self) -> bool {
232 self.0.take().is_some()
233 }
234
235 ///
236 /// Will cancel the closure, so it cannot be called anymore.
237 /// This drops the closure.
238 ///
239 /// # Returns
240 /// * true: closure was dropped and will not be called anymore.
241 /// * false: closure was already dropped previously because `cancel_ref` or `destroy_ref` was called previously.
242 ///
243 #[inline(always)]
244 pub fn cancel_ref(&mut self) -> bool {
245 self.0.take().is_some()
246 }
247}
248
249impl<F: FnOnce()> Drop for DeferGuard<F> {
250 fn drop(&mut self) {
251 if let Some(f) = self.0.take() {
252 f()
253 }
254 }
255}
256
257/// Executes a block of code when the surrounding scope ends.
258///
259/// # Examples
260///
261/// Simplest example:
262///
263/// ```rust
264/// use defer_heavy::defer;
265///
266/// fn test() {
267/// defer! { println!("Second"); }
268/// println!("First");
269/// }
270/// ```
271///
272/// Multiple statements:
273///
274/// ```rust
275/// use defer_heavy::defer;
276///
277/// fn test() {
278/// defer! {
279/// println!("Second");
280/// println!("Third");
281/// }
282/// println!("First");
283/// }
284/// ```
285///
286/// In Go, the `defer` code runs when the function exits. In this Rust
287/// implementation, however, the code runs when the surrounding scope ends –
288/// this makes it possible to use `defer` inside loops:
289///
290/// ```rust
291/// use defer_heavy::defer;
292///
293/// fn test() {
294/// defer! { println!("End"); }
295/// println!("Before");
296///
297/// for i in 0..2 {
298/// defer! { println!("Defer {}", i); }
299/// println!("Loop {}", i);
300/// }
301///
302/// println!("After");
303/// }
304/// ```
305#[macro_export]
306macro_rules! defer {
307 ( $($tt:tt)* ) => {
308 let _deferred = $crate::DeferGuard::new(|| { $($tt)* });
309 };
310}
311
312/// Executes a block of code when the surrounding scope ends.
313/// This macro moves all captured variables.
314///
315/// # Examples
316///
317/// ```rust
318/// use defer_heavy::defer_move;
319///
320/// fn test() {
321/// let n = 1;
322/// defer_move! { println!("Second n={}", n); }
323/// println!("First");
324/// }
325/// ```
326#[macro_export]
327macro_rules! defer_move {
328 ( $($tt:tt)* ) => {
329 let _deferred = $crate::DeferGuard::new(move || { $($tt)* });
330 };
331}
332
333/// Executes a block of code when the surrounding scope ends.
334///
335/// The macro returns a guard that defines the scope of the deferment.
336/// The guard can be used to immediately execute the deferred closure or cancel it and
337/// prevent execution of the closure altogether
338///
339/// # Examples
340///
341/// ```rust
342/// use defer_heavy::defer_guard;
343///
344/// fn test() {
345///
346/// let defer1 = defer_guard! { unreachable!("Wont be executed"); };
347/// let defer2 = defer_guard! { println!("Second"); };
348///
349/// println!("First");
350/// defer1.cancel();
351/// }
352/// ```
353///
354/// ```rust
355/// use defer_heavy::defer_guard;
356///
357/// fn test() {
358///
359/// let defer1 = defer_guard! { unreachable!("Wont be executed"); };
360/// let defer2 = defer_guard! { println!("Fourth"); };
361/// let defer3 = defer_guard! { println!("Second"); };
362///
363/// println!("First");
364/// defer3.destroy();
365/// println!("Third");
366/// defer1.cancel();
367/// }
368/// ```
369///
370#[macro_export]
371macro_rules! defer_guard {
372 ( $($tt:tt)* ) => {
373 $crate::DeferGuard::new(|| { $($tt)* })
374 };
375}
376
377/// Executes a block of code when the surrounding scope ends.
378///
379/// The macro returns a guard that defines the scope of the deferment.
380/// The guard can be used to immediately execute the deferred closure or cancel it and
381/// prevent execution of the closure altogether
382///
383/// # Examples
384///
385/// ```rust
386/// use defer_heavy::defer_move_guard;
387///
388/// fn test() {
389/// let n = 1;
390/// let defer1 = defer_move_guard! { unreachable!("Wont be executed {}", n); };
391/// let n = 2;
392/// let defer2 = defer_move_guard! { println!("Second {}", n); };
393///
394/// println!("First");
395/// defer1.cancel();
396/// }
397/// ```
398/// Prints:
399/// ```text
400/// First
401/// Second 2
402/// ```
403///
404/// ```rust
405/// use defer_heavy::defer_move_guard;
406///
407/// fn test() {
408///
409/// let n = 1;
410/// let defer1 = defer_move_guard! { unreachable!("Wont be executed {}", n); };
411/// let n = 2;
412/// let defer2 = defer_move_guard! { println!("Fourth {}", n); };
413/// let n = 3;
414/// let defer3 = defer_move_guard! { println!("Second {}", n); };
415///
416/// println!("First");
417/// defer3.destroy(); //Same as drop(defer3);
418/// println!("Third");
419/// defer1.cancel();
420/// }
421/// ```
422/// Prints:
423/// ```text
424/// First
425/// Second 3
426/// Third
427/// Fourth 2
428/// ```
429///
430/// ```rust
431///
432#[macro_export]
433macro_rules! defer_move_guard {
434 ( $($tt:tt)* ) => {
435 $crate::DeferGuard::new(move || { $($tt)* })
436 };
437}
438
439#[cfg(target_has_atomic = "8")]
440#[cfg(target_has_atomic = "ptr")]
441#[cfg(feature = "mt")]
442pub use mt::ArcDeferGuard;
443
444/// Executes a block of code when the surrounding scope ends.
445///
446/// The macro returns a guard that defines the scope of the deferment.
447/// The guard can be shared with other threads, and it will only execute the block of code when
448/// no more references to the guard exist.
449///
450/// The code closure must be 'Send'.
451///
452///
453/// # Examples
454/// ```rust
455/// use std::thread;
456/// use std::time::Duration;
457/// use defer_heavy::defer_arc;
458///
459/// pub fn test() {
460/// let deferred = defer_arc! { println!("Executed in {:?}", thread::current().id());};
461/// println!("Main thread {:?}", thread::current().id());
462/// let th;
463/// {
464/// let deferred = deferred.clone();
465/// th = thread::spawn(move ||{
466/// println!("Spawned thread {:?}", thread::current().id());
467/// let _deferred = deferred.own();
468/// thread::sleep(Duration::from_millis(2000)); //SIMULATE work
469/// });
470/// }
471/// thread::sleep(Duration::from_millis(2000)); //SIMULATE WORK
472/// drop(deferred);
473/// th.join().unwrap();
474/// }
475/// ```
476/// Prints:
477/// ```text
478/// Main thread Thread(1)
479/// Spawned thread Thread(2)
480/// "Executed in Thread(1)" or "Executed in Thread(2)"
481/// ```
482///
483#[cfg(target_has_atomic = "8")]
484#[cfg(target_has_atomic = "ptr")]
485#[cfg(feature = "mt")]
486#[macro_export]
487macro_rules! defer_arc {
488 ( $($tt:tt)* ) => {
489 $crate::ArcDeferGuard::new(|| { $($tt)* })
490 };
491}
492
493/// Executes a block of code when the surrounding scope ends.
494///
495/// The macro returns a guard that defines the scope of the deferment.
496/// The guard can be shared with other threads, and it will only execute the block of code when
497/// no more references to the guard exist.
498///
499/// The code closure must be 'Send'.
500/// The closure moves all used variables. Each used variable must be 'Send' or the closure won't be 'Send'.
501///
502/// # Examples
503/// ```rust
504/// use std::thread;
505/// use std::time::Duration;
506/// use defer_heavy::defer_move_arc;
507///
508/// pub fn test() {
509/// let v = 1;
510/// let deferred = defer_move_arc! { println!("Executed {} in {:?}", v, thread::current().id());};
511/// println!("Main thread {:?}", thread::current().id());
512/// let th;
513/// {
514/// let deferred = deferred.clone();
515/// th = thread::spawn(move ||{
516/// println!("Spawned thread {:?}", thread::current().id());
517/// let _deferred = deferred.own();
518/// thread::sleep(Duration::from_millis(2000)); //SIMULATE work
519/// });
520/// }
521/// thread::sleep(Duration::from_millis(2000)); //SIMULATE WORK
522/// drop(deferred);
523/// th.join().unwrap();
524/// }
525/// ```
526/// Prints:
527/// ```text
528/// Main thread Thread(1)
529/// Spawned thread Thread(2)
530/// "Executed in Thread(1)" or "Executed in Thread(2)"
531/// ```
532///
533#[cfg(target_has_atomic = "8")]
534#[cfg(target_has_atomic = "ptr")]
535#[cfg(feature = "mt")]
536#[macro_export]
537macro_rules! defer_move_arc {
538 ( $($tt:tt)* ) => {
539 $crate::ArcDeferGuard::new(move || { $($tt)* })
540 };
541}