|
|
| version 1.3, 2001/03/07 13:54:46 | version 1.27, 2012/03/16 09:24:10 |
|---|---|
| Line 1 | Line 1 |
| /* | /** @file |
| $Id$ | Parser: stack class decl. |
| Copyright (c) 2001-2012 Art. Lebedev Studio (http://www.artlebedev.com) | |
| Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru) | |
| */ | */ |
| #ifndef PA_STACK_H | #ifndef PA_STACK_H |
| #define PA_STACK_H | #define PA_STACK_H |
| #define IDENT_PA_STACK_H "$Id$" | |
| #include "pa_array.h" | #include "pa_array.h" |
| class Stack : public Array { | /// simple stack based on Array |
| template<typename T> class Stack: public Array<T> { | |
| public: | public: |
| Stack(Pool& apool) : Array(apool), ftop(0) { | Stack(size_t initial=4) : Array<T>(initial){} |
| } | |
| void push(Item *item) { | inline void push(T item) { |
| if(ftop<size()) // cell is already allocated? | if(this->is_full()) |
| put(ftop, item); // use it | expand(this->fallocated); // free is not called, so expanding a lot to decrease memory waste |
| else | this->felements[this->fused++]=item; |
| *this+=item; // append it | |
| ftop++; | |
| } | |
| Item *pop() { | |
| return get(--ftop); | |
| } | } |
| Item *operator [] (int top_offset) { | inline T pop() { |
| return get(ftop-top_offset-1); | return this->felements[--this->fused]; |
| } | } |
| int top() { return ftop-1; } | inline bool is_empty() { return this->fused==0; } |
| inline size_t top_index() { return this->fused; } | |
| inline void set_top_index(size_t atop) { this->fused=atop; } | |
| inline T top_value() { | |
| assert(!is_empty()); | |
| return this->felements[this->fused-1]; | |
| } | |
| private: | /// call this prior to collecting garbage [in unused part of stack there may be pointers(unused)] |
| void wipe_unused() { | |
| if(size_t above_top_size=this->fallocated-this->fused) | |
| memset(&this->felements[this->fused], 0, above_top_size*sizeof(T)); | |
| } | |
| // deepest used index | protected: |
| int ftop; | |
| void expand(size_t delta) { | |
| size_t new_allocated=this->fallocated+delta; | |
| // we can't use realloc as MethodParams references allocated stack | |
| T* new_elements = (T *)pa_malloc(new_allocated*sizeof(T)); | |
| memcpy(new_elements, this->felements, this->fallocated*sizeof(T)); | |
| this->felements=new_elements; | |
| this->fallocated=new_allocated; | |
| } | |
| }; | }; |
| #endif | #endif |