second_brain_api/
open_files.rs1use std::io;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub struct Raised {
5 pub from: libc::rlim_t,
6 pub to: libc::rlim_t,
7}
8
9pub fn raise_open_file_limit() -> io::Result<Raised> {
13 let mut limit = libc::rlimit {
14 rlim_cur: 0,
15 rlim_max: 0,
16 };
17 if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {
18 return Err(io::Error::last_os_error());
19 }
20 let from = limit.rlim_cur;
21 let to = ceiling(limit.rlim_max)?;
22 if to <= from {
23 return Ok(Raised { from, to: from });
24 }
25 limit.rlim_cur = to;
26 if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) } != 0 {
27 return Err(io::Error::last_os_error());
28 }
29 Ok(Raised { from, to })
30}
31
32#[cfg(target_vendor = "apple")]
35fn ceiling(hard: libc::rlim_t) -> io::Result<libc::rlim_t> {
36 let mut per_process: libc::c_int = 0;
37 let mut size = std::mem::size_of::<libc::c_int>();
38 let found = unsafe {
39 libc::sysctlbyname(
40 c"kern.maxfilesperproc".as_ptr(),
41 (&mut per_process as *mut libc::c_int).cast(),
42 &mut size,
43 std::ptr::null_mut(),
44 0,
45 )
46 };
47 if found != 0 {
48 return Err(io::Error::last_os_error());
49 }
50 let per_process = libc::rlim_t::try_from(per_process)
51 .map_err(|_| io::Error::other(format!("kern.maxfilesperproc is {per_process}")))?;
52 Ok(hard.min(per_process))
53}
54
55#[cfg(not(target_vendor = "apple"))]
56fn ceiling(hard: libc::rlim_t) -> io::Result<libc::rlim_t> {
57 Ok(hard)
58}