diff --git a/Include/Fledasty/Core/Stack.h b/Include/Fledasty/Core/Stack.h index cbee423..268b297 100644 --- a/Include/Fledasty/Core/Stack.h +++ b/Include/Fledasty/Core/Stack.h @@ -43,6 +43,7 @@ void *fledasty_stack_peek(const FledastyStack *current_stack); void *fledasty_stack_pop(FledastyStack *current_stack); FledastyError fledasty_stack_clear(FledastyStack *current_stack); +FledastyError fledasty_stack_shrink_to_fit(FledastyStack *current_stack); static inline bool fledasty_stack_is_empty(const FledastyStack *current_stack) { return current_stack == NULL || current_stack->size == 0; } diff --git a/Src/Core/Stack.c b/Src/Core/Stack.c index bcec7c3..3a6bcf6 100644 --- a/Src/Core/Stack.c +++ b/Src/Core/Stack.c @@ -21,6 +21,7 @@ * ----------------------------------------------------------------------------- */ #include "../../Include/Fledasty/Core/Stack.h" +#include "Fledasty/Utils/Error.h" #include #include @@ -114,3 +115,23 @@ FledastyError fledasty_stack_clear(FledastyStack *current_stack) { current_stack->size = 0; return FLEDASTY_ERROR_NONE; } + +FledastyError fledasty_stack_shrink_to_fit(FledastyStack *current_stack) { + if (current_stack == NULL) { + return FLEDASTY_ERROR_INVALID_POINTER; + } + + current_stack->capacity = (current_stack->size == 0) ? 10 : current_stack->size; + unsigned char *shrinked_buffer = (unsigned char*)hallocy_malloc(current_stack->capacity); + if (shrinked_buffer == NULL) { + return FLEDASTY_ERROR_FAILED_ALLOCATION; + } + + hallocy_copy_memory(shrinked_buffer, current_stack->buffer, current_stack->size); + if (hallocy_free(current_stack->buffer) != HALLOCY_ERROR_NONE) { + return FLEDASTY_ERROR_FAILED_ALLOCATION; + } + + current_stack->buffer = shrinked_buffer; + return FLEDASTY_ERROR_NONE; +} diff --git a/Tests/Main.c b/Tests/Main.c index 963c553..9c10342 100644 --- a/Tests/Main.c +++ b/Tests/Main.c @@ -61,6 +61,9 @@ int main() { fledasty_stack_push(&test_stack, &i); } + fledasty_stack_shrink_to_fit(&test_stack); + printf("Stack schrinked to fit %s\n", (test_stack.capacity == test_stack.size) ? "succeeded" : "failed"); + int *peeked_stack_data = (int*)fledasty_stack_peek(&test_stack); printf("Stack peeked: %d\n", *peeked_stack_data);