btrfs: [] on the end of a struct field is a variable length array.
[haiku.git] / headers / private / kernel / util / Stack.h
blobd32a8023c6f48d54deabcb6e206bdf1bc1322299
1 /*
2 * Copyright 2001-2008, Axel Dörfler, axeld@pinc-software.de.
3 * This file may be used under the terms of the MIT License.
4 */
5 #ifndef KERNEL_UTIL_STACK_H
6 #define KERNEL_UTIL_STACK_H
9 #include <stdlib.h>
11 #include <SupportDefs.h>
13 #include <AutoDeleter.h>
16 template<class T> class Stack {
17 public:
18 Stack()
20 fArray(NULL),
21 fUsed(0),
22 fMax(0)
26 ~Stack()
28 free(fArray);
31 bool IsEmpty() const
33 return fUsed == 0;
36 void MakeEmpty()
38 // could also free the memory
39 fUsed = 0;
42 status_t Push(T value)
44 if (fUsed >= fMax) {
45 fMax += 16;
46 T *newArray = (T *)realloc(fArray, fMax * sizeof(T));
47 if (newArray == NULL)
48 return B_NO_MEMORY;
50 fArray = newArray;
52 fArray[fUsed++] = value;
53 return B_OK;
56 bool Pop(T *value)
58 if (fUsed == 0)
59 return false;
61 *value = fArray[--fUsed];
62 return true;
65 T *Array()
67 return fArray;
70 int32 CountItems() const
72 return fUsed;
75 private:
76 T *fArray;
77 int32 fUsed;
78 int32 fMax;
82 template<typename T> class StackDelete {
83 public:
84 inline void operator()(Stack<T>* stack)
86 if (stack == NULL)
87 return;
89 T item;
90 while (stack->Pop(&item)) {
91 delete item;
94 delete stack;
98 template<typename T> class StackDeleter
99 : public BPrivate::AutoDeleter<Stack<T>, StackDelete<T> > {
100 public:
101 StackDeleter()
105 StackDeleter(Stack<T>* stack)
106 : BPrivate::AutoDeleter<Stack<T>, StackDelete<T> >(stack)
111 #endif /* KERNEL_UTIL_STACK_H */