2015-06-08 08:04:15 +00:00
|
|
|
/* radare - LGPL - Copyright 2007-2015 - ret2libc */
|
|
|
|
|
|
|
|
#include <r_util.h>
|
|
|
|
|
2016-10-18 21:15:51 +00:00
|
|
|
R_API RStack *r_stack_new(ut32 n) {
|
2015-06-08 08:04:15 +00:00
|
|
|
RStack *s = R_NEW0 (RStack);
|
2016-10-18 21:15:51 +00:00
|
|
|
if (!s) {
|
|
|
|
return NULL;
|
|
|
|
}
|
2015-06-12 10:00:18 +00:00
|
|
|
s->elems = R_NEWS0 (void *, n);
|
2015-12-08 12:24:21 +00:00
|
|
|
if (!s->elems) {
|
2015-06-16 21:00:15 +00:00
|
|
|
free (s);
|
2015-06-08 08:04:15 +00:00
|
|
|
return NULL;
|
2015-06-16 21:00:15 +00:00
|
|
|
}
|
2015-06-08 08:04:15 +00:00
|
|
|
s->n_elems = n;
|
|
|
|
s->top = -1;
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
|
2016-10-18 21:15:51 +00:00
|
|
|
R_API RStack *r_stack_newf(ut32 n, RStackFree f) {
|
|
|
|
RStack *s = r_stack_new (n);
|
|
|
|
if (s) {
|
|
|
|
s->free = f;
|
|
|
|
}
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
|
2015-12-08 12:24:21 +00:00
|
|
|
R_API void r_stack_free(RStack *s) {
|
2016-10-18 21:15:51 +00:00
|
|
|
if (s) {
|
|
|
|
if (s->free && s->top > 0) {
|
|
|
|
int i = 0;
|
|
|
|
for (i = 0; i < s->top; i++) {
|
|
|
|
s->free (s->elems[i]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
free (s->elems);
|
|
|
|
free (s);
|
|
|
|
}
|
2015-06-08 08:04:15 +00:00
|
|
|
}
|
|
|
|
|
2015-12-08 12:24:21 +00:00
|
|
|
R_API int r_stack_push(RStack *s, void *el) {
|
2015-06-08 08:04:15 +00:00
|
|
|
if (s->top == s->n_elems - 1) {
|
|
|
|
/* reallocate the stack */
|
|
|
|
s->n_elems *= 2;
|
2015-12-08 12:24:21 +00:00
|
|
|
s->elems = realloc (s->elems, s->n_elems * sizeof (void *));
|
2015-06-08 08:04:15 +00:00
|
|
|
if (!s->elems)
|
2016-07-12 20:15:19 +00:00
|
|
|
return false;
|
2015-06-08 08:04:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
s->top++;
|
|
|
|
s->elems[s->top] = el;
|
2016-07-12 20:15:19 +00:00
|
|
|
return true;
|
2015-06-08 08:04:15 +00:00
|
|
|
}
|
|
|
|
|
2016-11-20 18:20:14 +00:00
|
|
|
|
2016-10-18 21:15:51 +00:00
|
|
|
//the caller should be take care of the object returned
|
2015-12-08 12:24:21 +00:00
|
|
|
R_API void *r_stack_pop(RStack *s) {
|
2015-06-08 08:04:15 +00:00
|
|
|
void *res;
|
2016-10-18 21:15:51 +00:00
|
|
|
if (s->top == -1) {
|
2015-06-08 08:04:15 +00:00
|
|
|
return NULL;
|
2016-10-18 21:15:51 +00:00
|
|
|
}
|
2015-06-08 08:04:15 +00:00
|
|
|
res = s->elems[s->top];
|
|
|
|
s->top--;
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2016-11-20 18:20:14 +00:00
|
|
|
R_API bool r_stack_is_empty(RStack *s) {
|
2015-06-08 08:04:15 +00:00
|
|
|
return s->top == -1;
|
|
|
|
}
|
2015-06-12 09:08:05 +00:00
|
|
|
|
2015-12-08 12:24:21 +00:00
|
|
|
R_API unsigned int r_stack_size(RStack *s) {
|
2015-06-12 09:08:05 +00:00
|
|
|
return (unsigned int)(s->top + 1);
|
|
|
|
}
|