pub const CHUNK_TARGET_ENTRIES: u64 = 2_048;
pub const CHUNK_MIN_ENTRIES: usize = 512;
pub const CHUNK_MAX_ENTRIES: usize = 8_192;
#[must_use]
pub fn cut_after(key: &[u8], entries: usize) -> bool {
if entries >= CHUNK_MAX_ENTRIES {
return true;
}
entries >= CHUNK_MIN_ENTRIES
&& boundary_hash(key) % CHUNK_TARGET_ENTRIES == CHUNK_TARGET_ENTRIES - 1
}
fn boundary_hash(key: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in key {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clamps_bound_every_chunk() {
assert!(!cut_after(b"any", CHUNK_MIN_ENTRIES - 1));
assert!(cut_after(b"any", CHUNK_MAX_ENTRIES));
}
#[test]
fn boundaries_depend_only_on_the_key() {
let selected = (0u64..100_000)
.map(|n| n.to_be_bytes().to_vec())
.find(|key| cut_after(key, CHUNK_MIN_ENTRIES))
.expect("a boundary key exists within the search space");
for entries in [
CHUNK_MIN_ENTRIES,
CHUNK_MIN_ENTRIES + 1,
CHUNK_MAX_ENTRIES - 1,
] {
assert!(cut_after(&selected, entries));
}
}
}