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