typestar

Bridging a serial iterator in Rust

par_bridge parallelises any iterator, even one that cannot be split.

use rayon::prelude::*;

fn score(word: &str) -> usize {
    word.chars().filter(|c| "aeiou".contains(*c)).count()
}

fn main() {
    let text = "practice makes the difference between typing and thinking";

    let mut scored: Vec<(usize, &str)> = text
        .split_whitespace()
        .par_bridge()
        .map(|word| (score(word), word))
        .collect();

    scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1)));
    println!("{:?}", &scored[..3]);
    println!("total vowels {}", scored.iter().map(|s| s.0).sum::<usize>());
}

How it works

  1. par_bridge feeds items to the pool as they are produced.
  2. Order is not preserved, so collect into a set or sort after.
  3. It suits lines from a reader or values from a generator.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
482
Tokens
181
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 3 of 3 in Splitting work, step 8 of 9 in Data parallelism with rayon.

← Previous Next →