2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 /** @file array.hpp Array without an explicit maximum size. */
13 #include "fixedsizearray.hpp"
14 #include "../string_func.h"
17 * Flexible array with size limit. Implemented as fixed size
18 * array of fixed size arrays
20 template <class T
, uint B
= 1024, uint N
= B
>
23 typedef FixedSizeArray
<T
, B
> SubArray
; ///< inner array
24 typedef FixedSizeArray
<SubArray
, N
> SuperArray
; ///< outer array
26 static const uint Tcapacity
= B
* N
; ///< total max number of items
28 SuperArray data
; ///< array of arrays of items
30 /** return first sub-array with free space for new item */
31 inline SubArray
&FirstFreeSubArray()
33 uint super_size
= data
.Length();
35 SubArray
&s
= data
[super_size
- 1];
36 if (!s
.IsFull()) return s
;
38 return *data
.AppendC();
42 /** implicit constructor */
47 /** Clear (destroy) all items */
53 /** Return actual number of items */
54 inline uint
Length() const
56 uint super_size
= data
.Length();
57 if (super_size
== 0) return 0;
58 uint sub_size
= data
[super_size
- 1].Length();
59 return (super_size
- 1) * B
+ sub_size
;
61 /** return true if array is empty */
64 return data
.IsEmpty();
67 /** return true if array is full */
70 return data
.IsFull() && data
[N
- 1].IsFull();
73 /** allocate but not construct new item */
76 return FirstFreeSubArray().Append();
79 /** allocate and construct new item */
82 return FirstFreeSubArray().AppendC();
85 /** indexed access (non-const) */
86 inline T
& operator[](uint index
)
88 const SubArray
&s
= data
[index
/ B
];
89 T
&item
= s
[index
% B
];
92 /** indexed access (const) */
93 inline const T
& operator[](uint index
) const
95 const SubArray
&s
= data
[index
/ B
];
96 const T
&item
= s
[index
% B
];
101 * Helper for creating a human readable output of this data.
102 * @param dmp The location to dump to.
104 template <typename D
> void Dump(D
&dmp
) const
106 dmp
.WriteValue("capacity", Tcapacity
);
107 uint num_items
= Length();
108 dmp
.WriteValue("num_items", num_items
);
109 for (uint i
= 0; i
< num_items
; i
++) {
110 const T
&item
= (*this)[i
];
111 dmp
.WriteStructT(fmt::format("item[{}]", i
), &item
);
116 #endif /* ARRAY_HPP */