-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Add core::mem::DropGuard
#144236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yoshuawuyts
wants to merge
13
commits into
rust-lang:master
Choose a base branch
from
yoshuawuyts:drop-guard
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+207
−0
Open
Add core::mem::DropGuard
#144236
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
bb82763
Add `core::mem::DropGuard`
yoshuawuyts dc5f453
Fix CI for drop_guard
yoshuawuyts 7094637
fix CI
yoshuawuyts c3cf598
fix all tidy lints
yoshuawuyts 394cc58
fix tidy link
yoshuawuyts 7b4d181
add first batch of feedback from review
yoshuawuyts 8fd3010
Add second batch of feedback from review
yoshuawuyts d8afe56
add third batch of feedback from review
yoshuawuyts 3888a95
fix failing test
yoshuawuyts a3b2450
Update library/core/src/mem/drop_guard.rs
yoshuawuyts e2aae53
fix doctests
yoshuawuyts a77b308
Implement changes from T-Libs-API review
yoshuawuyts e98ede4
fix tidy lint
yoshuawuyts File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
use crate::fmt::{self, Debug}; | ||
use crate::mem::ManuallyDrop; | ||
use crate::ops::{Deref, DerefMut}; | ||
|
||
/// Wrap a value and run a closure when dropped. | ||
/// | ||
/// This is useful for quickly creating desructors inline. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ```rust | ||
/// # #![allow(unused)] | ||
/// #![feature(drop_guard)] | ||
/// | ||
/// use std::mem::DropGuard; | ||
/// | ||
/// { | ||
/// // Create a new guard around a string that will | ||
/// // print its value when dropped. | ||
/// let s = String::from("Chashu likes tuna"); | ||
/// let mut s = DropGuard::new(s, |s| println!("{s}")); | ||
/// | ||
/// // Modify the string contained in the guard. | ||
/// s.push_str("!!!"); | ||
/// | ||
/// // The guard will be dropped here, printing: | ||
/// // "Chashu likes tuna!!!" | ||
/// } | ||
/// ``` | ||
#[unstable(feature = "drop_guard", issue = "144426")] | ||
#[doc(alias = "ScopeGuard")] | ||
#[doc(alias = "defer")] | ||
pub struct DropGuard<T, F> | ||
where | ||
F: FnOnce(T), | ||
{ | ||
inner: ManuallyDrop<T>, | ||
f: ManuallyDrop<F>, | ||
} | ||
|
||
impl<T, F> DropGuard<T, F> | ||
where | ||
F: FnOnce(T), | ||
{ | ||
/// Create a new instance of `DropGuard`. | ||
/// | ||
/// # Example | ||
/// | ||
/// ```rust | ||
/// # #![allow(unused)] | ||
/// #![feature(drop_guard)] | ||
/// | ||
/// use std::mem::DropGuard; | ||
/// | ||
/// let value = String::from("Chashu likes tuna"); | ||
/// let guard = DropGuard::new(value, |s| println!("{s}")); | ||
/// ``` | ||
#[unstable(feature = "drop_guard", issue = "144426")] | ||
#[must_use] | ||
pub const fn new(inner: T, f: F) -> Self { | ||
Self { inner: ManuallyDrop::new(inner), f: ManuallyDrop::new(f) } | ||
} | ||
|
||
/// Consumes the `DropGuard`, returning the wrapped value. | ||
/// | ||
/// This will not execute the closure. This is implemented as an associated | ||
/// function to prevent any potential conflicts with any other methods called | ||
/// `into_inner` from the `Deref` and `DerefMut` impls. | ||
/// | ||
/// It is typically preferred to call this function instead of `mem::forget` | ||
/// because it will return the stored value and drop variables captured | ||
/// by the closure instead of leaking their owned resources. | ||
/// | ||
/// # Example | ||
/// | ||
/// ```rust | ||
/// # #![allow(unused)] | ||
/// #![feature(drop_guard)] | ||
/// | ||
/// use std::mem::DropGuard; | ||
/// | ||
/// let value = String::from("Nori likes chicken"); | ||
/// let guard = DropGuard::new(value, |s| println!("{s}")); | ||
/// assert_eq!(DropGuard::into_inner(guard), "Nori likes chicken"); | ||
/// ``` | ||
#[unstable(feature = "drop_guard", issue = "144426")] | ||
#[inline] | ||
pub fn into_inner(guard: Self) -> T { | ||
// First we ensure that dropping the guard will not trigger | ||
// its destructor | ||
let mut guard = ManuallyDrop::new(guard); | ||
|
||
// Next we manually read the stored value from the guard. | ||
// | ||
// SAFETY: this is safe because we've taken ownership of the guard. | ||
let value = unsafe { ManuallyDrop::take(&mut guard.inner) }; | ||
|
||
// Finally we drop the stored closure. We do this *after* having read | ||
// the value, so that even if the closure's `drop` function panics, | ||
// unwinding still tries to drop the value. | ||
// | ||
// SAFETY: this is safe because we've taken ownership of the guard. | ||
unsafe { ManuallyDrop::drop(&mut guard.f) }; | ||
value | ||
} | ||
} | ||
|
||
#[unstable(feature = "drop_guard", issue = "144426")] | ||
impl<T, F> Deref for DropGuard<T, F> | ||
where | ||
F: FnOnce(T), | ||
{ | ||
type Target = T; | ||
|
||
fn deref(&self) -> &T { | ||
&*self.inner | ||
} | ||
} | ||
|
||
#[unstable(feature = "drop_guard", issue = "144426")] | ||
impl<T, F> DerefMut for DropGuard<T, F> | ||
where | ||
F: FnOnce(T), | ||
{ | ||
fn deref_mut(&mut self) -> &mut T { | ||
&mut *self.inner | ||
} | ||
} | ||
|
||
#[unstable(feature = "drop_guard", issue = "144426")] | ||
impl<T, F> Drop for DropGuard<T, F> | ||
where | ||
F: FnOnce(T), | ||
{ | ||
fn drop(&mut self) { | ||
// SAFETY: `DropGuard` is in the process of being dropped. | ||
let inner = unsafe { ManuallyDrop::take(&mut self.inner) }; | ||
|
||
// SAFETY: `DropGuard` is in the process of being dropped. | ||
let f = unsafe { ManuallyDrop::take(&mut self.f) }; | ||
|
||
f(inner); | ||
} | ||
} | ||
|
||
#[unstable(feature = "drop_guard", issue = "144426")] | ||
impl<T, F> Debug for DropGuard<T, F> | ||
where | ||
T: Debug, | ||
F: FnOnce(T), | ||
{ | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
fmt::Debug::fmt(&**self, f) | ||
yoshuawuyts marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.