core/mem/drop_guard.rs
1use crate::fmt::{self, Debug};
2use crate::marker::Destruct;
3use crate::mem::ManuallyDrop;
4use crate::ops::{Deref, DerefMut};
5
6/// Wrap a value and run a closure when dropped.
7///
8/// This is useful for quickly creating destructors inline.
9///
10/// # Examples
11///
12/// ```rust
13/// # #![allow(unused)]
14/// use std::mem::DropGuard;
15///
16/// {
17/// // Create a new guard around a string that will
18/// // print its value when dropped.
19/// let s = String::from("Chashu likes tuna");
20/// let mut s = DropGuard::new(s, |s| println!("{s}"));
21///
22/// // Modify the string contained in the guard.
23/// s.push_str("!!!");
24///
25/// // The guard will be dropped here, printing:
26/// // "Chashu likes tuna!!!"
27/// }
28/// ```
29#[stable(feature = "drop_guard", since = "1.100.0")]
30#[doc(alias = "ScopeGuard")]
31#[doc(alias = "defer")]
32pub struct DropGuard<#[rustc_assert_variance(covariant)] T, #[rustc_assert_variance(covariant)] F>
33where
34 F: FnOnce(T),
35{
36 inner: ManuallyDrop<T>,
37 f: ManuallyDrop<F>,
38}
39
40impl<T, F> DropGuard<T, F>
41where
42 F: FnOnce(T),
43{
44 /// Create a new instance of `DropGuard`.
45 ///
46 /// # Example
47 ///
48 /// ```rust
49 /// # #![allow(unused)]
50 /// use std::mem::DropGuard;
51 ///
52 /// let value = String::from("Chashu likes tuna");
53 /// let guard = DropGuard::new(value, |s| println!("{s}"));
54 /// ```
55 #[stable(feature = "drop_guard", since = "1.100.0")]
56 #[rustc_const_unstable(feature = "const_drop_guard", issue = "none")]
57 #[must_use]
58 pub const fn new(inner: T, f: F) -> Self {
59 Self { inner: ManuallyDrop::new(inner), f: ManuallyDrop::new(f) }
60 }
61
62 /// Consumes the `DropGuard`, returning the wrapped value.
63 ///
64 /// This will not execute the closure. It is typically preferred to call
65 /// this function instead of `mem::forget` because it will return the stored
66 /// value and drop variables captured by the closure instead of leaking their
67 /// owned resources.
68 ///
69 /// # Example
70 ///
71 /// ```rust
72 /// # #![allow(unused)]
73 /// use std::mem::DropGuard;
74 ///
75 /// let value = String::from("Nori likes chicken");
76 /// let guard = DropGuard::new(value, |s| println!("{s}"));
77 /// assert_eq!(DropGuard::dismiss(guard), "Nori likes chicken");
78 /// ```
79 #[stable(feature = "drop_guard", since = "1.100.0")]
80 #[rustc_const_unstable(feature = "const_drop_guard", issue = "none")]
81 #[inline]
82 pub const fn dismiss(guard: Self) -> T
83 where
84 F: [const] Destruct,
85 {
86 // First we ensure that dropping the guard will not trigger
87 // its destructor
88 let mut guard = ManuallyDrop::new(guard);
89
90 // Next we manually read the stored value from the guard.
91 //
92 // SAFETY: this is safe because we've taken ownership of the guard.
93 let value = unsafe { ManuallyDrop::take(&mut guard.inner) };
94
95 // Finally we drop the stored closure. We do this *after* having read
96 // the value, so that even if the closure's `drop` function panics,
97 // unwinding still tries to drop the value.
98 //
99 // SAFETY: this is safe because we've taken ownership of the guard.
100 unsafe { ManuallyDrop::drop(&mut guard.f) };
101 value
102 }
103}
104
105#[stable(feature = "drop_guard", since = "1.100.0")]
106#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
107const impl<T, F> Deref for DropGuard<T, F>
108where
109 F: FnOnce(T),
110{
111 type Target = T;
112
113 fn deref(&self) -> &T {
114 &self.inner
115 }
116}
117
118#[stable(feature = "drop_guard", since = "1.100.0")]
119#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
120const impl<T, F> DerefMut for DropGuard<T, F>
121where
122 F: FnOnce(T),
123{
124 fn deref_mut(&mut self) -> &mut T {
125 &mut self.inner
126 }
127}
128
129#[stable(feature = "drop_guard", since = "1.100.0")]
130#[rustc_const_unstable(feature = "const_drop_guard", issue = "none")]
131const impl<T, F> Drop for DropGuard<T, F>
132where
133 F: [const] FnOnce(T),
134{
135 fn drop(&mut self) {
136 // SAFETY: `DropGuard` is in the process of being dropped.
137 let inner = unsafe { ManuallyDrop::take(&mut self.inner) };
138
139 // SAFETY: `DropGuard` is in the process of being dropped.
140 let f = unsafe { ManuallyDrop::take(&mut self.f) };
141
142 f(inner);
143 }
144}
145
146#[stable(feature = "drop_guard", since = "1.100.0")]
147impl<T, F> Debug for DropGuard<T, F>
148where
149 T: Debug,
150 F: FnOnce(T),
151{
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 fmt::Debug::fmt(&**self, f)
154 }
155}