Skip to content

Instantly share code, notes, and snippets.

@xorgy
Created August 7, 2025 17:25
Show Gist options
  • Save xorgy/90d269954ca4c9a565e6df240ad28aa3 to your computer and use it in GitHub Desktop.
Save xorgy/90d269954ca4c9a565e6df240ad28aa3 to your computer and use it in GitHub Desktop.
impl<T> Fillet<T> {
/// The system allocator will probably manage our allocation with virtual memory at this size.
///
/// Estimates here are very conservative right now, and will probably be tuned downward.
const PROBABLE_VM_THRESHOLD: usize = if size_of::<T>() == 0 {
// Irrelevant for ZSTs.
0
} else if cfg!(target_env = "gnu") {
// glibc/ptmalloc: Initial 128KB, dynamic up to ~4MB on 64-bit.
4 * 1024 * 1024
} else if cfg!(target_env = "musl") {
// musl: No fixed, but large ~256KB+ often mmap; conservative ~1MB.
1024 * 1024
} else if cfg!(target_os = "windows") {
// Windows HeapAlloc: ~512KB bypass to VirtualAlloc; conservative 1MB.
1024 * 1024
} else if cfg!(target_os = "macos") {
// macOS libmalloc: >127KB to vm_allocate; conservative 256KB.
256 * 1024
} else {
// Fallback: Assume ~128KB like glibc default.
128 * 1024
};
/// When `len` is less than this, we are in a small class, and `realloc` will just copy.
///
/// Irrelevant for ZSTs, as no allocations occur.
const SMALL_THRESH_ELEMS: usize = if size_of::<T>() == 0 {
usize::MAX
} else if Self::DATA_OFFSET >= 8192 {
// Huge align_of::<T>() would otherwise underflow.
0
} else {
(8192 - Self::DATA_OFFSET) / size_of::<T>()
};
/// When `len` is greater this, malloc tends to use `mmap`/`munmap` for `realloc`.
///
/// `realloc` should be quite cheap at this size, especially if already page aligned.
const VM_THRESH_ELEMS: usize = if size_of::<T>() == 0 {
// Irrelevant for ZSTs.
usize::MAX
} else {
(Self::PROBABLE_VM_THRESHOLD + Self::DATA_OFFSET) / size_of::<T>()
};
/// When `len` is less than this, prefer alloc + copy + dealloc over move + realloc.
///
/// If `FilletIntoIter` has no front consumption, it is always better to try `realloc` on its own
/// but if there has been front consumption, `realloc` after moving the remaining elements can
/// lead to two consecutive copying operations; so sometimes it's better to just allocate anew,
/// copy the remaining elements, and dealloc the original.
const SHRINK_THRESH_ELEMS: usize = if size_of::<T>() == 0 {
// Irrelevant for ZSTs.
usize::MAX
} else {
Self::SMALL_THRESH_ELEMS / 2
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment