polymorph-allocator 0.1.0

A simple no_std memory allocator
Documentation
#[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;

use super::{Allocator, Region};
use core::mem::size_of;

#[test]
fn iterator_two_regions() {
    const HEAP_SIZE: usize = 1024;
    let heap_one = Box::into_raw(Box::new([0u8; HEAP_SIZE])) as *mut u8;
    let heap_two = Box::into_raw(Box::new([0u8; HEAP_SIZE])) as *mut u8;

    let mut allocator = Allocator::empty();
    // Add region
    unsafe {
        allocator.add_region(heap_one as usize, HEAP_SIZE);
        allocator.add_region(heap_two as usize, HEAP_SIZE);
    }

    // Collect (addr, size) as an iterator
    let regions = allocator
        .iter()
        .map(|r| {(
            unsafe { r.header_ptr().map_or(0, |x| x.as_ptr() as usize ) },
            r.size()
        )})
        .collect::<Vec<(usize, usize)>>();

    // Check we have the right values
    assert_eq!(
        regions,
        vec![
            (heap_one as usize, HEAP_SIZE - size_of::<Region>()),
            (heap_two as usize, HEAP_SIZE - size_of::<Region>()),
        ]
    );

    // Destroy heap box
    core::mem::drop(allocator);
    core::mem::drop(unsafe { Box::from_raw(heap_one) });
    core::mem::drop(unsafe { Box::from_raw(heap_two) });
}