Created
July 25, 2020 18:36
-
-
Save vanaur/60f30aca8f425b8c6d6f16df52d6d241 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef struct stack_s | |
{ | |
long sz; | |
long sp; | |
void **s; | |
} *stack_t; | |
#define stack_pop(__t,__s) ((__t)_stack_pop(__s)) | |
#define stack_peek(__t,__s) ((__t)_stack_peek(__s)) | |
#define stack_is_empty(_s) (_s->sp == -1) | |
#define stack_not_empty(_s) (_s->sp != -1) | |
#define STACK_DEFAULT_RESIZE 1024 | |
static inline stack_t stack_new(); | |
static inline stack_t stack_dup(const stack_t s); | |
static inline stack_t stack_clone(const stack_t s, void *(*clone_entry)(void *)); | |
static inline void stack_free(stack_t s); | |
static inline void stack_push(stack_t s, void *item); | |
static inline void *_stack_pop(stack_t s); | |
static inline void *_stack_peek(stack_t s); | |
static inline stack_t stack_new() | |
{ | |
stack_t ret = malloc(sizeof *ret); | |
ASSERT(ret != NULL); | |
memset(ret, 0, sizeof(*ret)); | |
ret->sp = -1; | |
return ret; | |
} | |
static inline stack_t stack_dup(const stack_t s) | |
{ | |
stack_t ret = stack_new(); | |
ret->s = malloc(s->sz * sizeof(void*)); | |
memcpy(ret->s, s->s, s->sz * sizeof(void*)); | |
ret->sp = s->sp; | |
ret->sz = s->sz; | |
return ret; | |
} | |
static inline stack_t stack_clone(const stack_t s, void *(*clone_entry)(void *)) | |
{ | |
stack_t ret = stack_new(); | |
ret->s = malloc(s->sz * sizeof(void *)); | |
ret->sp = s->sp; | |
ret->sz = s->sz; | |
for (long i = 0; i <= s->sp; i++) | |
ret->s[i] = clone_entry(s->s[i]); | |
return ret; | |
} | |
static inline void stack_push(stack_t s, void *item) | |
{ | |
ASSERT(s != NULL); | |
s->sp += 1; | |
if (s->sz <= s->sp) | |
{ | |
s->sz += STACK_DEFAULT_RESIZE; | |
s->s = (void **)realloc(s->s, s->sz * sizeof(void *)); | |
} | |
s->s[s->sp] = item; | |
} | |
static inline void stack_free(stack_t s) | |
{ | |
ASSERT(s != NULL); | |
if (s->s) free(s->s); | |
free(s); | |
} | |
static inline void *_stack_pop(stack_t s) | |
{ | |
if (s->sp == -1) return NULL; | |
return s->s[s->sp--]; | |
} | |
static inline void *_stack_peek(stack_t s) | |
{ | |
if (s->sp == -1) return NULL; | |
return s->s[s->sp]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment