SHARE
TWEET

Untitled

a guest Aug 23rd, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use rayon::prelude::*;
  2.  
  3. fn par_swap_remove<T, I>(v: &mut Vec<T>, indices: I)
  4. where
  5.     T: Send + Sync + std::fmt::Display,
  6.     I: IntoParallelIterator<Item = usize>,
  7.     I::Iter: IndexedParallelIterator,
  8. {
  9.     struct SafePtr<T: ?Sized>(*mut T);
  10.     unsafe impl<T: ?Sized> Send for SafePtr<T> {}
  11.     unsafe impl<T: ?Sized> Sync for SafePtr<T> {}
  12.  
  13.     // Exercise for the reader to validate the incomming parallel iterator
  14.    
  15.     let len = v.len();
  16.     let ptr = SafePtr(v.as_mut_ptr());
  17.    
  18.     let removed = indices
  19.         .into_par_iter()
  20.         .enumerate()
  21.         .map(move |(i, idx): (usize, usize)| unsafe {
  22.             let SafePtr(ptr) = ptr;
  23.        
  24.             let hole: *mut _ = ptr.add(idx);
  25.             let last = ptr.add(len - i - 1);
  26.             std::ptr::swap(hole, last);
  27.         })
  28.         .count();
  29.    
  30.     v.truncate(len - removed);
  31. }
  32.  
  33. fn main() {
  34.     let mut v = vec![1, 2, 3, 4, 5];
  35.     let indices: Vec<usize> = vec![0, 2, 4];
  36.     par_swap_remove(&mut v, indices);
  37.     println!("{:?}", v);
  38. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top