00001 /* $Id: array.hpp 17248 2009-08-21 20:21:05Z rubidium $ */ 00002 00003 /* 00004 * This file is part of OpenTTD. 00005 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. 00006 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 00007 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. 00008 */ 00009 00012 #ifndef ARRAY_HPP 00013 #define ARRAY_HPP 00014 00015 #include "fixedsizearray.hpp" 00016 00019 template <class Titem_, int Tblock_size_ = 1024, int Tnum_blocks_ = Tblock_size_> 00020 class CArrayT { 00021 public: 00022 typedef Titem_ Titem; 00023 typedef CFixedSizeArrayT<Titem_, Tblock_size_> CSubArray; 00024 typedef CFixedSizeArrayT<CSubArray, Tnum_blocks_> CSuperArray; 00025 00026 protected: 00027 CSuperArray m_a; 00028 00029 public: 00030 static const int Tblock_size = Tblock_size_; 00031 static const int Tnum_blocks = Tnum_blocks_; 00032 static const int Tcapacity = Tblock_size * Tnum_blocks; 00033 00035 FORCEINLINE CArrayT() { } 00037 FORCEINLINE void Clear() {m_a.Clear();} 00039 FORCEINLINE int Size() const 00040 { 00041 int super_size = m_a.Size(); 00042 if (super_size == 0) return 0; 00043 int sub_size = m_a[super_size - 1].Size(); 00044 return (super_size - 1) * Tblock_size + sub_size; 00045 } 00047 FORCEINLINE bool IsEmpty() { return m_a.IsEmpty(); } 00049 FORCEINLINE bool IsFull() { return m_a.IsFull() && m_a[Tnum_blocks - 1].IsFull(); } 00051 FORCEINLINE CSubArray& FirstFreeSubArray() 00052 { 00053 int super_size = m_a.Size(); 00054 if (super_size > 0) { 00055 CSubArray& sa = m_a[super_size - 1]; 00056 if (!sa.IsFull()) return sa; 00057 } 00058 return m_a.Add(); 00059 } 00061 FORCEINLINE Titem_& AddNC() { return FirstFreeSubArray().AddNC(); } 00063 FORCEINLINE Titem_& Add() { return FirstFreeSubArray().Add(); } 00065 FORCEINLINE Titem& operator [] (int idx) 00066 { 00067 CSubArray& sa = m_a[idx / Tblock_size]; 00068 Titem& item = sa [idx % Tblock_size]; 00069 return item; 00070 } 00072 FORCEINLINE const Titem& operator [] (int idx) const 00073 { 00074 const CSubArray& sa = m_a[idx / Tblock_size]; 00075 const Titem& item = sa [idx % Tblock_size]; 00076 return item; 00077 } 00078 00079 template <typename D> void Dump(D &dmp) const 00080 { 00081 dmp.WriteLine("capacity = %d", Tcapacity); 00082 int num_items = Size(); 00083 dmp.WriteLine("num_items = %d", num_items); 00084 CStrA name; 00085 for (int i = 0; i < num_items; i++) { 00086 const Titem& item = (*this)[i]; 00087 name.Format("item[%d]", i); 00088 dmp.WriteStructT(name.Data(), &item); 00089 } 00090 } 00091 }; 00092 00093 #endif /* ARRAY_HPP */