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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#![feature(alloc)]
use std::rt::heap;
use std::{mem,ptr};
struct Dropper<T> {
ptr: *mut T
}
impl<T> Drop for Dropper<T> {
fn drop(&mut self) {
unsafe {
heap::deallocate(self.ptr as *mut u8, mem::size_of::<T>(), mem::align_of::<T>());
}
}
}
pub fn map_in_place<T, U, F>(x: Box<T>, f: F) -> Box<U> where F: FnOnce(T) -> U {
assert!(mem::size_of::<T>() == mem::size_of::<U>(),
"map_in_place: `T` and `U` are of different sizes");
assert!(mem::align_of::<T>() >= mem::align_of::<U>(),
"map_in_place: alignment of `U` is too large");
unsafe {
let dropper = Dropper {
ptr: mem::transmute(x)
};
let old = ptr::read(dropper.ptr);
let new = f(old);
ptr::write(dropper.ptr as *mut U, new);
let ret: Box<U> = mem::transmute(dropper.ptr);
mem::forget(dropper);
ret
}
}
#[cfg(test)]
mod tests {
use super::map_in_place;
use std::thread;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
#[derive(PartialEq, Debug)]
struct NotCopy(i32);
#[derive(PartialEq, Debug)]
struct NotCopy2(f32);
#[test]
fn smoke() {
assert_eq!(map_in_place(Box::new(NotCopy(1)), |x| NotCopy2(x.0 as f32 + 1.0)),
Box::new(NotCopy2(2.0)));
}
#[test]
fn in_place() {
let x = Box::new(NotCopy(1));
let address_x = &*x as *const NotCopy;
let y = map_in_place(x, |x| NotCopy(x.0 + 1));
let address_y = &*y as *const _;
assert_eq!(address_x, address_y);
}
#[test]
fn destructor_count() {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
struct Foo { _x: u8 }
impl Drop for Foo {
fn drop(&mut self) {
COUNT.fetch_add(1, Ordering::SeqCst);
}
}
struct Bar { _x: u8 }
impl Drop for Bar {
fn drop(&mut self) {
COUNT.fetch_add(10_000, Ordering::SeqCst);
}
}
COUNT.store(0, Ordering::SeqCst);
let value = Box::new(Foo { _x: 1 });
let _ = thread::spawn(|| {
map_in_place(value, |_| -> Bar { panic!() });
}).join();
assert_eq!(COUNT.load(Ordering::SeqCst), 1);
}
#[test]
#[should_panic]
fn mismatching_sizes() {
map_in_place(Box::new(1i32), |_| 0i16);
}
#[test]
#[should_panic]
fn insufficient_alignment() {
map_in_place(Box::new([0u8; 8]), |_| 0u64);
}
}