5 /// This replaces the value behind the `v` unique reference by calling the
8 /// If a panic occurs in the `change` closure, the entire process will be aborted.
9 #[allow(dead_code)] // keep as illustration and for future use
11 pub fn take_mut<T>(v: &mut T, change: impl FnOnce(T) -> T) {
12 replace(v, |value| (change(value), ()))
15 /// This replaces the value behind the `v` unique reference by calling the
16 /// relevant function, and returns a result obtained along the way.
18 /// If a panic occurs in the `change` closure, the entire process will be aborted.
20 pub fn replace<T, R>(v: &mut T, change: impl FnOnce(T) -> (T, R)) -> R {
22 impl Drop for PanicGuard {
27 let guard = PanicGuard;
28 let value = unsafe { ptr::read(v) };
29 let (new_value, ret) = change(value);
31 ptr::write(v, new_value);