From 8a813e877adea6c8e12a0845449fd45ff39f2574 Mon Sep 17 00:00:00 2001 From: Gregory Lirent Date: Tue, 7 Jun 2022 21:35:13 +0300 Subject: [PATCH] Add stack --- include/extra/memory.h | 15 ++++++++++++ src/extra.c | 53 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/include/extra/memory.h b/include/extra/memory.h index d0a584d..fb3ca3a 100644 --- a/include/extra/memory.h +++ b/include/extra/memory.h @@ -7,6 +7,16 @@ #ifndef LIBCDSB_EXTRA_MEMORY_H #define LIBCDSB_EXTRA_MEMORY_H +typedef struct libcdsb_stack_node { + struct libcdsb_stack_node* prev; + void* value; +} stack_t; + +extern void libcdsb_stack_init (stack_t* stack); +extern void libcdsb_stack_push (stack_t* stack, void* value); +extern void* libcdsb_stack_pop (stack_t* stack); +extern void libcdsb_stack_flush(stack_t* stack); + extern void* libcdsb_aalloc (size_t a, size_t n) LIBCDSB_nt__ LIBCDSB_wur__; extern void* libcdsb_malloc (size_t n) LIBCDSB_nt__ LIBCDSB_wur__; extern void* libcdsb_calloc (size_t n, size_t c) LIBCDSB_nt__ LIBCDSB_wur__; @@ -17,4 +27,9 @@ extern void* libcdsb_realloc(void *p, size_t n) LIBCDSB_nt__ LIBCDSB_wur__; #define calloc libcdsb_calloc #define realloc libcdsb_realloc +#define stack_init libcdsb_stack_init +#define stack_push libcdsb_stack_push +#define stack_pop libcdsb_stack_pop +#define stack_flush libcdsb_stack_flush + #endif /* LIBCDSB_EXTRA_MEMORY_H */ diff --git a/src/extra.c b/src/extra.c index 4d8ae6a..a1c261c 100644 --- a/src/extra.c +++ b/src/extra.c @@ -81,6 +81,59 @@ char* libcdsb_strndup(const char* s, size_t n) { /*#####################################################################################################################*/ +void libcdsb_stack_init(stack_t* x) { + memset(x, 0, sizeof(*x)); +} + + +void libcdsb_stack_push(stack_t* x, void* value) { + stack_t* n; + + if (x->value) { + if (!(n = malloc(sizeof(*n)))) + abort(); + + n->prev = x->prev; + n->value = x->value; + x->prev = n; + } + + x->value = value; +} + +void* libcdsb_stack_pop(stack_t* x) { + + stack_t* n; + void* v; + + v = x->value; + + if (x->prev) { + n = x->prev; + x->prev = n->prev; + x->value = n->value; + free(n); + } else x->value = 0; + + return v; +} + + +void libcdsb_stack_flush(stack_t* stack) { + stack_t* c; + + while (stack->prev) { + c = stack->prev; + stack->prev = c->prev; + free(c); + } + + stack->value = 0; +} + +/*#####################################################################################################################*/ + + size_t libcdsb_strlen(const char* s) { static const size_t m = (sizeof(size_t) == 8) ? 0x8080808080808080UL : 0x80808080UL; static const size_t d = (sizeof(size_t) == 8) ? 0x0101010101010101UL : 0x01010101UL;