1// Extracted from the scopeguard crate
2use core::{
3 mem,
4 ops::{Deref, DerefMut},
5 ptr,
6};
78pub struct ScopeGuard<T, F>
9where
10F: FnMut(&mut T),
11{
12 dropfn: F,
13 value: T,
14}
1516#[inline]
17pub fn guard<T, F>(value: T, dropfn: F) -> ScopeGuard<T, F>
18where
19F: FnMut(&mut T),
20{
21 ScopeGuard { dropfn, value }
22}
2324impl<T, F> ScopeGuard<T, F>
25where
26F: FnMut(&mut T),
27{
28#[inline]
29pub fn into_inner(guard: Self) -> T {
30// Cannot move out of Drop-implementing types, so
31 // ptr::read the value and forget the guard.
32unsafe {
33let value = ptr::read(&guard.value);
34// read the closure so that it is dropped, and assign it to a local
35 // variable to ensure that it is only dropped after the guard has
36 // been forgotten. (In case the Drop impl of the closure, or that
37 // of any consumed captured variable, panics).
38let _dropfn = ptr::read(&guard.dropfn);
39 mem::forget(guard);
40 value
41 }
42 }
43}
4445impl<T, F> Deref for ScopeGuard<T, F>
46where
47F: FnMut(&mut T),
48{
49type Target = T;
50#[inline]
51fn deref(&self) -> &T {
52&self.value
53 }
54}
5556impl<T, F> DerefMut for ScopeGuard<T, F>
57where
58F: FnMut(&mut T),
59{
60#[inline]
61fn deref_mut(&mut self) -> &mut T {
62&mut self.value
63 }
64}
6566impl<T, F> Drop for ScopeGuard<T, F>
67where
68F: FnMut(&mut T),
69{
70#[inline]
71fn drop(&mut self) {
72 (self.dropfn)(&mut self.value);
73 }
74}