4763b5b5c9b4e2e48860810499d07bc0061d310a
[smdp.git] / src / 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 mdp.
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 <stdio.h> // fprintf
23 #include <stdlib.h> // malloc, realloc
24
25 #include "cstack.h"
26
27 cstack_t *cstack_init() {
28     cstack_t *stack = NULL;
29     if((stack = malloc(sizeof(cstack_t))) != NULL) {
30         stack->content = NULL;
31         stack->alloc = stack->size = 0;
32         stack->head = -1;
33         stack->push = cstack_push;
34         stack->pop = cstack_pop;
35         stack->top = cstack_top;
36         stack->empty = cstack_empty;
37         stack->delete = cstack_delete;
38     } else {
39         fprintf(stderr, "%s\n", "cstack_init() failed to allocate memory.");
40         exit(EXIT_FAILURE);
41     }
42     return stack;
43 }
44
45 void cstack_push(cstack_t *self, char c) {
46     if(self->size + sizeof(c) > self->alloc) {
47         self->alloc += (sizeof(char));
48         if((self->content = realloc(self->content, self->alloc)) == NULL) {
49             fprintf(stderr, "%s\n", "cstack_push() failed to reallocate memory.");
50             exit(EXIT_FAILURE);
51         }
52     }
53     self->content[++self->head] = c;
54     self->size += (sizeof(char));
55 }
56
57 char cstack_pop(cstack_t *self) {
58     self->size -= (sizeof(char));
59     return self->content[self->head--];
60 }
61
62 bool cstack_top(cstack_t *self, char c) {
63     return self->head >= 0 && self->content[self->head] == c;
64 }
65
66 bool cstack_empty(cstack_t *self) {
67     return self->head == -1;
68 }
69
70 void cstack_delete(cstack_t *self) {
71     free(self->content);
72     free(self);
73 }