1 /* Licensed under BSD-MIT - see LICENSE file for details */
9 #include <ccan/container_of/container_of.h>
12 * struct lstack_link - a stack link
13 * @down: immedately lower entry in the stack, or NULL if this is the bottom.
15 * This is used as an entry in a stack.
20 * struct lstack_link sl;
24 struct lstack_link *down;
28 * struct lstack - a stack
29 * @b: the top of the stack (NULL if empty)
32 struct lstack_link *top;
36 * LSTACK - define and initialize an empty stack
37 * @name: the name of the lstack.
39 * The LSTACK macro defines an lstack and initializes it to an empty
40 * stack. It can be prepended by "static" to define a static lstack.
48 * assert(lstack_empty(&my_stack));
50 #define LSTACK(name) \
51 struct lstack name = { NULL, }
54 * lstack_init - initialize a stack
55 * @h: the lstack to set to an empty stack
58 * struct lstack *sp = malloc(sizeof(*sp));
61 static inline void lstack_init(struct lstack *s)
67 * lstack_empty - is a stack empty?
70 * If the stack is empty, returns true.
73 * assert(lstack_empty(sp));
75 static inline bool lstack_empty(const struct lstack *s)
77 return (s->top == NULL);
81 * lstack_entry - convert an lstack_link back into the structure containing it.
83 * @type: the type of the entry
84 * @member: the lstack_link member of the type
89 * struct lstack_link sl;
91 * assert(lstack_entry(&st.sl, struct stacker, sl) == &st);
93 #define lstack_entry(n, type, member) container_of_or_null(n, type, member)
96 * lstack_top - get top entry in a stack
98 * @type: the type of stack entries
99 * @member: the lstack_link entry
101 * If the stack is empty, returns NULL.
106 * t = lstack_top(sp, struct stacker, sl);
107 * assert(lstack_pop(sp, struct stacker, sl) == t);
109 #define lstack_top(s, type, member) \
110 lstack_entry(lstack_top_((s)), type, member)
111 static inline struct lstack_link *lstack_top_(const struct lstack *s)
117 * lstack_push - add an entry to the top of the stack
118 * @s: the stack to add the node to
119 * @e: the item to push
120 * @member: the lstack_link field of *e
122 * The lstack_link does not need to be initialized; it will be overwritten.
124 #define lstack_push(s, e, member) \
125 lstack_push_((s), &((e)->member))
126 static inline void lstack_push_(struct lstack *s, struct lstack_link *e)
128 e->down = lstack_top_(s);
133 * lstack_pop - remove and return the entry from the top of the stack
135 * @type: the type of stack entries
136 * @member: the lstack_link field of @type
138 * Note that this leaves the returned entry's link in an undefined
139 * state; it can be added to another stack, but not deleted again.
141 #define lstack_pop(s, type, member) \
142 lstack_entry(lstack_pop_((s)), type, member)
143 static inline struct lstack_link *lstack_pop_(struct lstack *s)
145 struct lstack_link *top;
150 top = lstack_top_(s);
155 #endif /* CCAN_LSTACK_H */