silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
use std::sync::Mutex;

/// The stack of every thread that walks a syntax tree: the walks recurse once per level, and a
/// tree of `span_lang::MAX_DEPTH` levels fits with room to spare. Pages are only committed
/// when touched.
pub const STACK: usize = 512 << 20;

/// `f` on a scoped thread with a `STACK` stack.
pub fn spawn<'scope, T: Send + 'scope>(
    scope: &'scope std::thread::Scope<'scope, '_>,
    f: impl FnOnce() -> T + Send + 'scope,
) -> std::thread::ScopedJoinHandle<'scope, T> {
    std::thread::Builder::new()
        .stack_size(STACK)
        .spawn_scoped(scope, f)
        .expect("a thread spawns")
}

/// `items.map(f)` on every core, in input order. The heaviest items by `weight` start
/// first, so a large file does not start last and hold the run up alone.
/// `items.map(f)` on every core, in input order, for many items of about one cost each: each
/// worker takes a run of them at once rather than one at a time.
pub fn map_many<T: Send, R: Send>(items: Vec<T>, f: impl Fn(T) -> R + Sync) -> Vec<R> {
    let threads = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1);
    let run = items.len().div_ceil(threads * 4).max(1);
    let mut runs: Vec<Vec<T>> = Vec::new();
    let mut items = items.into_iter().peekable();
    while items.peek().is_some() {
        runs.push(items.by_ref().take(run).collect());
    }
    map(runs, Vec::len, |run| {
        run.into_iter().map(&f).collect::<Vec<R>>()
    })
    .into_iter()
    .flatten()
    .collect()
}

pub fn map<T: Send, R: Send>(
    items: Vec<T>,
    weight: impl Fn(&T) -> usize,
    f: impl Fn(T) -> R + Sync,
) -> Vec<R> {
    let threads = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
        .min(items.len());
    if threads <= 1 {
        return items.into_iter().map(f).collect();
    }
    let mut queue: Vec<(usize, T)> = items.into_iter().enumerate().collect();
    queue.sort_by_key(|(_, item)| std::cmp::Reverse(weight(item)));
    let queue = Mutex::new(queue.into_iter());
    let mut done: Vec<(usize, R)> = std::thread::scope(|scope| {
        let workers: Vec<_> = (0..threads)
            .map(|_| {
                spawn(scope, || {
                    let mut out = Vec::new();
                    loop {
                        let next = queue.lock().expect("work queue").next();
                        let Some((idx, item)) = next else {
                            return out;
                        };
                        out.push((idx, f(item)));
                    }
                })
            })
            .collect();
        workers
            .into_iter()
            .flat_map(|w| w.join().expect("worker thread"))
            .collect()
    });
    done.sort_by_key(|(idx, _)| *idx);
    done.into_iter().map(|(_, r)| r).collect()
}