1 use smallvec::{Array, SmallVec};
5 pub trait MapInPlace<T>: Sized {
6 fn map_in_place<F>(&mut self, mut f: F)
10 self.flat_map_in_place(|e| Some(f(e)))
13 fn flat_map_in_place<F, I>(&mut self, f: F)
16 I: IntoIterator<Item = T>;
19 // The implementation of this method is syntactically identical for all the
20 // different vector types.
21 macro_rules! flat_map_in_place {
23 fn flat_map_in_place<F, I>(&mut self, mut f: F)
26 I: IntoIterator<Item = T>,
31 let mut old_len = self.len();
32 self.set_len(0); // make sure we just leak elements in case of panic
34 while read_i < old_len {
35 // move the read_i'th item out of the vector and map it
37 let e = ptr::read(self.as_ptr().add(read_i));
38 let iter = f(e).into_iter();
43 ptr::write(self.as_mut_ptr().add(write_i), e);
46 // If this is reached we ran out of space
47 // in the middle of the vector.
48 // However, the vector is in a valid state here,
49 // so we just do a somewhat inefficient insert.
50 self.set_len(old_len);
51 self.insert(write_i, e);
62 // write_i tracks the number of actually written new items.
63 self.set_len(write_i);
69 impl<T> MapInPlace<T> for Vec<T> {
73 impl<T, A: Array<Item = T>> MapInPlace<T> for SmallVec<A> {
77 impl<T> MapInPlace<T> for ThinVec<T> {