diff --git a/stack.c b/stack.c index 9ce82e0..72ea52e 100644 --- a/stack.c +++ b/stack.c @@ -31,6 +31,8 @@ typedef enum { MUST_CHECK StackResult stack_init(Stack *stack, size_t capacity, size_t item_sz); MUST_CHECK StackResult stack_init_raw(Stack *stack, uint8_t *buf, size_t buf_sz, size_t item_sz); +MUST_CHECK StackResult stack_resize(Stack *stack, size_t capacity); +uint8_t *stack_resize_raw(Stack *stack, uint8_t *new_buf, size_t buf_sz); MUST_CHECK StackResult stack_destroy(Stack *stack); MUST_CHECK StackResult stack_push(Stack *stack, const void *value); MUST_CHECK StackResult stack_pop(Stack *stack, void *dest); @@ -78,6 +80,28 @@ StackResult stack_init_raw(Stack *stack, uint8_t *buf, size_t buf_sz, size_t ite return Ok; } +StackResult stack_resize(Stack *stack, size_t capacity) { + uint8_t *old_buf = stack_resize_raw(stack, malloc(capacity * stack->item_sz), capacity * stack->item_sz); + + if (old_buf) + free(old_buf); + + return Ok; +} + +uint8_t *stack_resize_raw(Stack *stack, uint8_t *new_buf, size_t buf_sz) { + if (stack->read_ptr > buf_sz) + return NULL; + + uint8_t *old_buf = stack->buf; + memcpy(new_buf, old_buf, stack->buf_sz); + + stack->buf = new_buf; + stack->buf_sz = buf_sz; + + return old_buf; +} + StackResult stack_push(Stack *stack, const void *value) { if (stack->read_ptr + stack->item_sz > stack->buf_sz) return StackFull; @@ -162,5 +186,47 @@ int main(void) { assert(stack_empty(&s2)); /* Make sure to not call stack_destroy or free here, since buf[] is static */ + + uint8_t buf2[64]; + stack_resize_raw(&s2, buf2, 64); + + assert(stack_capacity(&s2) == 16); + assert(stack_length(&s2) == 0); + assert(stack_empty(&s2)); + } + + { + uint8_t buf[32]; + Stack st; + if (stack_init_raw(&st, (uint8_t *)buf, 32, sizeof(int)) != Ok) { + printf("Error: stack_init_raw did not init properly..."); + return 1; + } + + for (int i = 1; stack_push(&st, &i) == Ok; i++); + + assert(stack_full(&st)); + assert(stack_capacity(&st) == 8); + assert(stack_length(&st) == 8); + assert(!stack_empty(&st)); + + /* Make sure to not call stack_destroy or free here, since buf[] is static */ + + uint8_t buf2[64]; + stack_resize_raw(&st, buf2, 64); + + assert(stack_capacity(&st) == 16); + assert(stack_length(&st) == 8); + assert(!stack_empty(&st)); + assert(!stack_full(&st)); + + int r; + for (int i = 8; i >= 0; i--) { + if (stack_pop(&st, &r) != Ok) + return 1; + + printf("%d == %d\n", i, r); + assert(r == i); + } } }