2db539f41968442841bf5849ff4738bda773a20c
[smdp.git] / cstack.c
1 /*
2  * An implementation of a char stack in heap memory.
3  * Copyright (C) 2014 Michael Goehler
4  *
5  * This file is part of mpd.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21
22 #include <stdlib.h> // malloc, realloc
23
24 #include "include/cstack.h"
25
26 cstack_t *cstack_init() {
27     cstack_t *stack = malloc(sizeof(cstack_t));
28     stack->content = (void*)0;
29     stack->alloc = stack->size = 0;
30     stack->head = -1;
31     stack->push = cstack_push;
32     stack->pop = cstack_pop;
33     stack->top = cstack_top;
34     stack->empty = cstack_empty;
35     stack->delete = cstack_delete;
36     return stack;
37 }
38
39 void cstack_push(cstack_t *self, char c) {
40     if(self->size + sizeof(c) > self->alloc) {
41         self->alloc += (sizeof(char));
42         self->content = realloc(self->content, self->alloc);
43     }
44     self->content[++self->head] = c;
45     self->size += (sizeof(char));
46 }
47
48 char cstack_pop(cstack_t *self) {
49     self->size -= (sizeof(char));
50     return self->content[self->head--];
51 }
52
53 int cstack_top(cstack_t *self, char c) {
54     if(self->head >= 0 && self->content[self->head] == c)
55         return 1;
56     return 0;
57 }
58
59 int cstack_empty(cstack_t *self)  {
60    return self->head == -1;
61 }
62
63 void cstack_delete(cstack_t *self) {
64     free(self->content);
65     free(self);
66 }
67