parallel/
parallel.rs

1// To analyze events in parallel we need:
2// - Add `rayon` as a dependency in your `Cargo.toml` (cargo add rayon)
3// - Add `midasio` as a dependency with the `rayon` feature enabled (cargo add midasio --features rayon)
4// - Bring rayon's prelude into scope (use rayon::prelude::*)
5
6#[cfg(feature = "rayon")]
7use rayon::prelude::*;
8
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let contents = std::fs::read("example.mid")?;
11    // Note that if your MIDAS file is compressed, you will need to decompress
12    // its contents (using an external crate) before parsing it.
13    let file_view = midasio::FileView::try_from_bytes(&contents)?;
14
15    // We want to process all events with an ID of 1. This can be any complex
16    // operation, e.g. reconstructing a vertex
17    let mut results = Vec::new();
18
19    #[cfg(feature = "rayon")]
20    results.par_extend(
21        file_view
22            .into_par_iter()
23            .filter(|event| event.id() == 1)
24            .map(|event| {
25                // This is a placeholder for a complex operation
26                event.into_iter().count()
27            }),
28    );
29    // The equivalent non-parallel version would be:
30    #[cfg(not(feature = "rayon"))]
31    results.extend(
32        file_view
33            .into_iter()
34            .filter(|event| event.id() == 1)
35            .map(|event| event.into_iter().count()),
36    );
37
38    Ok(())
39}