OpenTTD Source 20261129-master-g72a8bdc861
saveload_oldpool.h
Go to the documentation of this file.
1/*
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/>.
6 */
7
9
10#ifndef SAVELOAD_OLDPOOL_H
11#define SAVELOAD_OLDPOOL_H
12
17template <typename T>
19public:
21 struct Item {
22 uint32_t index = 0;
23 uint32_t next = 0;
24 T value{};
25 };
26
30 void Clear()
31 {
32 this->items.clear();
33 this->items.shrink_to_fit();
34 }
35
41 Item *Get(size_t ref_index)
42 {
43 if (ref_index == 0) return nullptr;
44 assert(ref_index <= this->items.size());
45 return &this->items[ref_index - 1];
46 }
47
53 Item &Allocate(size_t pool_index)
54 {
55 assert(pool_index < UINT32_MAX);
56 if (pool_index >= this->items.size()) this->items.resize(pool_index + 1);
57 return this->items[pool_index];
58 }
59
65 template <typename Taction>
66 void TransformItems(size_t ref_index, Taction action)
67 {
68 for (Item *item = this->Get(ref_index); item != nullptr; item = this->Get(item->next)) {
69 action(item->value);
70 }
71 }
72
78 std::vector<T> TransformToVector(size_t ref_index)
79 {
80 std::vector<T> list;
81 TransformItems(ref_index, [&list](const auto &item) { list.push_back(std::move(item)); });
82 return list;
83 }
84
85 std::vector<Item> items{};
86};
87
88#endif /* SAVELOAD_OLDPOOL_H */
Helper class to handle conversion of linked-list style pools to plain vectors.
Item & Allocate(size_t pool_index)
Allocate an old item with the given pool index.
std::vector< T > TransformToVector(size_t ref_index)
Convert an old linked-list of items into a plain vector of items.
void Clear()
Clear all items from this old pool.
std::vector< Item > items
void TransformItems(size_t ref_index, Taction action)
Traverse an old linked-list of items and perform an action on each one in turn.
Item * Get(size_t ref_index)
Get a pointer to an old item with the given reference index.
#define T
Climate temperate.
Definition engines.h:91
Container for each item with linked-list indexes.
uint32_t index
This item's index (1-based).
T value
The item's value.
uint32_t next
The next item's index (1-based).