1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use util::small_vector::SmallVector;
15 pub trait MoveMap<T>: Sized {
16 fn move_map<F>(self, mut f: F) -> Self where F: FnMut(T) -> T {
17 self.move_flat_map(|e| Some(f(e)))
20 fn move_flat_map<F, I>(self, f: F) -> Self
21 where F: FnMut(T) -> I,
22 I: IntoIterator<Item=T>;
25 impl<T> MoveMap<T> for Vec<T> {
26 fn move_flat_map<F, I>(mut self, mut f: F) -> Self
27 where F: FnMut(T) -> I,
28 I: IntoIterator<Item=T>
33 let mut old_len = self.len();
34 self.set_len(0); // make sure we just leak elements in case of panic
36 while read_i < old_len {
37 // move the read_i'th item out of the vector and map it
39 let e = ptr::read(self.get_unchecked(read_i));
40 let mut iter = f(e).into_iter();
43 while let Some(e) = iter.next() {
45 ptr::write(self.get_unchecked_mut(write_i), e);
48 // If this is reached we ran out of space
49 // in the middle of the vector.
50 // However, the vector is in a valid state here,
51 // so we just do a somewhat inefficient insert.
52 self.set_len(old_len);
53 self.insert(write_i, e);
64 // write_i tracks the number of actually written new items.
65 self.set_len(write_i);
72 impl<T> MoveMap<T> for ::ptr::P<[T]> {
73 fn move_flat_map<F, I>(self, f: F) -> Self
74 where F: FnMut(T) -> I,
75 I: IntoIterator<Item=T>
77 ::ptr::P::from_vec(self.into_vec().move_flat_map(f))
81 impl<T> MoveMap<T> for SmallVector<T> {
82 fn move_flat_map<F, I>(mut self, mut f: F) -> Self
83 where F: FnMut(T) -> I,
84 I: IntoIterator<Item=T>
89 let mut old_len = self.len();
90 self.set_len(0); // make sure we just leak elements in case of panic
92 while read_i < old_len {
93 // move the read_i'th item out of the vector and map it
95 let e = ptr::read(self.get_unchecked(read_i));
96 let mut iter = f(e).into_iter();
99 while let Some(e) = iter.next() {
100 if write_i < read_i {
101 ptr::write(self.get_unchecked_mut(write_i), e);
104 // If this is reached we ran out of space
105 // in the middle of the vector.
106 // However, the vector is in a valid state here,
107 // so we just do a somewhat inefficient insert.
108 self.set_len(old_len);
109 self.insert(write_i, e);
111 old_len = self.len();
120 // write_i tracks the number of actually written new items.
121 self.set_len(write_i);