Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // # memory: heap & stack
- // - rlyeh, public domain.
- //
- // # heap: easy arenas (~ stack-scope allocator)
- // memory is split in two: bottom-to-top is heap, top-to-bottom is stack.
- // heap pointer can be restarted (to bottom) for quick level loading.
- // stack pointer can be restarted (to top) when entering a new frame.
- //
- // |bottom>>|ui|spinners|mecommon|level1|level2|..>>>HEAP_PTR free-space STACK_PTR<<<< top|
- //
- // @todo: odd/even stack frames support
- // @todo: void *remark[256]; push_heap(); pop_heap();
- //
- // [ref] double ended allocator
- // [ref] Game Engine Architecture p211..213, p291
- #include <stdint.h>
- struct heap_t {
- char *bottom, *heap; // bottom >> ... heap >>
- char *stack, *top; // << stack ... << top
- } heap_[32];
- void heap_create(int heap_id, void *buffer, int sz) {
- struct heap_t *M = &heap_[ heap_id ];
- M->bottom = M->heap = (char*)buffer;
- M->stack = M->top = (char*)buffer + sz;
- }
- void* heap_malloc(int heap_id, int sz, int align) {
- struct heap_t *M = &heap_[ heap_id ];
- align = align ? (align - ((uintptr_t)M->heap & (align - 1)) & (align-1)) : 0;
- sz += align;
- if( M->heap + sz >= M->stack ) {
- return 0;
- }
- void *ret = M->heap + align + 0 /*fence*/;
- M->heap += sz;
- return ret;
- }
- void* heap_alloca(int heap_id, int sz) {
- struct heap_t *M = &heap_[ heap_id ];
- if( M->heap + sz >= M->stack ) {
- return 0;
- }
- M->stack -= sz;
- return M->stack;
- }
- void heap_clear_heap(int heap_id) {
- struct heap_t *M = &heap_[ heap_id ];
- M->heap = M->bottom; // clear heap
- }
- void heap_clear_stack(int heap_id) {
- struct heap_t *M = &heap_[ heap_id ];
- M->stack = M->top; // likely every frame
- }
- int heap_avail(int heap_id) {
- struct heap_t *M = &heap_[ heap_id ];
- return M->stack - M->heap;
- }
- int heap_used(int heap_id) {
- struct heap_t *M = &heap_[ heap_id ];
- return (M->heap - M->bottom) + (M->top - M->stack);
- }
- #include <stdio.h>
- char *heap_debug(int heap_id) {
- static char buffer[256];
- sprintf(buffer, "bottom:%p | heap:%p >> ... << stack:%p | top:%p", heap_[heap_id].bottom, heap_[heap_id].heap, heap_[heap_id].stack, heap_[heap_id].top);
- return buffer;
- }
- #ifdef MEMHEAPDEMO
- #include <stdlib.h>
- int main() {
- enum {
- HEAP_AUDIO = 3,
- HEAP_GRAPHICS = 10,
- };
- void *buffer;
- heap_create(HEAP_AUDIO, buffer = (void*)malloc(1*1024*1024), 1*1024*1024);
- void *ptr1 = heap_malloc(HEAP_AUDIO, 515, 0x10000);
- void *ptr2 = heap_malloc(HEAP_AUDIO, 515, 0x10000);
- void *temp = heap_alloca(HEAP_AUDIO, 0x100);
- printf("ptr1[%p] ptr2[%p] temp[%p]\n", ptr1, ptr2, temp);
- char buf[256];
- puts( heap_debug(HEAP_AUDIO) );
- free( buffer );
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement