ulo_conformance_support/
slots.rs1use std::num::NonZeroUsize;
4use std::sync::{Condvar, Mutex, OnceLock, PoisonError};
5
6use crate::PARALLEL_VAR;
7use crate::failures::startup_failed;
8
9pub struct Slots {
15 held: Mutex<usize>,
16 freed: Condvar,
17}
18
19impl Slots {
20 pub const fn new() -> Self {
22 Slots { held: Mutex::new(0), freed: Condvar::new() }
23 }
24
25 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
44pub 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
61fn 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}