1use core::{intrinsics, mem, ptr};
23/// This replaces the value behind the `v` unique reference by calling the
4/// relevant function.
5///
6/// If a panic occurs in the `change` closure, the entire process will be aborted.
7#[allow(dead_code)] // keep as illustration and for future use
8#[inline]
9pub(super) fn take_mut<T>(v: &mut T, change: impl FnOnce(T) -> T) {
10 replace(v, |value| (change(value), ()))
11}
1213/// This replaces the value behind the `v` unique reference by calling the
14/// relevant function, and returns a result obtained along the way.
15///
16/// If a panic occurs in the `change` closure, the entire process will be aborted.
17#[inline]
18pub(super) fn replace<T, R>(v: &mut T, change: impl FnOnce(T) -> (T, R)) -> R {
19struct PanicGuard;
20impl Drop for PanicGuard {
21fn drop(&mut self) {
22 intrinsics::abort()
23 }
24 }
25let guard = PanicGuard;
26let value = unsafe { ptr::read(v) };
27let (new_value, ret) = change(value);
28unsafe {
29 ptr::write(v, new_value);
30 }
31 mem::forget(guard);
32 ret
33}