Last active
October 29, 2015 16:14
-
-
Save martincohen/3a5c9c95a18050efb86b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ScratchMemory { | |
void *base; | |
memi capacity; | |
}; | |
void child(ScratchMemory *memory,...) { | |
// do things to memory | |
} | |
void parent(ScratchMemory *memory,...) { | |
// do things to memory | |
child(memory); | |
// do things to memory | |
// problem: memory is changed by child | |
} | |
// | |
// | |
// | |
struct StackMemory { | |
void *base; | |
void *position; | |
memi capacity; | |
}; | |
void * | |
stack_allocate(StackMemory *stack, memi capacity) | |
{ | |
void *ret; | |
memi p = stack->position - stack->base; | |
if ((p + capacity) > stack->capacity) { | |
stack->base = memory_reallocate(base, p + capacity); // Grow factor? | |
ret = stack->base + p; | |
} else { | |
ret = stack->postition; | |
} | |
stack->position = ret + capacity; | |
return ret; | |
} | |
void | |
stack_release(StackMemory *stack, memi capacity) | |
{ | |
stack->position -= capacity; | |
} | |
// | |
// | |
// | |
struct StackAllocator { | |
StackMemory stack; | |
memi capacity; | |
StackAllocator(StackMemory *stack) : | |
_stack(stack), | |
_capacity(0) | |
{} | |
~StackAllocator() { | |
if (_capacity) { | |
stack_release(stack, _capacity); | |
} | |
} | |
inline void * | |
allocate(memi capacity) { | |
_capacity += capacity; | |
memory = stack_allocate(capacity); | |
} | |
inline void * | |
ptr() { | |
return stack->position - _capacity; | |
} | |
}; | |
// | |
// | |
// | |
void child1(StackMemory *stack,...) { | |
StackAllocator allocator(stack); | |
allocator.allocate(stack, 1024); | |
// do things to memory | |
} | |
void child2(StackMemory *stack,...) { | |
// do nothing to memory | |
} | |
void parent(StackMemory *stack,...) { | |
StackAllocator allocator(stack); | |
allocator.allocate(1024); | |
// do things to memory | |
child1(stack); | |
// do things to memory | |
child2(stack); | |
// do things to memory | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment