1/* Stack - a template stack class (plus some handy methods)
2 *
3 * Copyright 2001-2005, Axel Dörfler, axeld@pinc-software.de.
4 * This file may be used under the terms of the MIT License.
5 */
6#ifndef KERNEL_UTIL_STACK_H
7#define KERNEL_UTIL_STACK_H
8
9
10#include <SupportDefs.h>
11
12
13template<class T> class Stack {
14	public:
15		Stack()
16			:
17			fArray(NULL),
18			fUsed(0),
19			fMax(0)
20		{
21		}
22
23		~Stack()
24		{
25			free(fArray);
26		}
27
28		bool IsEmpty() const
29		{
30			return fUsed == 0;
31		}
32
33		void MakeEmpty()
34		{
35			// could also free the memory
36			fUsed = 0;
37		}
38
39		status_t Push(T value)
40		{
41			if (fUsed >= fMax) {
42				fMax += 16;
43				T *newArray = (T *)realloc(fArray, fMax * sizeof(T));
44				if (newArray == NULL)
45					return B_NO_MEMORY;
46
47				fArray = newArray;
48			}
49			fArray[fUsed++] = value;
50			return B_OK;
51		}
52
53		bool Pop(T *value)
54		{
55			if (fUsed == 0)
56				return false;
57
58			*value = fArray[--fUsed];
59			return true;
60		}
61
62		T *Array()
63		{
64			return fArray;
65		}
66
67		int32 CountItems() const
68		{
69			return fUsed;
70		}
71
72	private:
73		T		*fArray;
74		int32	fUsed;
75		int32	fMax;
76};
77
78#endif	/* KERNEL_UTIL_STACK_H */
79