-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
91 lines (58 loc) · 3.09 KB
/
stack.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#ifndef stack_1LKrZ2oprBaT
#define stack_1LKrZ2oprBaT
#include <err.h>
#include <stdlib.h>
/* This is not assert: It is not intended to be disabled in non-debug
mode. Use this for acceptable runtime errors to terminate the
program. */
#define ERRIF(c) do { \
if (c) \
err(1, "Fatal " #c " at " __FILE__ \
":%d; errno", __LINE__); \
} while (0)
/* An array-based stack. `STACK(foo)` is the type, so `STACK(int)
bar` declares variable `bar` to be a stack of integers. The stack
is not initialised. */
#define STACK(ty) struct { size_t alloc, used; ty *array; }
/* Allocate memory in stack `foo` for `s` entries. The stack is
empty. Terminates the program if `malloc` fails. */
#define ALLOCATE(foo, s) do { \
foo.alloc = s; \
foo.used = 0; \
foo.array = malloc(foo.alloc * sizeof(*foo.array)); \
ERRIF(!foo.array); \
} while (0)
/* If stack `foo` is full, double its size. Terminates the program if
`realloc` fails. */
#define ENOUGH(foo) do { \
if (foo.used >= foo.alloc) { \
foo.alloc *= 2; \
foo.array = realloc(foo.array, foo.alloc * sizeof(*foo.array)); \
ERRIF(!foo.array); \
} \
} while (0)
/* Reduce allocated memory of stack to the minimum required to contain
its items. If stack `foo` is emty, free memory. Terminates
the program if `realloc` fails. */
#define TRIM(foo) do { \
foo.alloc = foo.used; \
if (foo.alloc) { \
foo.array = realloc(foo.array, foo.alloc * sizeof(*foo.array)); \
ERRIF(!foo.array); \
} else { \
free(foo.array); \
foo.array = NULL; \
} \
} while (0)
/* Push `val` on stack `foo`. The result is undefined if the stack is
not large enough. No check is performed! */
#define PUSH(foo, val) (foo.array[foo.used++] = (val))
/* Get number of entries on the stack */
#define COUNT(foo) (foo.used)
/* Pop value from stack `foo`. The result is undefined if the stack
is empty. No check is performed! */
#define POP(foo) (foo.array[--foo.used])
/* Get `idx`-th value from stack. The result is undefined if the
stack is not large enough. No check is performed! */
#define AT(foo, idx) (foo.array[idx])
#endif