1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2007 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): Pavol "PM OnoTo" Marko
8 * ============================
11 #ifndef __SH_STACK_H__
12 #define __SH_STACK_H__
15 #include "sh_vector.h"
19 // May _never_ reallocate used memory!
21 template <class T> class CStack
23 static const size_t SECTOR_SIZE = 16;
25 CVector<T*> m_Sectors; // Stores sectors
31 typename CVector<T*>::iterator sect_iter;
32 for (sect_iter = m_Sectors.begin(); sect_iter != m_Sectors.end(); ++sect_iter)
39 friend class iterator;
45 iterator(CStack<T> *pParent, size_t id) : m_pParent(pParent), m_Index(id)
49 iterator(CStack<T> *pParent) : m_pParent(pParent), m_Index(0)
53 iterator() : m_pParent(NULL), m_Index(0)
59 return m_pParent->at(m_Index);
61 const T &operator *() const
63 return m_pParent->at(m_Index);
68 return &(m_pParent->at(m_Index));
71 const T * operator->() const
73 return &(m_pParent->at(m_Index));
76 iterator & operator++() // preincrement
82 iterator operator++(int) // postincrement
89 iterator & operator--() // predecrement
95 iterator operator--(int) // postdecrememnt
102 bool operator==(const iterator & right) const
104 return (m_pParent == right.m_pParent && m_Index == right.m_Index);
107 bool operator!=(const iterator & right) const
109 return !(*this == right);
112 CStack() : m_UsedSize(0)
116 CStack(const CStack &other)
118 for (typename CVector<T*>::iterator sect_iter = other.m_Sectors.begin();
119 sect_iter != other.m_Sectors.end(); ++sect_iter)
121 m_Sectors.push_back(new T[SECTOR_SIZE]);
122 for (size_t i = 0; i < SECTOR_SIZE; ++i)
123 m_Sectors.back()[i] = (*sect_iter)[i];
125 m_UsedSize = other.m_UsedSize;
128 CStack & operator =(const CStack &other)
131 for (typename CVector<T*>::iterator sect_iter = other.m_Sectors.begin();
132 sect_iter != other.m_Sectors.end(); ++sect_iter)
134 m_Sectors.push_back(new T[SECTOR_SIZE]);
135 for (size_t i = 0; i < SECTOR_SIZE; ++i)
136 m_Sectors.back()[i] = (*sect_iter)[i];
138 m_UsedSize = other.m_UsedSize;
149 return m_Sectors[x / SECTOR_SIZE][x % SECTOR_SIZE];
152 const T &at(size_t x) const
154 return m_Sectors[x / SECTOR_SIZE][x % SECTOR_SIZE];
157 bool push(const T &val)
159 if ((m_UsedSize / SECTOR_SIZE) >= m_Sectors.size())
162 m_Sectors.push_back(new T[SECTOR_SIZE]);
165 at(m_UsedSize) = val;
173 if ((m_UsedSize / SECTOR_SIZE) >= m_Sectors.size())
176 m_Sectors.push_back(new T[SECTOR_SIZE]);
179 return &(at(m_UsedSize++));
194 return at(m_UsedSize-1);
197 const T &front() const
199 return at(m_UsedSize-1);
204 return at(m_UsedSize-2);
207 const T &second() const
209 return at(m_UsedSize-2);
214 return iterator(this, 0);
218 return iterator(this, m_UsedSize);
227 return m_UsedSize == 0 ? true : false;
230 }; //namespace SourceHook