feat(stack): implemented schrink to fit function

This commit is contained in:
Mineplay 2025-05-15 12:28:54 -05:00
parent 5f87686633
commit f7ac0e5192
3 changed files with 25 additions and 0 deletions

View file

@ -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; }

View file

@ -21,6 +21,7 @@
* -----------------------------------------------------------------------------
*/
#include "../../Include/Fledasty/Core/Stack.h"
#include "Fledasty/Utils/Error.h"
#include <Hallocy/Core/Allocator.h>
#include <Hallocy/Core/Memory.h>
@ -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;
}

View file

@ -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);