syntax: implement in-place folding of P<T> and Vec<T>.

This commit is contained in:
Eduard Burtescu 2014-05-19 12:11:06 +03:00
parent 946bb4b10b
commit f8df4fadc8
2 changed files with 17 additions and 4 deletions

View File

@ -35,8 +35,15 @@ pub trait MoveMap<T> {
}
impl<T> MoveMap<T> for Vec<T> {
fn move_map(self, f: |T| -> T) -> Vec<T> {
self.move_iter().map(f).collect()
fn move_map(mut self, f: |T| -> T) -> Vec<T> {
use std::{mem, ptr};
for p in self.mut_iter() {
unsafe {
// FIXME(#5016) this shouldn't need to zero to be safe.
mem::move_val_init(p, f(ptr::read_and_zero(p)));
}
}
self
}
}

View File

@ -31,8 +31,14 @@ impl<T: 'static> P<T> {
f(*self.ptr)
}
pub fn map(self, f: |T| -> T) -> P<T> {
self.and_then(|x| P(f(x)))
pub fn map(mut self, f: |T| -> T) -> P<T> {
use std::{mem, ptr};
unsafe {
let p = &mut *self.ptr;
// FIXME(#5016) this shouldn't need to zero to be safe.
mem::move_val_init(p, f(ptr::read_and_zero(p)));
}
self
}
}