1 use smallvec::{Array, SmallVec};
4 pub trait MapInPlace<T>: Sized {
5 fn map_in_place<F>(&mut self, mut f: F)
9 self.flat_map_in_place(|e| Some(f(e)))
12 fn flat_map_in_place<F, I>(&mut self, f: F)
15 I: IntoIterator<Item = T>;
18 impl<T> MapInPlace<T> for Vec<T> {
19 fn flat_map_in_place<F, I>(&mut self, mut f: F)
22 I: IntoIterator<Item = T>,
27 let mut old_len = self.len();
28 self.set_len(0); // make sure we just leak elements in case of panic
30 while read_i < old_len {
31 // move the read_i'th item out of the vector and map it
33 let e = ptr::read(self.as_ptr().add(read_i));
34 let iter = f(e).into_iter();
39 ptr::write(self.as_mut_ptr().add(write_i), e);
42 // If this is reached we ran out of space
43 // in the middle of the vector.
44 // However, the vector is in a valid state here,
45 // so we just do a somewhat inefficient insert.
46 self.set_len(old_len);
47 self.insert(write_i, e);
58 // write_i tracks the number of actually written new items.
59 self.set_len(write_i);
64 impl<T, A: Array<Item = T>> MapInPlace<T> for SmallVec<A> {
65 fn flat_map_in_place<F, I>(&mut self, mut f: F)
68 I: IntoIterator<Item = T>,
73 let mut old_len = self.len();
74 self.set_len(0); // make sure we just leak elements in case of panic
76 while read_i < old_len {
77 // move the read_i'th item out of the vector and map it
79 let e = ptr::read(self.as_ptr().add(read_i));
80 let iter = f(e).into_iter();
85 ptr::write(self.as_mut_ptr().add(write_i), e);
88 // If this is reached we ran out of space
89 // in the middle of the vector.
90 // However, the vector is in a valid state here,
91 // so we just do a somewhat inefficient insert.
92 self.set_len(old_len);
93 self.insert(write_i, e);
104 // write_i tracks the number of actually written new items.
105 self.set_len(write_i);