Skip to content

Implement an allocator for PSRAM #400

Description

@JacksonUtsch

Motivations

  • Would you like to implement this feature? y

Solution

Add type to alloc.rs that implements either nightly's or allocator_api2's Allocator

Alternatives

Only use SPIRAM as part of global heap and get corruption errors when utilizing esp-idf or avoid using SPIRAM.

Additional context

Here is my current implementation that seems to not be exactly right.

#[derive(Debug, Clone, Default)]
pub struct SpiAlloc;

unsafe impl allocator_api2::alloc::Allocator for SpiAlloc {
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, allocator_api2::alloc::AllocError> {
        unsafe {
            let align = layout.pad_to_align().align();
            let mut size = layout.size();
            if size == 0 {
                size = 1; // avoids returning null
            }
            let raw = heap_caps_aligned_alloc(align, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
            if raw.is_null() {
                return Err(allocator_api2::alloc::AllocError);
            }

            let real_size = heap_caps_get_allocated_size(raw);

            let pointer = ptr::slice_from_raw_parts_mut(raw as *mut u8, real_size);
            let non_null = NonNull::new_unchecked(pointer);
            return Ok(non_null);
        }
    }

    unsafe fn deallocate(&self, ptr: NonNull<u8>, _layout: Layout) {
        heap_caps_free(ptr.as_ptr() as *mut _);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions