pub(crate) const DIRECT_IO_ALIGN: usize = 4096;
pub(crate) const DEFAULT_COMPRESSION_CHUNK_BYTES: usize = 64 * 1024;
pub(crate) fn clamp_direct_prefetch_window(prefetch_bytes: usize, chunk_size: usize) -> usize {
let record = chunk_size.saturating_add(4);
let floor = record.saturating_mul(2);
let want = prefetch_bytes.max(floor).max(DIRECT_IO_ALIGN);
want.checked_next_multiple_of(DIRECT_IO_ALIGN)
.unwrap_or(usize::MAX & !(DIRECT_IO_ALIGN - 1))
}
#[cfg(test)]
mod tests {
use super::*;
fn worst_case_refills(window: usize, record: usize) -> usize {
record.div_ceil(window) + 1
}
#[test]
fn clamp_bounds_per_chunk_refills_to_two() {
let chunk = DEFAULT_COMPRESSION_CHUNK_BYTES;
let record = chunk + 4;
let tiny = 8 * 1024;
assert!(
worst_case_refills(tiny, record) > 2,
"an unclamped sub-chunk window must amplify (>2 refills/chunk); \
got {} for window={} record={}",
worst_case_refills(tiny, record),
tiny,
record
);
let clamped = clamp_direct_prefetch_window(tiny, chunk);
assert!(
clamped >= 2 * record,
"clamped window must hold >= 2 records: {clamped} < {}",
2 * record
);
assert_eq!(
worst_case_refills(clamped, record),
2,
"clamped window must bound per-chunk refills to ceil(chunk/window)+1 = 2"
);
}
#[test]
fn clamp_result_is_4k_aligned_and_at_least_floor() {
for &(pf, chunk) in &[
(0usize, 64 * 1024usize),
(1, 64 * 1024),
(8 * 1024, 64 * 1024),
(4095, 4096),
(1024 * 1024, 64 * 1024), (128 * 1024, 256 * 1024), ] {
let w = clamp_direct_prefetch_window(pf, chunk);
assert_eq!(w % DIRECT_IO_ALIGN, 0, "window {w} not 4K-aligned");
assert!(
w >= 2 * (chunk + 4),
"window {w} below floor 2*(chunk+4)={} (chunk={chunk})",
2 * (chunk + 4)
);
assert!(w >= pf, "window {w} dropped below requested {pf}");
assert!(w >= DIRECT_IO_ALIGN, "window {w} below one alignment unit");
}
}
#[test]
fn clamp_preserves_large_windows() {
let big = 4 * 1024 * 1024;
assert_eq!(
clamp_direct_prefetch_window(big, DEFAULT_COMPRESSION_CHUNK_BYTES),
big,
"an already-aligned window above the floor is returned unchanged"
);
}
#[test]
fn clamp_saturates_on_overflow() {
let w = clamp_direct_prefetch_window(usize::MAX, usize::MAX);
assert_eq!(w % DIRECT_IO_ALIGN, 0, "saturated window must stay aligned");
assert_eq!(w, usize::MAX & !(DIRECT_IO_ALIGN - 1));
}
}