OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

array.hpp
Go to the documentation of this file.
1 /* $Id: array.hpp 23640 2011-12-20 17:57:56Z truebrain $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
9
12 #ifndef ARRAY_HPP
13 #define ARRAY_HPP
14
15 #include "fixedsizearray.hpp"
16 #include "str.hpp"
17
22 template <class T, uint B = 1024, uint N = B>
23 class SmallArray {
24 protected:
25 typedef FixedSizeArray<T, B> SubArray;
26 typedef FixedSizeArray<SubArray, N> SuperArray;
27
28 static const uint Tcapacity = B * N;
29
30 SuperArray data;
31
33 inline SubArray& FirstFreeSubArray()
34 {
35 uint super_size = data.Length();
36 if (super_size > 0) {
37 SubArray& s = data[super_size - 1];
38 if (!s.IsFull()) return s;
39 }
40 return *data.AppendC();
41 }
42
43 public:
45 inline SmallArray() { }
47 inline void Clear() {data.Clear();}
49 inline uint Length() const
50 {
51 uint super_size = data.Length();
52 if (super_size == 0) return 0;
53 uint sub_size = data[super_size - 1].Length();
54 return (super_size - 1) * B + sub_size;
55 }
57 inline bool IsEmpty() { return data.IsEmpty(); }
59 inline bool IsFull() { return data.IsFull() && data[N - 1].IsFull(); }
61 inline T *Append() { return FirstFreeSubArray().Append(); }
63 inline T *AppendC() { return FirstFreeSubArray().AppendC(); }
65 inline T& operator [] (uint index)
66 {
67 const SubArray& s = data[index / B];
68 T& item = s[index % B];
69 return item;
70 }
72 inline const T& operator [] (uint index) const
73 {
74 const SubArray& s = data[index / B];
75 const T& item = s[index % B];
76 return item;
77 }
78
83 template <typename D> void Dump(D &dmp) const
84 {
85 dmp.WriteLine("capacity = %d", Tcapacity);
86 uint num_items = Length();
87 dmp.WriteLine("num_items = %d", num_items);
88 CStrA name;
89 for (uint i = 0; i < num_items; i++) {
90 const T& item = (*this)[i];
91 name.Format("item[%d]", i);
92 dmp.WriteStructT(name.Data(), &item);
93 }
94 }
95 };
96
97 #endif /* ARRAY_HPP */