smallvec_type.hpp

Go to the documentation of this file.
00001 /* $Id: smallvec_type.hpp 13781 2008-07-22 14:17:29Z peter1138 $ */
00002 
00005 #ifndef SMALLVEC_TYPE_HPP
00006 #define SMALLVEC_TYPE_HPP
00007 
00008 #include "alloc_func.hpp"
00009 #include "math_func.hpp"
00010 
00021 template <typename T, uint S>
00022 class SmallVector {
00023 protected:
00024   T *data;       
00025   uint items;    
00026   uint capacity; 
00027 
00028 public:
00029   SmallVector() : data(NULL), items(0), capacity(0) { }
00030 
00031   ~SmallVector()
00032   {
00033     free(this->data);
00034   }
00035 
00039   FORCEINLINE void Clear()
00040   {
00041     /* In fact we just reset the item counter avoiding the need to
00042      * probably reallocate the same amount of memory the list was
00043      * previously using. */
00044     this->items = 0;
00045   }
00046 
00050   FORCEINLINE void Compact()
00051   {
00052     uint capacity = Align(this->items, S);
00053     if (capacity >= this->capacity) return;
00054 
00055     this->capacity = capacity;
00056     this->data = ReallocT(this->data, this->capacity);
00057   }
00058 
00062   FORCEINLINE T *Append()
00063   {
00064     if (this->items == this->capacity) {
00065       this->capacity += S;
00066       this->data = ReallocT(this->data, this->capacity);
00067     }
00068 
00069     return &this->data[this->items++];
00070   }
00071 
00075   FORCEINLINE uint Length() const
00076   {
00077     return this->items;
00078   }
00079 
00085   FORCEINLINE const T *Begin() const
00086   {
00087     return this->data;
00088   }
00089 
00095   FORCEINLINE T *Begin()
00096   {
00097     return this->data;
00098   }
00099 
00105   FORCEINLINE const T *End() const
00106   {
00107     return &this->data[this->items];
00108   }
00109 
00115   FORCEINLINE T *End()
00116   {
00117     return &this->data[this->items];
00118   }
00119 
00126   FORCEINLINE const T *Get(uint index) const
00127   {
00128     return &this->data[index];
00129   }
00130 
00137   FORCEINLINE T *Get(uint index)
00138   {
00139     return &this->data[index];
00140   }
00141 
00148   FORCEINLINE const T &operator[](uint index) const
00149   {
00150     return this->data[index];
00151   }
00152 
00159   FORCEINLINE T &operator[](uint index)
00160   {
00161     return this->data[index];
00162   }
00163 };
00164 
00165 
00176 template <typename T, uint S>
00177 class AutoFreeSmallVector : public SmallVector<T, S> {
00178 public:
00179   ~AutoFreeSmallVector()
00180   {
00181     this->Clear();
00182   }
00183 
00187   FORCEINLINE void Clear()
00188   {
00189     for (uint i = 0; i < this->items; i++) {
00190       free(this->data[i]);
00191     }
00192 
00193     this->items = 0;
00194   }
00195 };
00196 
00197 #endif /* SMALLVEC_TYPE_HPP */

Generated on Wed Nov 19 19:01:37 2008 for openttd by  doxygen 1.5.6