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