pub unsafe fn replace_map<'a, T, F>(src: &mut T, prod: F)where
F: FnOnce(T) -> T,
Expand description
Replace the value at a mutable memory location with the value produced by the passed in closure.
Does not create an intermediate value, so is more efficient and ergonomic in cases where producing a value to pass to mem::replace is hard.
This is not a totally safe function, it has some curious edge cases. Generally you should only pass in a reference the data behind that reference owns itself. An example may be helpful:
Unsafe Usage:
ⓘ
struct Foo { num: Box<u32> }
struct Bar { foo: Foo }
impl Drop for Bar {
fn drop(&mut self) {
*self.foo.num
}
}
let mut b = Bar { foo: Foo { num: Box::new(123) } };
// replace_map will zero b.foo.num when it reads it and passes
// it to the closure. The closure then panics, leaving b.foo.num
// set to 0, which then causes a null-pointer dereference in b's
// destructors.
unsafe { replace_map(&mut b.foo.num, |_| panic!()); }