#[must_use]
pub(crate) fn default_width() -> usize {
let cores = std::thread::available_parallelism().map_or(4, std::num::NonZero::get);
(cores * 8).clamp(8, 128).min(descriptor_cap())
}
#[must_use]
pub(crate) fn descriptor_cap() -> usize {
descriptors().map_or(usize::MAX, |limit| (limit / 32).max(1))
}
fn descriptors() -> Option<usize> {
#[cfg(unix)]
{
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } == 0 {
return usize::try_from(limit.rlim_cur).ok();
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_default_width_never_exceeds_the_descriptor_cap() {
let width = default_width();
assert!(width >= 1, "a pool of zero workers is not a pool");
assert!(width <= descriptor_cap(), "{width} exceeds the descriptor cap");
assert!(width <= 128, "{width} exceeds the hard cap");
}
#[test]
fn the_descriptor_cap_shrinks_with_the_limit() {
assert_eq!(descriptor_cap_for(128), 4);
assert_eq!(descriptor_cap_for(256), 8);
assert_eq!(descriptor_cap_for(1024), 32);
}
fn descriptor_cap_for(limit: usize) -> usize {
(limit / 32).max(1)
}
}