Skip to content
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

Implement replace_with, a function similar to the one provided by the take_mut crate. #36186

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/libcore/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,66 @@ pub fn replace<T>(dest: &mut T, mut src: T) -> T {
src
}

/// A guarding type which will abort upon drop.
///
/// This is used for catching unwinding and transforming it into abort.
struct ExitGuard;

impl Drop for ExitGuard {
fn drop(&mut self) {
// To avoid unwinding, we abort the program, which ensures that the destructor of the
// invalidated value isn't runned.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/runned/run/

unsafe { intrinsics::abort(); }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to print a message here, ideally even a backtrace (if RUST_BACKTRACE is set).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Unfortunately, there is no possibility to do so in libcore.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aha. Well, perhaps libstd could do so instead of providing a straight re-export.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah

}
}

/// Temporarily takes ownership of a value at a mutable location, and replace it with a new value
/// based on the old one.
///
/// We move out of reference temporarily, to apply a closure, returning a new value, which is then
/// placed at the original value's location.
///
/// # An important note
///
/// The behavior on panic (or to be more precise, unwinding) is unspecified (but not undefined).
///
/// # Example
///
/// ```
/// use std::mem;
///
/// // Dump some stuff into a box.
/// let mut bx: Box<i32> = Box::new(200);
///
/// // Temporarily steal ownership.
/// mem::replace(&mut bx, |mut owned| {
/// owner = 5;
///
/// // The returned value is placed back in `&mut bx`.
/// Box::new(owner)
/// });
/// ```
#[inline]
#[unstable(feature = "replace_with", issue = "...")]
pub fn replace_with<T, F>(val: &mut T, replace: F)
where F: FnOnce(T) -> T {
// Guard against unwinding. Note that this is critical to safety, to avoid the value behind the
// reference `val` is not dropped twice during unwinding.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of "to avoid the value...is not dropped", maybe " to avoid the value...being dropped" or just "to avoid dropping the value..."

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

your example in the comment uses mem::replace instead of mem::replace_with

let guard = ExitGuard;

unsafe {
// Take out the value behind the pointer.
let old = ptr::read(val);
// Run the closure.
let new = closure(old);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/closure/replace/

// Put the result back.
ptr::write(val, new);
}

// Drop the guard.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/Drop/Don't drop/

mem::forget(guard);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fails with "Use of undeclared type or module mem". I believe this should just be forget(guard);

}

/// Disposes of a value.
///
/// While this does call the argument's implementation of `Drop`, it will not
Expand Down
22 changes: 22 additions & 0 deletions src/libcoretest/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,28 @@ fn test_replace() {
assert!(y.is_some());
}

#[test]
fn test_replace_with() {
let mut x = Some("test".to_string());
replace_with(&mut x, |_| None);
assert!(x.is_none());
}

#[test]
fn test_replace_with_2() {
let mut x = Box::new(21);
replace_with(&mut x, |x| Box::new(x + 5));
assert_eq!(*x, 26);
}

#[test]
fn test_replace_with_3() {
let is_called = Cell::new(false);
let mut x = 2;
replace_with(&mut x, |_| is_called.set(true));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this type error? The lambda never returns an integer.

assert!(is_called.get());
}

#[test]
fn test_transmute_copy() {
assert_eq!(1, unsafe { transmute_copy(&1) });
Expand Down