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 #include <stdlib.h> 13 14 template<class T> class Stack { 15 public: 16 Stack() 17 : 18 fArray(NULL), 19 fUsed(0), 20 fMax(0) 21 { 22 } 23 24 ~Stack() 25 { 26 free(fArray); 27 } 28 29 bool IsEmpty() const 30 { 31 return fUsed == 0; 32 } 33 34 void MakeEmpty() 35 { 36 // could also free the memory 37 fUsed = 0; 38 } 39 40 status_t Push(T value) 41 { 42 if (fUsed >= fMax) { 43 fMax += 16; 44 T *newArray = (T *)realloc(fArray, fMax * sizeof(T)); 45 if (newArray == NULL) 46 return B_NO_MEMORY; 47 48 fArray = newArray; 49 } 50 fArray[fUsed++] = value; 51 return B_OK; 52 } 53 54 bool Pop(T *value) 55 { 56 if (fUsed == 0) 57 return false; 58 59 *value = fArray[--fUsed]; 60 return true; 61 } 62 63 T *Array() 64 { 65 return fArray; 66 } 67 68 int32 CountItems() const 69 { 70 return fUsed; 71 } 72 73 private: 74 T *fArray; 75 int32 fUsed; 76 int32 fMax; 77 }; 78 79 #endif /* KERNEL_UTIL_STACK_H */ 80