use crate::chunks::CHUNK_SIZE;
use core::alloc::Layout;
pub(crate) const MIN_ALIGN: usize = 16;
pub(crate) const STEP: usize = 8;
pub const MAX_ALIGN: usize = 64 * CHUNK_SIZE;
pub const MAX_SMALL: usize = 64 << 10;
const ANYWHERE_MAX: usize = 256;
pub(crate) const TABLE_MAX: usize = 8192;
pub(crate) const CLASSES: usize =
LINEAR_CLASSES + 8 * (MAX_SMALL.ilog2() - LINEAR_LIMIT.ilog2()) as usize;
const LINEAR_LIMIT: usize = 128;
const SMALLEST: usize = 16;
const LINEAR_CLASSES: usize = (LINEAR_LIMIT - SMALLEST) / STEP + 1;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Class(u8);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Request {
Small(Class),
Huge { chunks: usize, align: usize },
}
#[cfg(any(test, feature = "testing"))]
pub(crate) const fn is_small(layout: Layout) -> bool {
layout.size() <= MAX_SMALL && layout.align() <= CHUNK_SIZE
}
const fn block_size_of(i: usize) -> usize {
if i < LINEAR_CLASSES {
return SMALLEST + i * STEP;
}
let (doubling, step) = ((i - LINEAR_CLASSES) / 8, (i - LINEAR_CLASSES) % 8);
let top_bit = doubling + 7;
(1 << top_bit) + (step + 1) * (1 << (top_bit - 3))
}
const BLOCK_SIZES: [u32; CLASSES] = {
let mut sizes = [0; CLASSES];
let mut i = 0;
while i < CLASSES {
sizes[i] = block_size_of(i) as u32;
i += 1;
}
sizes
};
const LINE: usize = if cfg!(target_arch = "aarch64") { 128 } else { 64 };
const fn bin_initial_of(i: usize) -> usize {
let size = block_size_of(i);
if size <= TABLE_MAX {
clamp((32 << 10) / size, 8, 128)
} else {
clamp((64 << 10) / size, 1, 8)
}
}
const fn bin_max_of(i: usize) -> usize {
let size = block_size_of(i);
if size <= TABLE_MAX {
clamp((128 << 10) / size, 8, 2048)
} else {
clamp((128 << 10) / size, 1, 16)
}
}
const fn clamp(value: usize, low: usize, high: usize) -> usize {
if value < low {
low
} else if value > high {
high
} else {
value
}
}
const BIN_STARTS: ([u16; CLASSES], usize) = {
let mut starts = [0; CLASSES];
let mut total = 0;
let mut i = 0;
while i < CLASSES {
starts[i] = total as u16;
total += bin_max_of(i);
i += 1;
}
(starts, total)
};
const BIN_CAPACITIES: ([u16; CLASSES], [u16; CLASSES]) = {
let (mut initial, mut max) = ([0; CLASSES], [0; CLASSES]);
let mut i = 0;
while i < CLASSES {
initial[i] = bin_initial_of(i) as u16;
max[i] = bin_max_of(i) as u16;
i += 1;
}
(initial, max)
};
pub(crate) const BIN_SLOTS: usize = BIN_STARTS.1;
const RECIPROCALS: [u64; CLASSES] = {
let mut table = [0; CLASSES];
let mut i = 0;
while i < CLASSES {
table[i] = (1_u64 << 32).div_ceil(block_size_of(i) as u64);
i += 1;
}
table
};
pub(crate) const TABLE_STEPS: usize = TABLE_MAX / STEP + 1;
const TABLE: [u8; TABLE_STEPS] = {
let mut table = [0; TABLE_STEPS];
let mut step = 0;
while step < table.len() {
table[step] = Class::for_size(step * STEP).0;
step += 1;
}
table
};
impl Class {
#[inline(always)]
pub(crate) const fn from_table(size: usize) -> Self {
Self(TABLE[size.div_ceil(STEP)])
}
#[inline(always)]
pub(crate) const fn is_table_request(layout: Layout) -> bool {
layout.size() <= TABLE_MAX && layout.align() <= MIN_ALIGN
}
pub(crate) const fn from_index(index: usize) -> Self {
assert!(index < CLASSES);
Self(index as u8)
}
pub(crate) const unsafe fn from_index_unchecked(index: usize) -> Self {
debug_assert!(index < CLASSES);
Self(index as u8)
}
pub(crate) const fn for_size(size: usize) -> Self {
debug_assert!(size <= MAX_SMALL);
if size <= LINEAR_LIMIT {
return Self(size.saturating_sub(SMALLEST).div_ceil(STEP) as u8);
}
let below = size - 1;
let top_bit = (usize::BITS - 1 - below.leading_zeros()) as usize;
let step = (below >> (top_bit - 3)) & 7;
Self((LINEAR_CLASSES + (top_bit - 7) * 8 + step) as u8)
}
pub(crate) const fn bin_initial(self) -> usize {
BIN_CAPACITIES.0[self.0 as usize] as usize
}
pub(crate) const fn bin_max(self) -> usize {
BIN_CAPACITIES.1[self.0 as usize] as usize
}
pub(crate) const fn bin_start(self) -> usize {
BIN_STARTS.0[self.0 as usize] as usize
}
pub(crate) const fn reusable_anywhere(self) -> bool {
let size = self.block_size();
size.is_multiple_of(LINE) && size <= ANYWHERE_MAX
}
pub(crate) const fn index(self) -> usize {
self.0 as usize
}
pub(crate) const fn block_size(self) -> usize {
BLOCK_SIZES[self.0 as usize] as usize
}
pub(crate) const fn index_of(self, offset: usize) -> usize {
((offset as u64 * RECIPROCALS[self.0 as usize]) >> 32) as usize
}
pub(crate) const fn slab_chunks(self) -> usize {
if self.block_size() <= TABLE_MAX { 1 } else { 8 }
}
pub(crate) const fn blocks_per_slab(self) -> usize {
self.slab_chunks() * CHUNK_SIZE / self.block_size()
}
}
pub(crate) const fn classify(layout: Layout) -> Option<Request> {
let (size, align) = (layout.size(), layout.align());
if align > CHUNK_SIZE {
return classify_aligned_run(size, align);
}
if size > MAX_SMALL {
return Some(Request::Huge { chunks: size.div_ceil(CHUNK_SIZE), align: 1 });
}
let size = if align <= STEP {
size
} else if align == MIN_ALIGN {
size.next_multiple_of(MIN_ALIGN)
} else {
let rounded = size.next_power_of_two();
if rounded > align { rounded } else { align }
};
Some(Request::Small(Class::for_size(size)))
}
#[cold]
const fn classify_aligned_run(size: usize, align: usize) -> Option<Request> {
if align > MAX_ALIGN {
return None;
}
let chunks = size.div_ceil(CHUNK_SIZE);
Some(Request::Huge { chunks: if chunks > 2 { chunks } else { 2 }, align: align / CHUNK_SIZE })
}
#[cfg(test)]
mod test {
use super::*;
fn layout(size: usize, align: usize) -> Layout {
Layout::from_size_align(size, align).unwrap()
}
#[test]
fn the_table_is_strictly_increasing_and_spans_the_range() {
let sizes: std::vec::Vec<_> =
(0..CLASSES).map(|i| Class::from_index(i).block_size()).collect();
assert_eq!((sizes[0], sizes[CLASSES - 1]), (SMALLEST, MAX_SMALL));
assert!(sizes.windows(2).all(|pair| pair[0] < pair[1]));
assert!(sizes.iter().all(|size| size % STEP == 0));
assert!(sizes[LINEAR_CLASSES..].iter().all(|size| size % MIN_ALIGN == 0));
}
#[test]
fn for_size_picks_the_smallest_class_that_fits() {
let step = if cfg!(miri) { 997 } else { 1 };
for size in (1..=MAX_SMALL).step_by(step) {
let class = Class::for_size(size);
assert!(class.block_size() >= size, "{size} does not fit {class:?}");
if class.index() > 0 {
let smaller = Class::from_index(class.index() - 1);
assert!(smaller.block_size() < size, "{size} would fit {smaller:?}");
}
}
}
#[test]
fn the_table_agrees_with_the_arithmetic() {
for size in 0..=TABLE_MAX {
assert_eq!(Class::from_table(size), Class::for_size(size), "{size}");
}
}
#[test]
fn table_classes_have_one_chunk_slabs() {
for size in 0..=TABLE_MAX {
assert_eq!(Class::from_table(size).slab_chunks(), 1, "{size}");
}
}
#[test]
fn rounding_wastes_at_most_an_eighth() {
for i in 1..CLASSES {
let (class, below) = (Class::from_index(i), Class::from_index(i - 1));
let worst = below.block_size() + 1;
if worst > LINEAR_LIMIT {
assert!(
class.block_size() * 8 <= worst * 9,
"{class:?} wastes too much on {worst}"
);
}
}
}
#[test]
fn index_of_divides_every_block_offset_exactly() {
for i in 0..CLASSES {
let class = Class::from_index(i);
for index in 0..class.blocks_per_slab() {
assert_eq!(class.index_of(index * class.block_size()), index, "{class:?}");
}
}
}
#[test]
fn slabs_hold_at_least_eight_blocks_and_waste_little() {
for i in 0..CLASSES {
let class = Class::from_index(i);
assert!(class.slab_chunks().is_power_of_two());
assert!(class.blocks_per_slab() >= 8, "{class:?}");
let tail =
class.slab_chunks() * CHUNK_SIZE - class.blocks_per_slab() * class.block_size();
assert!(tail < class.block_size(), "{class:?} wastes a whole block");
}
}
#[test]
fn blocks_honour_the_requested_alignment() {
for align_shift in 0..=MAX_ALIGN.ilog2() {
let align = 1usize << align_shift;
for size in [1, 7, 16, 100, 4096, 5000, 70_000, MAX_SMALL, MAX_SMALL + 1, 3 << 20] {
match classify(layout(size, align)).unwrap() {
Request::Small(class) => {
assert!(class.block_size() >= size);
assert_eq!(class.block_size() % align, 0, "{size}/{align}");
}
Request::Huge { chunks, align: run_align } => {
assert!(chunks * CHUNK_SIZE >= size);
assert!(run_align * CHUNK_SIZE >= align, "{size}/{align}");
}
}
}
}
}
#[test]
fn requests_for_sixteen_bytes_of_alignment_get_classes_that_keep_it() {
for size in 1..=TABLE_MAX {
let Some(Request::Small(class)) = classify(layout(size, MIN_ALIGN)) else { panic!() };
assert_eq!(class.block_size() % MIN_ALIGN, 0, "{size}");
assert_eq!(Class::from_table(size.next_multiple_of(MIN_ALIGN)), class);
let Some(Request::Small(loose)) = classify(layout(size, STEP)) else { panic!() };
assert!(loose.block_size() <= class.block_size());
assert_eq!(Class::from_table(size), loose);
}
assert_eq!(Class::for_size(24).block_size(), 24, "three words fill their block");
}
#[test]
fn the_small_and_huge_boundary_is_exact() {
assert_eq!(
classify(layout(MAX_SMALL, 1)),
Some(Request::Small(Class::from_index(CLASSES - 1)))
);
assert_eq!(classify(layout(MAX_SMALL + 1, 1)), Some(Request::Huge { chunks: 2, align: 1 }));
assert_eq!(
classify(layout(CHUNK_SIZE, 1)),
Some(Request::Small(Class::for_size(CHUNK_SIZE)))
);
}
#[test]
fn alignment_beyond_a_chunk_takes_an_aligned_run_up_to_the_limit() {
assert_eq!(
classify(layout(8, 2 * CHUNK_SIZE)),
Some(Request::Huge { chunks: 2, align: 2 }),
"a small request aligned past a chunk takes a run of its own, bigger than a slab block"
);
assert_eq!(classify(layout(0, MAX_ALIGN)), Some(Request::Huge { chunks: 2, align: 64 }));
assert_eq!(classify(layout(8, MAX_ALIGN * 2)), None);
for size in [1, MAX_SMALL, MAX_SMALL + 1] {
for align in [1, CHUNK_SIZE, 2 * CHUNK_SIZE, MAX_ALIGN] {
let small = matches!(classify(layout(size, align)), Some(Request::Small(_)));
assert_eq!(is_small(layout(size, align)), small, "{size}/{align}");
}
}
}
}