329
|
1 /*
|
|
2 lw_stack.c
|
|
3
|
|
4 Copyright © 2010 William Astle
|
|
5
|
|
6 This file is part of LWTOOLS.
|
|
7
|
|
8 LWTOOLS is free software: you can redistribute it and/or modify it under the
|
|
9 terms of the GNU General Public License as published by the Free Software
|
|
10 Foundation, either version 3 of the License, or (at your option) any later
|
|
11 version.
|
|
12
|
|
13 This program is distributed in the hope that it will be useful, but WITHOUT
|
|
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
|
16 more details.
|
|
17
|
|
18 You should have received a copy of the GNU General Public License along with
|
|
19 this program. If not, see <http://www.gnu.org/licenses/>.
|
|
20 */
|
|
21
|
|
22 #include <config.h>
|
|
23
|
|
24 #define ___lw_stack_c_seen___
|
|
25 #include <lw_stack.h>
|
|
26 #include <lw_alloc.h>
|
|
27
|
|
28 /* this is technically valid but dubious */
|
|
29 #define NULL 0
|
|
30
|
|
31 lw_stack_t lw_stack_create(void (*freefn)(void *d))
|
|
32 {
|
|
33 lw_stack_t S;
|
|
34
|
|
35 S = lw_alloc(sizeof(lw_stack_t));
|
|
36 S -> head = NULL;
|
|
37 S -> freefn = freefn;
|
|
38 return S;
|
|
39 }
|
|
40
|
|
41 void *lw_stack_pop(lw_stack_t S)
|
|
42 {
|
|
43 if (S -> head)
|
|
44 {
|
|
45 void *ret, *r2;
|
|
46
|
|
47 ret = S -> head -> data;
|
|
48 r2 = S -> head;
|
|
49 S -> head = S -> head -> next;
|
|
50 lw_free(r2);
|
|
51 return ret;
|
|
52 }
|
|
53 return NULL;
|
|
54 }
|
|
55
|
|
56 void lw_stack_destroy(lw_stack_t S)
|
|
57 {
|
|
58 void *d;
|
|
59
|
|
60 while (d = lw_stack_pop(S))
|
|
61 (S->freefn)(d);
|
|
62 lw_free(S);
|
|
63 }
|
|
64
|
|
65 void *lw_stack_top(lw_stack_t S)
|
|
66 {
|
|
67 if (S -> head)
|
|
68 return S -> head -> data;
|
|
69 return NULL;
|
|
70 }
|
|
71
|
|
72 void lw_stack_push(lw_stack_t S, void *item)
|
|
73 {
|
|
74 struct lw_stack_node_priv *t;
|
|
75
|
|
76 t = lw_alloc(sizeof(struct lw_stack_node_priv));
|
|
77 t -> next = S -> head;
|
|
78 S -> head = t;
|
|
79 t -> data = item;
|
|
80 }
|