swc_visit/util/
map.rs

1use std::ptr;
2
3/// Copied from `syntax::ptr::P` of rustc.
4pub trait Map<T> {
5    /// Transform the inner value, consuming `self` and producing a new `P<T>`.
6    ///
7    /// # Memory leak
8    ///
9    /// This will leak `self` if the given closure panics.
10    fn map<F>(self, f: F) -> Self
11    where
12        F: FnOnce(T) -> T;
13}
14
15impl<T> Map<T> for Box<T> {
16    fn map<F>(self, f: F) -> Self
17    where
18        F: FnOnce(T) -> T,
19    {
20        // Leak self in case of panic.
21        // FIXME(eddyb) Use some sort of "free guard" that
22        // only deallocates, without dropping the pointee,
23        // in case the call the `f` below ends in a panic.
24        let p = Box::into_raw(self);
25
26        unsafe {
27            ptr::write(p, f(ptr::read(p)));
28
29            // Recreate self from the raw pointer.
30            Box::from_raw(p)
31        }
32    }
33}