xref: /netbsd-src/external/cddl/osnet/dist/tools/ctf/cvt/stack.c (revision ebc5b22cbe4297ba04381720bbd4dd2ad38312ff)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 #ifdef HAVE_NBTOOL_CONFIG_H
23 #include "nbtool_config.h"
24 #endif
25 
26 /*
27  * Copyright (c) 2001 by Sun Microsystems, Inc.
28  * All rights reserved.
29  */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 /*
34  * Routines for manipulating stacks
35  */
36 
37 #include <stdio.h>
38 #include <assert.h>
39 #include <stdlib.h>
40 
41 #include "stack.h"
42 #include "memory.h"
43 
44 #define	STACK_SEEDSIZE	5
45 
46 struct stk {
47 	int st_nument;
48 	int st_top;
49 	void **st_data;
50 
51 	void (*st_free)(void *);
52 };
53 
54 stk_t *
stack_new(void (* freep)(void *))55 stack_new(void (*freep)(void *))
56 {
57 	stk_t *sp;
58 
59 	sp = xmalloc(sizeof (stk_t));
60 	sp->st_nument = STACK_SEEDSIZE;
61 	sp->st_top = -1;
62 	sp->st_data = xmalloc(sizeof (void *) * sp->st_nument);
63 	sp->st_free = freep;
64 
65 	return (sp);
66 }
67 
68 void
stack_free(stk_t * sp)69 stack_free(stk_t *sp)
70 {
71 	int i;
72 
73 	if (sp->st_free) {
74 		for (i = 0; i <= sp->st_top; i++)
75 			sp->st_free(sp->st_data[i]);
76 	}
77 	free(sp->st_data);
78 	free(sp);
79 }
80 
81 void *
stack_pop(stk_t * sp)82 stack_pop(stk_t *sp)
83 {
84 	assert(sp->st_top >= 0);
85 
86 	return (sp->st_data[sp->st_top--]);
87 }
88 
89 void *
stack_peek(stk_t * sp)90 stack_peek(stk_t *sp)
91 {
92 	if (sp->st_top == -1)
93 		return (NULL);
94 
95 	return (sp->st_data[sp->st_top]);
96 }
97 
98 void
stack_push(stk_t * sp,void * data)99 stack_push(stk_t *sp, void *data)
100 {
101 	sp->st_top++;
102 
103 	if (sp->st_top == sp->st_nument) {
104 		sp->st_nument += STACK_SEEDSIZE;
105 		sp->st_data = xrealloc(sp->st_data,
106 		    sizeof (void *) * sp->st_nument);
107 	}
108 
109 	sp->st_data[sp->st_top] = data;
110 }
111 
112 int
stack_level(stk_t * sp)113 stack_level(stk_t *sp)
114 {
115 	return (sp->st_top + 1);
116 }
117