Skip to main content

ulo_conformance_support/
slots.rs

1//! The bound on how many scenarios of one suite hold an environment at once.
2
3use std::num::NonZeroUsize;
4use std::sync::{Condvar, Mutex, OnceLock, PoisonError};
5
6use crate::PARALLEL_VAR;
7use crate::failures::startup_failed;
8
9/// The slots one stamped suite's scenarios share. A suite's stamping macro declares one as a
10/// `static` beside the tests it writes, and each test holds a slot from before its environment
11/// starts until the scenario has returned; an environment or link author names it nowhere. Each
12/// scenario runs on its own test thread, so a slot is waited for by blocking that thread before
13/// the scenario's runtime starts.
14pub struct Slots {
15    held: Mutex<usize>,
16    freed: Condvar,
17}
18
19impl Slots {
20    /// No slot held, a `const fn` for the `static` a suite declares.
21    pub const fn new() -> Self {
22        Slots { held: Mutex::new(0), freed: Condvar::new() }
23    }
24
25    /// A slot when the suite's `declared` bound or the host's [`PARALLEL_VAR`] bounds the
26    /// suite, the smaller when both do, held until the guard drops; `None` otherwise.
27    pub fn hold(&'static self, declared: Option<NonZeroUsize>) -> Option<Slot> {
28        let parallel = bound(declared, host_parallel())?;
29        let mut held = self.held.lock().unwrap_or_else(PoisonError::into_inner);
30        while *held >= parallel.get() {
31            held = self.freed.wait(held).unwrap_or_else(PoisonError::into_inner);
32        }
33        *held += 1;
34        Some(Slot(self))
35    }
36}
37
38impl Default for Slots {
39    fn default() -> Self {
40        Slots::new()
41    }
42}
43
44/// One held slot, given back on drop, a scenario's panic included.
45pub struct Slot(&'static Slots);
46
47impl Drop for Slot {
48    fn drop(&mut self) {
49        *self.0.held.lock().unwrap_or_else(PoisonError::into_inner) -= 1;
50        self.0.freed.notify_one();
51    }
52}
53
54fn bound(declared: Option<NonZeroUsize>, host: Option<NonZeroUsize>) -> Option<NonZeroUsize> {
55    match (declared, host) {
56        (Some(declared), Some(host)) => Some(declared.min(host)),
57        (declared, host) => declared.or(host),
58    }
59}
60
61/// [`PARALLEL_VAR`] as the host set it, read once per test binary: `None` unset or empty.
62fn host_parallel() -> Option<NonZeroUsize> {
63    static HOST: OnceLock<Option<NonZeroUsize>> = OnceLock::new();
64    *HOST.get_or_init(|| match std::env::var(PARALLEL_VAR) {
65        Err(std::env::VarError::NotPresent) => None,
66        Ok(value) if value.trim().is_empty() => None,
67        Ok(value) => match value.trim().parse::<NonZeroUsize>() {
68            Ok(parallel) => Some(parallel),
69            Err(_) => startup_failed(format!("{PARALLEL_VAR} is `{value}`, not a positive integer")),
70        },
71        Err(std::env::VarError::NotUnicode(value)) => startup_failed(format!("{PARALLEL_VAR} is {value:?}, not a positive integer")),
72    })
73}
74
75#[cfg(test)]
76mod tests {
77    use std::num::NonZeroUsize;
78
79    use super::bound;
80
81    fn n(value: usize) -> Option<NonZeroUsize> {
82        NonZeroUsize::new(value)
83    }
84
85    #[test]
86    fn the_smaller_of_two_bounds_applies() {
87        assert_eq!(bound(n(4), n(6)), n(4), "a broker's bound below the host's");
88        assert_eq!(bound(n(6), n(4)), n(4), "a host's bound below the broker's");
89    }
90
91    #[test]
92    fn either_bound_alone_applies() {
93        assert_eq!(bound(n(4), None), n(4), "the broker's bound, the host setting none");
94        assert_eq!(bound(None, n(6)), n(6), "the host's bound, the broker declaring none");
95        assert_eq!(bound(None, None), None, "neither bound");
96    }
97}