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