use crate::tiles_error::{Result, TilesError};
const RESERVED_FILES: u64 = 128;
pub(crate) fn ensure_open_files(runs: usize) -> Result<()> {
let need = runs as u64 + RESERVED_FILES;
let limit = raise_open_file_limit(need);
check(runs, limit)
}
fn check(runs: usize, limit: u64) -> Result<()> {
let need = runs as u64 + RESERVED_FILES;
if limit >= need {
Ok(())
} else {
Err(TilesError::TooManyRuns { runs, limit, need })
}
}
#[cfg(unix)]
#[allow(
unsafe_code,
reason = "libc getrlimit and setrlimit on local structs; each unsafe block has a SAFETY comment"
)]
fn raise_open_file_limit(want: u64) -> u64 {
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } != 0 {
return 256;
}
let target = want.min(limit.rlim_max);
if limit.rlim_cur < target {
let raised = libc::rlimit {
rlim_cur: target,
rlim_max: limit.rlim_max,
};
if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const raised) } == 0 {
return target;
}
}
limit.rlim_cur
}
#[cfg(not(unix))]
fn raise_open_file_limit(_want: u64) -> u64 {
u64::MAX
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_limit_below_the_runs_stops_the_merge_with_the_numbers() {
match check(5000, 1024).expect_err("5000 runs do not fit in 1024 files") {
TilesError::TooManyRuns { runs, limit, need } => {
assert_eq!((runs, limit, need), (5000, 1024, 5128));
}
other => panic!("wrong error: {other}"),
}
}
#[test]
fn a_limit_with_room_for_the_runs_and_the_reserve_passes() {
assert!(check(100, 1024).is_ok());
assert!(check(896, 1024).is_ok(), "896 + 128 = 1024 fits exactly");
assert!(check(897, 1024).is_err());
}
#[cfg(unix)]
#[test]
fn the_soft_limit_is_raised_when_the_hard_limit_allows_it() {
ensure_open_files(3000 - RESERVED_FILES as usize).expect("raised to 3000");
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
#[allow(unsafe_code, reason = "reads the limit the test just raised")]
let status = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) };
assert_eq!(status, 0);
assert!(limit.rlim_cur >= 3000, "{}", limit.rlim_cur);
}
}