ESH

Executive Shell
git clone http://git.omkov.net/ESH
Log | Tree | Refs | README | Download

ESH/src/util/stack.c (36 lines, 799 B) -rw-r--r-- blame download

01234567891011121314151617181920212223242526272829303132333435
// Copyright (C) 2023, Jakob Wakeling
// All rights reserved.

#include "stack.h"
#include "util.h"

#include <stdlib.h>
#include <string.h>

/* Initialise a stack. */
stack stack_init(u64 el, void (*free)(void *)) {
	return (stack){ .el = el, .free = free };
}

/* Uninitialise a stack. */
void stack_free(stack *s) {
	if (s) {
		if (s->free) for (u64 i = 0; i < s->al; i += 1) {
			void *e; memcpy(&e, s->a + i * s->el, s->el); s->free(e);
		}

		free(s->a);
	}
}

/* Push a pointer to the top of a stack. */
void _stack_push(stack *s, void *e) {
	s->a = xrealloc(s->a, (s->ac += 1) * s->el);
	memcpy(s->a + (s->al * s->el), &e, s->el); s->al += 1;
}

/* Pop a pointer from the top of a stack. */
void *stack_pop(stack *s) {
	void *e; memcpy(&e, s->a + ((s->al -= 1) * s->el), s->el); return e;
}