alloc.rs


Overview

The `alloc.rs` file implements a **custom global memory allocator** for the Rust components of the project, which delegates all memory management operations to Python's native memory allocator APIs (`PyMem_Malloc`, `PyMem_Free`, and `PyMem_Realloc`). This integration ensures that memory allocations performed by Rust code remain compatible with Python's memory management system, preserving consistency, safety, and debugging capabilities when Rust interacts with Python objects.

By replacing Rust's default global allocator with this Python-aware allocator, the project avoids memory fragmentation and ownership conflicts between Rust and Python runtimes, which is critical for seamless interoperability in Python extension modules or embedded Rust code.


Detailed Description

PyMemAllocator Struct


Global Allocator Instance


Trait Implementations

Sync for PyMemAllocator


GlobalAlloc for PyMemAllocator

This trait defines the core allocator interface for the Rust global allocator.

unsafe impl GlobalAlloc for PyMemAllocator {
    #[inline]
    unsafe fn alloc(&self, layout: Layout) -> *mut u8;

    #[inline]
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);

    #[inline]
    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8;

    #[inline]
    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8;
}

alloc

dealloc

alloc_zeroed

realloc

Important Implementation Details


Interaction with Other System Components


Usage Example

use core::alloc::{GlobalAlloc, Layout};

fn example_allocation() {
    let layout = Layout::from_size_align(256, 8).unwrap();
    unsafe {
        // Allocate 256 bytes
        let ptr = ALLOCATOR.alloc(layout);

        if !ptr.is_null() {
            // Use the memory...

            // Deallocate when done
            ALLOCATOR.dealloc(ptr, layout);
        }
    }
}

Mermaid Diagram: Memory Allocation Flow

flowchart TD
    RustCode[All Rust Code]
    MemoryOps[Memory Operations\n(alloc, dealloc, realloc, alloc_zeroed)]
    PyMemAPI[Python Memory API\n(PyMem_Malloc, PyMem_Free, PyMem_Realloc)]

    RustCode -->|requests memory| MemoryOps
    MemoryOps -->|calls| PyMemAPI

Summary

This design is fundamental for the project’s Python interoperability, preventing memory management issues when Rust and Python components share data and resources.