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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
//! Subroutines to help implementers of `TypeFoldable` avoid unnecessary heap allocations.

use std::marker::PhantomData;
use std::{mem, ptr};

fn is_zst<T>() -> bool {
    mem::size_of::<T>() == 0
}

fn is_layout_identical<T, U>() -> bool {
    mem::size_of::<T>() == mem::size_of::<U>() && mem::align_of::<T>() == mem::align_of::<U>()
}

/// Maps a `Box<T>` to a `Box<U>`, reusing the underlying storage if possible.
pub(super) fn fallible_map_box<T, U, E>(
    b: Box<T>,
    map: impl FnOnce(T) -> Result<U, E>,
) -> Result<Box<U>, E> {
    // This optimization is only valid when `T` and `U` have the same size/alignment and is not
    // useful for ZSTs.
    if !is_layout_identical::<T, U>() || is_zst::<T>() {
        return map(*b).map(Box::new);
    }

    let raw = Box::into_raw(b);
    unsafe {
        let val = ptr::read(raw);

        // Box<T> -> Box<MaybeUninit<U>>
        let mut raw: Box<mem::MaybeUninit<U>> = Box::from_raw(raw.cast());

        // If `map` panics or returns an error, `raw` will free the memory associated with `b`, but
        // not drop the boxed value itself since it is wrapped in `MaybeUninit`. This is what we
        // want since the boxed value was moved into `map`.
        let mapped_val = map(val)?;
        ptr::write(raw.as_mut_ptr(), mapped_val);

        // Box<MaybeUninit<U>> -> Box<U>
        Ok(Box::from_raw(Box::into_raw(raw).cast()))
    }
}

/// Maps a `Vec<T>` to a `Vec<U>`, reusing the underlying storage if possible.
pub(super) fn fallible_map_vec<T, U, E>(
    vec: Vec<T>,
    mut map: impl FnMut(T) -> Result<U, E>,
) -> Result<Vec<U>, E> {
    // This optimization is only valid when `T` and `U` have the same size/alignment and is not
    // useful for ZSTs.
    if !is_layout_identical::<T, U>() || is_zst::<T>() {
        return vec.into_iter().map(map).collect();
    }

    let mut vec = VecMappedInPlace::<T, U>::new(vec);

    unsafe {
        for i in 0..vec.len {
            let place = vec.ptr.add(i);
            let val = ptr::read(place);

            // Set `map_in_progress` so the drop impl for `VecMappedInPlace` can handle the other
            // elements correctly in case `map` panics or returns an error.
            vec.map_in_progress = i;
            let mapped_val = map(val)?;

            ptr::write(place as *mut U, mapped_val);
        }

        Ok(vec.finish())
    }
}

/// Takes ownership of a `Vec` that is being mapped in place, cleaning up if the map fails.
struct VecMappedInPlace<T, U> {
    ptr: *mut T,
    len: usize,
    cap: usize,

    map_in_progress: usize,
    _elem_tys: PhantomData<(T, U)>,
}

impl<T, U> VecMappedInPlace<T, U> {
    fn new(mut vec: Vec<T>) -> Self {
        assert!(is_layout_identical::<T, U>());

        // FIXME: This is just `Vec::into_raw_parts`. Use that instead when it is stabilized.
        let ptr = vec.as_mut_ptr();
        let len = vec.len();
        let cap = vec.capacity();
        mem::forget(vec);

        VecMappedInPlace {
            ptr,
            len,
            cap,

            map_in_progress: 0,
            _elem_tys: PhantomData,
        }
    }

    /// Converts back into a `Vec` once the map is complete.
    unsafe fn finish(self) -> Vec<U> {
        let this = mem::ManuallyDrop::new(self);
        Vec::from_raw_parts(this.ptr as *mut U, this.len, this.cap)
    }
}

/// `VecMappedInPlace` drops everything but the element that was passed to `map` when it panicked or
/// returned an error. Everything before that index in the vector has type `U` (it has been mapped)
/// and everything after it has type `T` (it has not been mapped).
///
/// ```text
///  mapped
///  |      not yet mapped
///  |----| |-----|
/// [UUUU UxTT TTTT]
///        ^
///    `map_in_progress` (not dropped)
/// ```
impl<T, U> Drop for VecMappedInPlace<T, U> {
    fn drop(&mut self) {
        // Drop mapped elements of type `U`.
        for i in 0..self.map_in_progress {
            unsafe {
                ptr::drop_in_place(self.ptr.add(i) as *mut U);
            }
        }

        // Drop unmapped elements of type `T`.
        for i in (self.map_in_progress + 1)..self.len {
            unsafe {
                ptr::drop_in_place(self.ptr.add(i));
            }
        }

        // Free the underlying storage for the `Vec`.
        // `len` is 0 because the elements were handled above.
        unsafe {
            Vec::from_raw_parts(self.ptr, 0, self.cap);
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fmt;
    use std::sync::{Arc, Mutex};

    /// A wrapper around `T` that records when it is dropped.
    struct RecordDrop<T: fmt::Display> {
        id: T,
        drops: Arc<Mutex<Vec<String>>>,
    }

    impl<T: fmt::Display> RecordDrop<T> {
        fn new(id: T, drops: &Arc<Mutex<Vec<String>>>) -> Self {
            RecordDrop {
                id,
                drops: drops.clone(),
            }
        }
    }

    impl RecordDrop<u8> {
        fn map_to_char(self) -> RecordDrop<char> {
            let this = std::mem::ManuallyDrop::new(self);
            RecordDrop {
                id: (this.id + b'A') as char,
                drops: this.drops.clone(),
            }
        }
    }

    impl<T: fmt::Display> Drop for RecordDrop<T> {
        fn drop(&mut self) {
            self.drops.lock().unwrap().push(format!("{}", self.id));
        }
    }

    #[test]
    fn vec_no_cleanup_after_success() {
        let drops = Arc::new(Mutex::new(Vec::new()));
        let to_fold = (0u8..5).map(|i| RecordDrop::new(i, &drops)).collect();

        let res: Result<_, ()> = super::fallible_map_vec(to_fold, |x| Ok(x.map_to_char()));

        assert!(res.is_ok());
        assert!(drops.lock().unwrap().is_empty());
    }

    #[test]
    fn vec_cleanup_after_panic() {
        let drops = Arc::new(Mutex::new(Vec::new()));
        let to_fold = (0u8..5).map(|i| RecordDrop::new(i, &drops)).collect();

        let res = std::panic::catch_unwind(|| {
            let _: Result<_, ()> = super::fallible_map_vec(to_fold, |x| {
                if x.id == 3 {
                    panic!();
                }

                Ok(x.map_to_char())
            });
        });

        assert!(res.is_err());
        assert_eq!(*drops.lock().unwrap(), &["3", "A", "B", "C", "4"]);
    }

    #[test]
    fn vec_cleanup_after_early_return() {
        let drops = Arc::new(Mutex::new(Vec::new()));
        let to_fold = (0u8..5).map(|i| RecordDrop::new(i, &drops)).collect();

        let res = super::fallible_map_vec(to_fold, |x| {
            if x.id == 2 {
                return Err(());
            }

            Ok(x.map_to_char())
        });

        assert!(res.is_err());
        assert_eq!(*drops.lock().unwrap(), &["2", "A", "B", "3", "4"]);
    }

    #[test]
    fn box_no_cleanup_after_success() {
        let drops = Arc::new(Mutex::new(Vec::new()));
        let to_fold = Box::new(RecordDrop::new(0, &drops));

        let res: Result<Box<_>, ()> = super::fallible_map_box(to_fold, |x| Ok(x.map_to_char()));

        assert!(res.is_ok());
        assert!(drops.lock().unwrap().is_empty());
    }

    #[test]
    fn box_cleanup_after_panic() {
        let drops = Arc::new(Mutex::new(Vec::new()));
        let to_fold = Box::new(RecordDrop::new(0, &drops));

        let res = std::panic::catch_unwind(|| {
            let _: Result<Box<()>, ()> = super::fallible_map_box(to_fold, |_| panic!());
        });

        assert!(res.is_err());
        assert_eq!(*drops.lock().unwrap(), &["0"]);
    }

    #[test]
    fn box_cleanup_after_early_return() {
        let drops = Arc::new(Mutex::new(Vec::new()));
        let to_fold = Box::new(RecordDrop::new(0, &drops));

        let res: Result<Box<()>, _> = super::fallible_map_box(to_fold, |_| Err(()));

        assert!(res.is_err());
        assert_eq!(*drops.lock().unwrap(), &["0"]);
    }
}