| 1 |
use std::io; |
| 2 |
use std::os::raw::c_int; |
| 3 |
|
| 4 |
extern "C" { |
| 5 |
fn _setmaxstdio(new_max: c_int) -> c_int; |
| 6 |
fn _getmaxstdio() -> c_int; |
| 7 |
} |
| 8 |
|
| 9 |
/// Sets a maximum for the number of simultaneously open files at the stream I/O level. |
| 10 |
/// |
| 11 |
/// The maximum allowed value is platform-dependent, typically 8192 on modern systems. |
| 12 |
/// Values that would overflow when converted to `c_int` or exceed the platform's |
| 13 |
/// maximum will result in an error. |
| 14 |
/// |
| 15 |
/// See <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setmaxstdio?view=msvc-170> |
| 16 |
/// |
| 17 |
/// # Errors |
| 18 |
/// Returns an error if: |
| 19 |
/// - `new_max` exceeds `c_int::MAX` (typically 2,147,483,647) |
| 20 |
/// - `new_max` is below the minimum (typically 20) or above the platform maximum (typically 8192) |
| 21 |
/// - The underlying `_setmaxstdio` call fails |
| 22 |
#[cfg_attr(docsrs, doc(cfg(windows)))] |
| 23 |
pub fn setmaxstdio(new_max: u32) -> io::Result<u32> { |
| 24 |
// Validate that new_max fits in c_int to prevent overflow. |
| 25 |
// SAFETY: c_int::MAX (i32::MAX = 2147483647) fits in u32, so this cast is safe. |
| 26 |
if new_max > c_int::MAX as u32 { |
| 27 |
return Err(io::Error::new( |
| 28 |
io::ErrorKind::InvalidInput, |
| 29 |
"new_max exceeds maximum allowed value", |
| 30 |
)); |
| 31 |
} |
| 32 |
|
| 33 |
// SAFETY: We've validated that new_max fits in c_int, so the cast is safe |
| 34 |
// (though clippy warns about possible wrapping). The cast back to u32 is |
| 35 |
// safe because we've checked that ret >= 0. |
| 36 |
#[allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)] |
| 37 |
unsafe { |
| 38 |
let ret = _setmaxstdio(new_max as c_int); |
| 39 |
if ret < 0 { |
| 40 |
return Err(io::Error::last_os_error()); |
| 41 |
} |
| 42 |
Ok(ret as u32) |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
/// Returns the number of simultaneously open files permitted at the stream I/O level. |
| 47 |
/// |
| 48 |
/// See <https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/getmaxstdio?view=msvc-170> |
| 49 |
#[cfg_attr(docsrs, doc(cfg(windows)))] |
| 50 |
#[must_use] |
| 51 |
pub fn getmaxstdio() -> u32 { |
| 52 |
// SAFETY: A negative `ret` should never appear. |
| 53 |
// It is safe even if the return value is wrong. |
| 54 |
#[allow(clippy::cast_sign_loss)] |
| 55 |
unsafe { |
| 56 |
let ret = _getmaxstdio(); |
| 57 |
debug_assert!(ret >= 0); |
| 58 |
ret as u32 |
| 59 |
} |
| 60 |
} |