use alloc::vec::Vec;
use core::fmt;
use core::ops::{Deref, DerefMut};
pub(crate) const TABLE_ALIGN: usize = 64;
pub(crate) struct Table<T> {
buf: Vec<T>,
off: usize,
len: usize,
}
impl<T: Copy + Default> Table<T> {
pub(crate) const fn new() -> Self {
Self {
buf: Vec::new(),
off: 0,
len: 0,
}
}
fn alloc(size: usize) -> Self {
if size == 0 {
return Self::new();
}
let elem = core::mem::size_of::<T>();
debug_assert!(elem > 0 && TABLE_ALIGN.is_multiple_of(elem));
let bytes = size * elem;
let align = if huge::ENABLED && bytes >= huge::MIN_TABLE {
huge::PAGE
} else {
TABLE_ALIGN
};
let buf = alloc::vec![T::default(); size + align / elem];
let misalign = buf.as_ptr() as usize % align;
let off = (align - misalign) % align / elem;
debug_assert!(off + size <= buf.len());
if align == huge::PAGE {
huge::advise(buf[off..].as_ptr().cast(), bytes / huge::PAGE * huge::PAGE);
}
Self {
buf,
off,
len: size,
}
}
pub(crate) fn reset_zeroed(&mut self, size: usize) {
if self.len == size {
self.fill(T::default());
} else {
*self = Self::alloc(size);
}
}
pub(crate) fn resize(&mut self, size: usize) {
if self.len == size {
return;
}
let mut t = Self::alloc(size);
let keep = self.len.min(size);
t[..keep].copy_from_slice(&self[..keep]);
*self = t;
}
}
impl<T: Copy + Default> Default for Table<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Deref for Table<T> {
type Target = [T];
#[inline(always)]
fn deref(&self) -> &[T] {
&self.buf[self.off..self.off + self.len]
}
}
impl<T> DerefMut for Table<T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut [T] {
&mut self.buf[self.off..self.off + self.len]
}
}
impl<T: fmt::Debug> fmt::Debug for Table<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Table").field("len", &self.len).finish()
}
}
mod huge {
pub(super) const PAGE: usize = 2 << 20;
pub(super) const MIN_TABLE: usize = 8 << 20;
pub(super) const ENABLED: bool = cfg!(all(
target_os = "linux",
target_arch = "x86_64",
feature = "std",
not(miri)
));
#[cfg(all(
target_os = "linux",
target_arch = "x86_64",
feature = "std",
not(miri)
))]
#[allow(unsafe_code)]
pub(super) fn advise(p: *const u8, len: usize) {
const SYS_MADVISE: usize = 28;
const MADV_HUGEPAGE: usize = 14;
if len == 0 {
return;
}
debug_assert!((p as usize).is_multiple_of(PAGE) && len.is_multiple_of(PAGE));
unsafe {
core::arch::asm!(
"syscall",
inlateout("rax") SYS_MADVISE => _,
in("rdi") p,
in("rsi") len,
in("rdx") MADV_HUGEPAGE,
lateout("rcx") _,
lateout("r11") _,
options(nostack),
);
}
}
#[cfg(not(all(
target_os = "linux",
target_arch = "x86_64",
feature = "std",
not(miri)
)))]
pub(super) fn advise(_p: *const u8, _len: usize) {}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn aligned_and_zeroed() {
for size in [1usize, 3, 16, 1000, 1 << 16] {
let t = Table::<u32>::alloc(size);
assert_eq!(t.len(), size);
assert_eq!(t.as_ptr() as usize % TABLE_ALIGN, 0);
assert!(t.iter().all(|&v| v == 0));
let t = Table::<u8>::alloc(size);
assert_eq!(t.len(), size);
assert_eq!(t.as_ptr() as usize % TABLE_ALIGN, 0);
}
assert!(Table::<u32>::alloc(0).is_empty());
}
#[test]
#[cfg_attr(miri, ignore = "scans 8-12 MiB tables; huge pages are off under Miri")]
fn large_tables_on_huge_page_boundaries() {
let entries = huge::MIN_TABLE / 4;
for size in [entries, entries + 7, 3 * entries / 2] {
let mut t = Table::<u32>::alloc(size);
let want = if huge::ENABLED {
huge::PAGE
} else {
TABLE_ALIGN
};
assert_eq!(t.as_ptr() as usize % want, 0);
assert!(t.iter().all(|&v| v == 0));
t[size - 1] = 7;
t.resize(size + 1);
assert_eq!(t[size - 1], 7);
assert_eq!(t.as_ptr() as usize % want, 0);
}
let t = Table::<u32>::alloc(entries - 1);
assert_eq!(t.as_ptr() as usize % TABLE_ALIGN, 0);
}
#[test]
fn reset_and_resize() {
let mut t = Table::<u8>::new();
t.resize(10);
t[..10].copy_from_slice(&[1; 10]);
t.resize(10); assert!(t.iter().all(|&v| v == 1));
t.resize(20); assert_eq!(&t[..10], &[1; 10]);
assert_eq!(&t[10..], &[0; 10]);
assert_eq!(t.as_ptr() as usize % TABLE_ALIGN, 0);
t.resize(5);
assert_eq!(&t[..], &[1; 5]);
t.reset_zeroed(5);
assert_eq!(&t[..], &[0; 5]);
t.reset_zeroed(0);
assert!(t.is_empty());
}
}