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/>.
10 /** @file array.hpp Array without an explicit maximum size. */
15 #include "fixedsizearray.hpp"
19 * Flexible array with size limit. Implemented as fixed size
20 * array of fixed size arrays
22 template <class T
, uint B
= 1024, uint N
= B
>
25 typedef FixedSizeArray
<T
, B
> SubArray
; ///< inner array
26 typedef FixedSizeArray
<SubArray
, N
> SuperArray
; ///< outer array
28 static const uint Tcapacity
= B
* N
; ///< total max number of items
30 SuperArray data
; ///< array of arrays of items
32 /** return first sub-array with free space for new item */
33 inline SubArray
& FirstFreeSubArray()
35 uint super_size
= data
.Length();
37 SubArray
&s
= data
[super_size
- 1];
38 if (!s
.IsFull()) return s
;
40 return *data
.AppendC();
44 /** implicit constructor */
49 /** Clear (destroy) all items */
55 /** Return actual number of items */
56 inline uint
Length() const
58 uint super_size
= data
.Length();
59 if (super_size
== 0) return 0;
60 uint sub_size
= data
[super_size
- 1].Length();
61 return (super_size
- 1) * B
+ sub_size
;
63 /** return true if array is empty */
66 return data
.IsEmpty();
69 /** return true if array is full */
72 return data
.IsFull() && data
[N
- 1].IsFull();
75 /** allocate but not construct new item */
78 return FirstFreeSubArray().Append();
81 /** allocate and construct new item */
84 return FirstFreeSubArray().AppendC();
87 /** indexed access (non-const) */
88 inline T
& operator[](uint index
)
90 const SubArray
&s
= data
[index
/ B
];
91 T
&item
= s
[index
% B
];
94 /** indexed access (const) */
95 inline const T
& operator[](uint index
) const
97 const SubArray
&s
= data
[index
/ B
];
98 const T
&item
= s
[index
% B
];
103 * Helper for creating a human readable output of this data.
104 * @param dmp The location to dump to.
106 template <typename D
> void Dump(D
&dmp
) const
108 dmp
.WriteLine("capacity = %d", Tcapacity
);
109 uint num_items
= Length();
110 dmp
.WriteLine("num_items = %d", num_items
);
112 for (uint i
= 0; i
< num_items
; i
++) {
113 const T
&item
= (*this)[i
];
114 name
.Format("item[%d]", i
);
115 dmp
.WriteStructT(name
.Data(), &item
);
120 #endif /* ARRAY_HPP */