Skip to content

Instantly share code, notes, and snippets.

@d3dave
Last active April 14, 2018 20:16
Show Gist options
  • Save d3dave/fad43bb612445e12d1ea072f628f3b53 to your computer and use it in GitHub Desktop.
Save d3dave/fad43bb612445e12d1ea072f628f3b53 to your computer and use it in GitHub Desktop.
Rust memmap parallel modify
extern crate memmap;
extern crate rayon;
fn main() {
use memmap::MmapMut;
use std::fs::OpenOptions;
use rayon::prelude::*;
let width: u32 = 800;
let height: u32 = 600;
let wls_to_sample: Vec<u32> =
(0..)
.map(|x| 360 + 10 * x)
.take_while(|x| x <= &760)
.collect();
println!("Samples per pixel: {}", wls_to_sample.len());
let f = OpenOptions::new().read(true).write(true).create(true).open("test")
.expect("Error opening file 'test'");
let total_samples = (wls_to_sample.len() as u32) * width * height;
println!("Total samples: {}", total_samples);
f.set_len(4 * total_samples as u64).expect("truncate");
let mut m = unsafe { MmapMut::map_mut(&f) }.expect("mmap");
// slice over samples in memory:
let m_u32 = unsafe {
std::slice::from_raw_parts_mut(m.as_mut_ptr() as *mut u32, total_samples as usize)
};
let ps = (0..height).flat_map(|y| (0..width).map(move |x| (x as u32, y as u32)));
let ss = m_u32.chunks_mut(wls_to_sample.len());
let mut pixs: Vec<((u32, u32), &mut [u32])> = ps.zip(ss).collect();
pixs.par_iter_mut().for_each(|pix| {
let &mut (p, ref mut samples) = pix;
let (x, y) = p;
let sf = sample(x as u32, y as u32);
for (i, wl) in wls_to_sample.iter().enumerate() {
samples[i] = sf(*wl);
}
});
}
fn sample(x: u32, y: u32) -> Box<Fn(u32) -> u32> {
let v = (((x * y) as f32).sqrt()) as u32;
Box::new(move |l| l * v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment