use core::ffi::c_void;
use std::mem::MaybeUninit;
use windows_sys::Win32::System::Memory::{
DiscardVirtualMemory, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS,
PAGE_READWRITE, VirtualAlloc, VirtualFree,
};
use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO};
use crate::BoAllocError;
use crate::os::BackingStore;
pub(crate) struct PlatformBacking {
page_size: usize,
allocation_granularity: usize,
}
impl PlatformBacking {
pub(crate) fn new() -> Result<Self, BoAllocError> {
let mut info = MaybeUninit::<SYSTEM_INFO>::uninit();
unsafe { GetSystemInfo(info.as_mut_ptr()) };
let info = unsafe { info.assume_init() };
let backing = Self {
page_size: info.dwPageSize as usize,
allocation_granularity: info.dwAllocationGranularity as usize,
};
if backing.page_size == 0 || backing.allocation_granularity == 0 {
return Err(BoAllocError::UnsupportedPlatform);
}
Ok(backing)
}
}
impl BackingStore for PlatformBacking {
fn page_size(&self) -> usize {
self.page_size
}
fn allocation_granularity(&self) -> usize {
self.allocation_granularity
}
unsafe fn reserve(&self, size: usize) -> Result<usize, BoAllocError> {
let ptr = unsafe { VirtualAlloc(std::ptr::null(), size, MEM_RESERVE, PAGE_NOACCESS) };
if ptr.is_null() {
Err(BoAllocError::AddressSpaceExhausted)
} else {
Ok(ptr as usize)
}
}
unsafe fn commit(&self, address: usize, size: usize) -> Result<(), BoAllocError> {
let ptr =
unsafe { VirtualAlloc(address as *const c_void, size, MEM_COMMIT, PAGE_READWRITE) };
if ptr.is_null() {
Err(BoAllocError::OutOfMemory)
} else {
Ok(())
}
}
unsafe fn decommit(&self, address: usize, size: usize) -> Result<(), BoAllocError> {
let ok = unsafe { VirtualFree(address as *mut c_void, size, MEM_DECOMMIT) };
if ok == 0 {
Err(BoAllocError::OutOfMemory)
} else {
Ok(())
}
}
unsafe fn discard(&self, address: usize, size: usize) -> Result<(), BoAllocError> {
let error = unsafe { DiscardVirtualMemory(address as *mut c_void, size) };
if error == 0 {
Ok(())
} else {
Err(BoAllocError::OutOfMemory)
}
}
unsafe fn release(&self, address: usize, _size: usize) -> Result<(), BoAllocError> {
let ok = unsafe { VirtualFree(address as *mut c_void, 0, MEM_RELEASE) };
if ok == 0 {
Err(BoAllocError::OutOfMemory)
} else {
Ok(())
}
}
}
pub(crate) unsafe fn reserve_commit_metadata_block(size: usize) -> Result<usize, BoAllocError> {
let pointer = unsafe {
VirtualAlloc(
std::ptr::null(),
size,
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE,
)
};
if pointer.is_null() {
Err(BoAllocError::OutOfMemory)
} else {
Ok(pointer as usize)
}
}
pub(crate) unsafe fn release_metadata_block(address: usize) -> Result<(), BoAllocError> {
let released = unsafe { VirtualFree(address as *mut c_void, 0, MEM_RELEASE) };
if released == 0 {
Err(BoAllocError::OutOfMemory)
} else {
Ok(())
}
}