#![feature(slice_ptr_get)]
#![no_std]
extern crate core;
use core::alloc::{GlobalAlloc, Layout};
use core::cell::UnsafeCell;
use core::ptr::null_mut;

pub struct Heap {
    playarea: usize,
    len:      UnsafeCell<usize>,
    header:   UnsafeCell<[(*mut u8, usize)]>
}

fn is_allocated(pointer: *mut u8, size: usize) -> bool {
    if (pointer..pointer.wrapping_add(size)).contains(&pointer) {
	true
    } else {
	false
    }
}

unsafe impl GlobalAlloc for Heap {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
	let size = layout.size();
	let align = layout.align();
	let mut ptr = null_mut();
	for pointer in 0..self.playarea {
	    if !is_allocated(pointer as *mut u8, size) {
		ptr = pointer as *mut u8;
		break;
	    }
	};

	unsafe { *self.header.get().get_unchecked_mut(*self.len.get())  = (ptr, size) };
	*self.len.get() += 1;

	ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {}
}
