-
Notifications
You must be signed in to change notification settings - Fork 2
/
stack.h
60 lines (51 loc) · 2.08 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
/**
Copyright (c) 2021 Vicente Romero Calero. All rights reserved.
Licensed under the MIT License.
See LICENSE file in the project root for full license information.
*/
#ifndef VTENC_STACK_H_
#define VTENC_STACK_H_
#include <stddef.h>
#include <string.h>
#define DEFINE_STACK_STRUCT(name, type, max_size) \
struct name { \
type data[max_size]; \
size_t head; \
}
#define DEFINE_STACK_INIT_FN(name) \
static inline void name##_init(struct name *s) \
{ \
s->head = 0; \
}
#define DEFINE_STACK_EMPTY_FN(name) \
static inline int name##_empty(struct name *s) \
{ \
return s->head == 0; \
}
#define DEFINE_STACK_SIZE_FN(name) \
static inline size_t name##_size(struct name *s) \
{ \
return s->head; \
}
#define DEFINE_STACK_PUSH_FN(name, type) \
static inline void name##_push(struct name *s, const type *element) \
{ \
memcpy(s->data + s->head, element, sizeof(type)); \
s->head++; \
}
#define DEFINE_STACK_POP_FN(name, type) \
static inline type *name##_pop(struct name *s) \
{ \
return &s->data[--s->head]; \
}
/**
* Creates a LIFO stack with a fixed maximum size `max_size`.
*/
#define CREATE_STACK(name, type, max_size) \
DEFINE_STACK_STRUCT(name, type, max_size); \
DEFINE_STACK_INIT_FN(name) \
DEFINE_STACK_EMPTY_FN(name) \
DEFINE_STACK_SIZE_FN(name) \
DEFINE_STACK_PUSH_FN(name, type) \
DEFINE_STACK_POP_FN(name, type)
#endif /* VTENC_STACK_H_ */