|
| 1 | +use crate::fmt::{self, Debug}; |
1 | 2 | use crate::mem::ManuallyDrop; |
2 | 3 | use crate::ops::{Deref, DerefMut}; |
3 | 4 | use crate::ptr; |
@@ -26,8 +27,10 @@ use crate::ptr; |
26 | 27 | /// } |
27 | 28 | /// ``` |
28 | 29 | #[unstable(feature = "drop_guard", issue = "none")] |
29 | | -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] |
30 | | -pub struct DropGuard<T, F> |
| 30 | +#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 31 | +#[doc(alias = "ScopeGuard")] |
| 32 | +#[doc(alias = "defer")] |
| 33 | +pub struct DropGuard<T, F = fn(T)> |
31 | 34 | where |
32 | 35 | F: FnOnce(T), |
33 | 36 | { |
|
51 | 54 | /// let guard = DropGuard::new(value, |s| println!("{s}")); |
52 | 55 | /// ``` |
53 | 56 | #[unstable(feature = "drop_guard", issue = "none")] |
54 | | - pub fn new(inner: T, f: F) -> Self { |
| 57 | + #[must_use] |
| 58 | + pub const fn new(inner: T, f: F) -> Self { |
55 | 59 | Self { inner: ManuallyDrop::new(inner), f: ManuallyDrop::new(f) } |
56 | 60 | } |
57 | 61 |
|
|
62 | 66 | /// `into_inner` from the `Deref` and `DerefMut` impls. |
63 | 67 | /// |
64 | 68 | /// It is typically preferred to call this function instead of `mem::forget` |
65 | | - /// because it will appropriately de-initialize the closure stored in the |
66 | | - /// `DropGuard` before returning the stored value. |
| 69 | + /// because it will return the stored value and drop variables captured |
| 70 | + /// by the closure instead of leaking their owned resources. |
67 | 71 | /// |
68 | 72 | /// # Example |
69 | 73 | /// |
|
78 | 82 | #[unstable(feature = "drop_guard", issue = "none")] |
79 | 83 | #[inline] |
80 | 84 | pub fn into_inner(guard: Self) -> T { |
81 | | - // Implementation note: this is the same approach that scopeguard takes. |
82 | | - |
83 | 85 | // First we ensure that dropping the guard will not trigger |
84 | 86 | // its destructor |
85 | 87 | let mut guard = ManuallyDrop::new(guard); |
@@ -136,3 +138,14 @@ where |
136 | 138 | f(inner); |
137 | 139 | } |
138 | 140 | } |
| 141 | + |
| 142 | +#[unstable(feature = "drop_guard", issue = "none")] |
| 143 | +impl<T, F> Debug for DropGuard<T, F> |
| 144 | +where |
| 145 | + T: Debug, |
| 146 | + F: FnOnce(T), |
| 147 | +{ |
| 148 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 149 | + fmt::Debug::fmt(&**self, f) |
| 150 | + } |
| 151 | +} |
0 commit comments