#![cfg(all(feature = "allocator", feature = "allocation-tracking"))]
use std::alloc::{Layout, System};
pub trait ReservedSize {
fn reserved_size(&self, layout: Layout) -> usize;
}
impl ReservedSize for System {
#[inline]
fn reserved_size(&self, layout: Layout) -> usize {
layout.size()
}
}
#[cfg(all(
any(target_arch = "x86_64", target_arch = "x86"),
any(target_os = "linux", target_os = "macos"),
not(target_env = "msvc"),
))]
const ALIGNOF_MAX_ALIGN_T: usize = 16;
#[cfg(all(
any(target_arch = "x86_64", target_arch = "x86"),
any(target_os = "linux", target_os = "macos"),
not(target_env = "msvc"),
))]
impl ReservedSize for jemallocator::Jemalloc {
#[inline]
fn reserved_size(&self, layout: Layout) -> usize {
let flags = if layout.align() <= ALIGNOF_MAX_ALIGN_T && layout.align() <= layout.size() {
0
} else {
jemalloc_sys::MALLOCX_ALIGN(layout.align())
};
let reserved = unsafe { jemalloc_sys::nallocx(layout.size(), flags) };
if reserved == 0 {
layout.size()
} else {
reserved
}
}
}
#[cfg(all(
any(unix, windows),
not(all(
any(target_arch = "x86_64", target_arch = "x86"),
any(target_os = "linux", target_os = "macos"),
not(target_env = "msvc"),
)),
))]
const MI_MAX_ALIGN_SIZE: usize = 16;
#[cfg(all(
any(unix, windows),
not(all(
any(target_arch = "x86_64", target_arch = "x86"),
any(target_os = "linux", target_os = "macos"),
not(target_env = "msvc"),
)),
))]
impl ReservedSize for mimalloc::MiMalloc {
#[inline]
fn reserved_size(&self, layout: Layout) -> usize {
let size = if layout.align() > MI_MAX_ALIGN_SIZE {
layout.size().max(MI_MAX_ALIGN_SIZE).saturating_add(layout.align().saturating_sub(1))
} else {
layout.size()
};
unsafe { mimalloc_sys::mi_good_size(size) }
}
}