00001 /* $Id$ */ 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 #include "str.hpp" 00017 00022 template <class T, uint B = 1024, uint N = B> 00023 class SmallArray { 00024 protected: 00025 typedef FixedSizeArray<T, B> SubArray; 00026 typedef FixedSizeArray<SubArray, N> SuperArray; 00027 00028 static const uint Tcapacity = B * N; 00029 00030 SuperArray data; 00031 00033 FORCEINLINE SubArray& FirstFreeSubArray() 00034 { 00035 uint super_size = data.Length(); 00036 if (super_size > 0) { 00037 SubArray& s = data[super_size - 1]; 00038 if (!s.IsFull()) return s; 00039 } 00040 return *data.AppendC(); 00041 } 00042 00043 public: 00045 FORCEINLINE SmallArray() { } 00047 FORCEINLINE void Clear() {data.Clear();} 00049 FORCEINLINE uint Length() const 00050 { 00051 uint super_size = data.Length(); 00052 if (super_size == 0) return 0; 00053 uint sub_size = data[super_size - 1].Length(); 00054 return (super_size - 1) * B + sub_size; 00055 } 00057 FORCEINLINE bool IsEmpty() { return data.IsEmpty(); } 00059 FORCEINLINE bool IsFull() { return data.IsFull() && data[N - 1].IsFull(); } 00061 FORCEINLINE T *Append() { return FirstFreeSubArray().Append(); } 00063 FORCEINLINE T *AppendC() { return FirstFreeSubArray().AppendC(); } 00065 FORCEINLINE T& operator [] (uint index) 00066 { 00067 const SubArray& s = data[index / B]; 00068 T& item = s[index % B]; 00069 return item; 00070 } 00072 FORCEINLINE const T& operator [] (uint index) const 00073 { 00074 const SubArray& s = data[index / B]; 00075 const T& item = s[index % B]; 00076 return item; 00077 } 00078 00083 template <typename D> void Dump(D &dmp) const 00084 { 00085 dmp.WriteLine("capacity = %d", Tcapacity); 00086 uint num_items = Length(); 00087 dmp.WriteLine("num_items = %d", num_items); 00088 CStrA name; 00089 for (uint i = 0; i < num_items; i++) { 00090 const T& item = (*this)[i]; 00091 name.Format("item[%d]", i); 00092 dmp.WriteStructT(name.Data(), &item); 00093 } 00094 } 00095 }; 00096 00097 #endif /* ARRAY_HPP */