Add implementation of the stack reversion

This commit is contained in:
Gregory Lirent 2022-08-24 12:26:17 +03:00
parent d7bd9be567
commit 8858e02afb
2 changed files with 44 additions and 5 deletions

View File

@ -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 (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_push_many(stack_t* stack, size_t n, ...) Nonnull__(1);
extern void* libcdsb_stack_pop (stack_t* stack) 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_stack_flush (stack_t* stack) Nonnull__(1);
extern void* libcdsb_aalloc (size_t a, size_t n) Warn_unused_result__; extern void* libcdsb_aalloc (size_t a, size_t n) Warn_unused_result__;

View File

@ -27,6 +27,7 @@ void libcdsb_stack_push(stack_t* x, void* value) {
x->value = value; x->value = value;
} }
void libcdsb_stack_push_many(stack_t* x, size_t c, ...) { void libcdsb_stack_push_many(stack_t* x, size_t c, ...) {
va_list args; va_list args;
@ -52,6 +53,7 @@ void libcdsb_stack_push_many(stack_t* x, size_t c, ...) {
va_end(args); va_end(args);
} }
void* libcdsb_stack_pop(stack_t* x) { void* libcdsb_stack_pop(stack_t* x) {
stack_t* n; 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; stack_t* c;
while (stack->prev) { while (x->prev) {
c = stack->prev; c = x->prev;
stack->prev = c->prev; x->prev = c->prev;
free(c); free(c);
} }
stack->value = 0; x->value = 0;
} }