From 8858e02afb31b6bbf97c985aea76181f9ba967cc Mon Sep 17 00:00:00 2001 From: Gregory Lirent Date: Wed, 24 Aug 2022 12:26:17 +0300 Subject: [PATCH] Add implementation of the stack reversion --- include/bits/memory.h | 1 + src/extra-stack.c | 48 ++++++++++++++++++++++++++++++++++++++----- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/include/bits/memory.h b/include/bits/memory.h index 5750557..5cc4635 100644 --- a/include/bits/memory.h +++ b/include/bits/memory.h @@ -16,6 +16,7 @@ extern void libcdsb_stack_init (stack_t* stack) Nonnull__(1) extern void libcdsb_stack_push (stack_t* stack, void* value) Nonnull__(1); extern void libcdsb_stack_push_many(stack_t* stack, size_t n, ...) Nonnull__(1); extern void* libcdsb_stack_pop (stack_t* stack) Nonnull__(1); +extern void libcdsb_stack_reverse (stack_t* stack) Nonnull__(1); extern void libcdsb_stack_flush (stack_t* stack) Nonnull__(1); extern void* libcdsb_aalloc (size_t a, size_t n) Warn_unused_result__; diff --git a/src/extra-stack.c b/src/extra-stack.c index 563a177..bdaca67 100644 --- a/src/extra-stack.c +++ b/src/extra-stack.c @@ -27,6 +27,7 @@ void libcdsb_stack_push(stack_t* x, void* value) { x->value = value; } + void libcdsb_stack_push_many(stack_t* x, size_t c, ...) { va_list args; @@ -52,6 +53,7 @@ void libcdsb_stack_push_many(stack_t* x, size_t c, ...) { va_end(args); } + void* libcdsb_stack_pop(stack_t* x) { stack_t* n; @@ -70,14 +72,50 @@ void* libcdsb_stack_pop(stack_t* x) { } -void libcdsb_stack_flush(stack_t* stack) { +void libcdsb_stack_reverse(stack_t* x) { + + stack_t z, *iter, *n, copy; + + + if (x->prev) { + z.prev = 0; + z.value = x->value; + iter = x->prev; + + while (iter->prev) { + n = iter; + iter = n->prev; + + copy.prev = z.prev; + copy.value = z.value; + + z.prev = n; + z.value = n->value; + + n->prev = copy.prev; + n->value = copy.value; + } + + copy.prev = z.prev; + copy.value = z.value; + + x->prev = iter; + x->value = iter->value; + + iter->prev = copy.prev; + iter->value = copy.value; + } +} + + +void libcdsb_stack_flush(stack_t* x) { stack_t* c; - while (stack->prev) { - c = stack->prev; - stack->prev = c->prev; + while (x->prev) { + c = x->prev; + x->prev = c->prev; free(c); } - stack->value = 0; + x->value = 0; }