Skip to main content

primase_core/
parallel.rs

1//! The threads a run may use (`core.threads`): [`Threads`] is `primase_foundations::parallel`'s, a run setting the
2//! program states on its pass manager ([`crate::pass::Settings`], [`crate::pass::PassManager::with_settings`]), which
3//! states it in each world it runs. A pass that runs on them declares [`THREADS`] in its
4//! [`crate::pass::Pass::settings`] and reads the world's statement with [`threads`].
5
6pub use primase_foundations::parallel::Threads;
7
8use crate::pass::{RunSetting, Setting, Unstated};
9use crate::{Resource, World};
10
11impl Resource for Threads {
12    const NAME: &'static str = "core.threads";
13}
14
15impl RunSetting for Threads {
16    fn text(&self) -> String {
17        format!("threads {}", self.get())
18    }
19}
20
21/// The thread count as a pass's setting ([`crate::pass::Pass::settings`]).
22pub const THREADS: Setting = Setting::of::<Threads>();
23
24/// The thread count the world `w` states; refused where it states none, since the program states how it runs: no
25/// count stands in for one it did not state.
26pub fn threads(w: &World) -> Result<Threads, Unstated> {
27    w.resource::<Threads>()
28        .copied()
29        .ok_or(Unstated { name: Threads::NAME })
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    /// A world states its thread count, and one that states none is refused by the setting's name.
37    #[test]
38    fn a_world_states_its_threads() {
39        let mut w = World::new();
40        let refused = threads(&w).unwrap_err();
41        assert_eq!(refused, Unstated { name: "core.threads" });
42        assert!(refused.to_string().contains("`core.threads`"), "{refused}");
43        w.insert_resource(Threads::new(6).unwrap());
44        assert_eq!(threads(&w).unwrap().get(), 6);
45        assert_eq!(THREADS.text(&w).as_deref(), Some("threads 6"));
46    }
47}