bomalloc 0.3.1

A fragmentation-aware experimental allocator built around address-span ownership
Documentation
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();
        // SAFETY: GetSystemInfo initializes the caller-provided SYSTEM_INFO.
        unsafe { GetSystemInfo(info.as_mut_ptr()) };
        // SAFETY: initialized by GetSystemInfo above.
        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> {
        // SAFETY: requesting a new anonymous reservation with a null hint.
        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> {
        // SAFETY: caller guarantees the range belongs to an existing reservation.
        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> {
        // SAFETY: caller guarantees page-aligned committed pages in our reservation.
        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> {
        // SAFETY: caller freezes an owned, committed, PAGE_READWRITE range.
        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> {
        // SAFETY: caller passes the original reservation base and MEM_RELEASE requires size zero.
        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> {
    // SAFETY: request a private read/write VM reservation used only by allocator metadata.
    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> {
    // SAFETY: caller passes the original base of a metadata reservation.
    let released = unsafe { VirtualFree(address as *mut c_void, 0, MEM_RELEASE) };
    if released == 0 {
        Err(BoAllocError::OutOfMemory)
    } else {
        Ok(())
    }
}