2008-05-08 20:43:59 +04:00
|
|
|
/*
|
|
|
|
* Copyright 2001-2008, Axel Dörfler, axeld@pinc-software.de.
|
2005-01-18 05:31:56 +03:00
|
|
|
* This file may be used under the terms of the MIT License.
|
|
|
|
*/
|
|
|
|
#ifndef KERNEL_UTIL_STACK_H
|
|
|
|
#define KERNEL_UTIL_STACK_H
|
|
|
|
|
|
|
|
|
2008-05-08 20:43:59 +04:00
|
|
|
#include <stdlib.h>
|
|
|
|
|
2005-01-18 05:31:56 +03:00
|
|
|
#include <SupportDefs.h>
|
|
|
|
|
2008-05-09 17:08:59 +04:00
|
|
|
#include <AutoDeleter.h>
|
|
|
|
|
2005-01-18 05:31:56 +03:00
|
|
|
|
|
|
|
template<class T> class Stack {
|
|
|
|
public:
|
|
|
|
Stack()
|
|
|
|
:
|
|
|
|
fArray(NULL),
|
|
|
|
fUsed(0),
|
|
|
|
fMax(0)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
~Stack()
|
|
|
|
{
|
|
|
|
free(fArray);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool IsEmpty() const
|
|
|
|
{
|
|
|
|
return fUsed == 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
void MakeEmpty()
|
|
|
|
{
|
|
|
|
// could also free the memory
|
|
|
|
fUsed = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
status_t Push(T value)
|
|
|
|
{
|
|
|
|
if (fUsed >= fMax) {
|
|
|
|
fMax += 16;
|
|
|
|
T *newArray = (T *)realloc(fArray, fMax * sizeof(T));
|
|
|
|
if (newArray == NULL)
|
|
|
|
return B_NO_MEMORY;
|
|
|
|
|
|
|
|
fArray = newArray;
|
|
|
|
}
|
|
|
|
fArray[fUsed++] = value;
|
|
|
|
return B_OK;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool Pop(T *value)
|
|
|
|
{
|
|
|
|
if (fUsed == 0)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
*value = fArray[--fUsed];
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2005-10-18 22:45:55 +04:00
|
|
|
T *Array()
|
|
|
|
{
|
|
|
|
return fArray;
|
|
|
|
}
|
|
|
|
|
|
|
|
int32 CountItems() const
|
|
|
|
{
|
|
|
|
return fUsed;
|
|
|
|
}
|
|
|
|
|
2005-01-18 05:31:56 +03:00
|
|
|
private:
|
|
|
|
T *fArray;
|
|
|
|
int32 fUsed;
|
|
|
|
int32 fMax;
|
|
|
|
};
|
|
|
|
|
2008-05-08 20:43:59 +04:00
|
|
|
|
2008-05-09 17:08:59 +04:00
|
|
|
template<typename T> class StackDelete {
|
|
|
|
public:
|
|
|
|
inline void operator()(Stack<T>* stack)
|
2008-05-08 20:43:59 +04:00
|
|
|
{
|
2008-05-09 17:08:59 +04:00
|
|
|
if (stack == NULL)
|
2008-05-08 20:43:59 +04:00
|
|
|
return;
|
2008-05-09 17:08:59 +04:00
|
|
|
|
2008-05-08 20:43:59 +04:00
|
|
|
T item;
|
2008-05-09 17:08:59 +04:00
|
|
|
while (stack->Pop(&item)) {
|
2008-05-08 20:43:59 +04:00
|
|
|
delete item;
|
|
|
|
}
|
2008-05-09 17:08:59 +04:00
|
|
|
|
|
|
|
delete stack;
|
2008-05-08 20:43:59 +04:00
|
|
|
}
|
2008-05-09 17:08:59 +04:00
|
|
|
};
|
2008-05-08 20:43:59 +04:00
|
|
|
|
2008-05-09 17:08:59 +04:00
|
|
|
template<typename T> class StackDeleter
|
|
|
|
: public BPrivate::AutoDeleter<Stack<T>, StackDelete<T> > {
|
|
|
|
public:
|
|
|
|
StackDeleter()
|
2008-05-08 20:43:59 +04:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2008-05-09 17:08:59 +04:00
|
|
|
StackDeleter(Stack<T>* stack)
|
|
|
|
: BPrivate::AutoDeleter<Stack<T>, StackDelete<T> >(stack)
|
|
|
|
{
|
|
|
|
}
|
2008-05-08 20:43:59 +04:00
|
|
|
};
|
|
|
|
|
2005-01-18 05:31:56 +03:00
|
|
|
#endif /* KERNEL_UTIL_STACK_H */
|