Codefix: [NewGRF] Don't read an extended byte into uint8_t. (#13302)
[openttd-github.git] / src / strings_internal.h
blobb710be23e5423c48d48e86fc5f4e58d318a00da8
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 */
8 /** @file strings_interal.h Types and functions related to the internal workings of formatting OpenTTD's strings. */
10 #ifndef STRINGS_INTERNAL_H
11 #define STRINGS_INTERNAL_H
13 #include "strings_func.h"
14 #include "string_func.h"
16 /** The data required to format and validate a single parameter of a string. */
17 struct StringParameter {
18 StringParameterData data; ///< The data of the parameter.
19 char32_t type; ///< The #StringControlCode to interpret this data with when it's the first parameter, otherwise '\0'.
22 class StringParameters {
23 protected:
24 StringParameters *parent = nullptr; ///< If not nullptr, this instance references data from this parent instance.
25 std::span<StringParameter> parameters = {}; ///< Array with the actual parameters.
27 size_t offset = 0; ///< Current offset in the parameters span.
28 char32_t next_type = 0; ///< The type of the next data that is retrieved.
30 StringParameters(std::span<StringParameter> parameters = {}) :
31 parameters(parameters)
34 const StringParameter &GetNextParameterReference();
36 public:
37 /**
38 * Create a new StringParameters instance that can reference part of the data of
39 * the given parent instance.
41 StringParameters(StringParameters &parent, size_t size) :
42 parent(&parent),
43 parameters(parent.parameters.subspan(parent.offset, size))
46 void PrepareForNextRun();
47 void SetTypeOfNextParameter(char32_t type) { this->next_type = type; }
49 /**
50 * Get the current offset, so it can be backed up for certain processing
51 * steps, or be used to offset the argument index within sub strings.
52 * @return The current offset.
54 size_t GetOffset() { return this->offset; }
56 /**
57 * Set the offset within the string from where to return the next result of
58 * \c GetInt64 or \c GetInt32.
59 * @param offset The offset.
61 void SetOffset(size_t offset)
64 * The offset must be fewer than the number of parameters when it is
65 * being set. Unless restoring a backup, then the original value is
66 * correct as well as long as the offset was not changed. In other
67 * words, when the offset was already at the end of the parameters and
68 * the string did not consume any parameters.
70 assert(offset < this->parameters.size() || this->offset == offset);
71 this->offset = offset;
74 /**
75 * Advance the offset within the string from where to return the next result of
76 * \c GetInt64 or \c GetInt32.
77 * @param advance The amount to advance the offset by.
79 void AdvanceOffset(size_t advance)
81 this->offset += advance;
82 assert(this->offset <= this->parameters.size());
85 /**
86 * Get the next parameter from our parameters.
87 * This updates the offset, so the next time this is called the next parameter
88 * will be read.
89 * @return The next parameter's value.
91 template <typename T>
92 T GetNextParameter()
94 struct visitor {
95 uint64_t operator()(const uint64_t &arg) { return arg; }
96 uint64_t operator()(const std::string &) { throw std::out_of_range("Attempt to read string parameter as integer"); }
99 const auto &param = GetNextParameterReference();
100 return static_cast<T>(std::visit(visitor{}, param.data));
104 * Get the next string parameter from our parameters.
105 * This updates the offset, so the next time this is called the next parameter
106 * will be read.
107 * @return The next parameter's value.
109 const char *GetNextParameterString()
111 struct visitor {
112 const char *operator()(const uint64_t &) { throw std::out_of_range("Attempt to read integer parameter as string"); }
113 const char *operator()(const std::string &arg) { return arg.c_str(); }
116 const auto &param = GetNextParameterReference();
117 return std::visit(visitor{}, param.data);
121 * Get a new instance of StringParameters that is a "range" into the
122 * remaining existing parameters. Upon destruction the offset in the parent
123 * is not updated. However, calls to SetDParam do update the parameters.
125 * The returned StringParameters must not outlive this StringParameters.
126 * @return A "range" of the string parameters.
128 StringParameters GetRemainingParameters() { return GetRemainingParameters(this->offset); }
131 * Get a new instance of StringParameters that is a "range" into the
132 * remaining existing parameters from the given offset. Upon destruction the
133 * offset in the parent is not updated. However, calls to SetDParam do
134 * update the parameters.
136 * The returned StringParameters must not outlive this StringParameters.
137 * @param offset The offset to get the remaining parameters for.
138 * @return A "range" of the string parameters.
140 StringParameters GetRemainingParameters(size_t offset)
142 return StringParameters(this->parameters.subspan(offset, this->parameters.size() - offset));
145 /** Return the amount of elements which can still be read. */
146 size_t GetDataLeft() const
148 return this->parameters.size() - this->offset;
151 /** Get the type of a specific element. */
152 char32_t GetTypeAtOffset(size_t offset) const
154 assert(offset < this->parameters.size());
155 return this->parameters[offset].type;
158 void SetParam(size_t n, const StringParameterData &v)
160 assert(n < this->parameters.size());
161 this->parameters[n].data = v;
164 void SetParam(size_t n, uint64_t v)
166 assert(n < this->parameters.size());
167 this->parameters[n].data = v;
170 template <typename T, std::enable_if_t<std::is_base_of<StrongTypedefBase, T>::value, int> = 0>
171 void SetParam(size_t n, T v)
173 SetParam(n, v.base());
176 void SetParam(size_t n, const char *str)
178 assert(n < this->parameters.size());
179 this->parameters[n].data = str;
182 void SetParam(size_t n, const std::string &str) { this->SetParam(n, str.c_str()); }
184 void SetParam(size_t n, std::string &&str)
186 assert(n < this->parameters.size());
187 this->parameters[n].data = std::move(str);
190 const StringParameterData &GetParam(size_t n) const
192 assert(n < this->parameters.size());
193 return this->parameters[n].data;
198 * Extension of StringParameters with its own statically sized buffer for
199 * the parameters.
201 template <size_t N>
202 class ArrayStringParameters : public StringParameters {
203 std::array<StringParameter, N> params{}; ///< The actual parameters
205 public:
206 ArrayStringParameters()
208 this->parameters = std::span(params.data(), params.size());
211 ArrayStringParameters(ArrayStringParameters&& other) noexcept
213 *this = std::move(other);
216 ArrayStringParameters& operator=(ArrayStringParameters &&other) noexcept
218 this->offset = other.offset;
219 this->next_type = other.next_type;
220 this->params = std::move(other.params);
221 this->parameters = std::span(params.data(), params.size());
222 return *this;
225 ArrayStringParameters(const ArrayStringParameters &other) = delete;
226 ArrayStringParameters& operator=(const ArrayStringParameters &other) = delete;
230 * Helper to create the StringParameters with its own buffer with the given
231 * parameter values.
232 * @param args The parameters to set for the to be created StringParameters.
233 * @return The constructed StringParameters.
235 template <typename... Args>
236 static auto MakeParameters(const Args&... args)
238 ArrayStringParameters<sizeof...(args)> parameters;
239 size_t index = 0;
240 (parameters.SetParam(index++, std::forward<const Args&>(args)), ...);
241 return parameters;
245 * Equivalent to the std::back_insert_iterator in function, with some
246 * convenience helpers for string concatenation.
248 class StringBuilder {
249 std::string *string;
251 public:
252 /* Required type for this to be an output_iterator; mimics std::back_insert_iterator. */
253 using value_type = void;
254 using difference_type = void;
255 using iterator_category = std::output_iterator_tag;
256 using pointer = void;
257 using reference = void;
260 * Create the builder of an external buffer.
261 * @param string The string to write to.
263 StringBuilder(std::string &string) : string(&string) {}
265 /* Required operators for this to be an output_iterator; mimics std::back_insert_iterator, which has no-ops. */
266 StringBuilder &operator++() { return *this; }
267 StringBuilder operator++(int) { return *this; }
268 StringBuilder &operator*() { return *this; }
271 * Operator to add a character to the end of the buffer. Like the back
272 * insert iterators this also increases the position of the end of the
273 * buffer.
274 * @param value The character to add.
275 * @return Reference to this inserter.
277 StringBuilder &operator=(const char value)
279 return this->operator+=(value);
283 * Operator to add a character to the end of the buffer.
284 * @param value The character to add.
285 * @return Reference to this inserter.
287 StringBuilder &operator+=(const char value)
289 this->string->push_back(value);
290 return *this;
294 * Operator to append the given string to the output buffer.
295 * @param str The string to add.
296 * @return Reference to this inserter.
298 StringBuilder &operator+=(std::string_view str)
300 *this->string += str;
301 return *this;
305 * Encode the given Utf8 character into the output buffer.
306 * @param c The character to encode.
308 void Utf8Encode(char32_t c)
310 auto iterator = std::back_inserter(*this->string);
311 ::Utf8Encode(iterator, c);
315 * Remove the given amount of characters from the back of the string.
316 * @param amount The amount of characters to remove.
318 void RemoveElementsFromBack(size_t amount)
320 this->string->erase(this->string->size() - std::min(amount, this->string->size()));
324 * Get the current index in the string.
325 * @return The index.
327 size_t CurrentIndex()
329 return this->string->size();
333 * Get the reference to the character at the given index.
334 * @return The reference to the character.
336 char &operator[](size_t index)
338 return (*this->string)[index];
342 void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index = 0, bool game_script = false);
343 std::string GetStringWithArgs(StringID string, StringParameters &args);
345 /* Do not leak the StringBuilder to everywhere. */
346 void GenerateTownNameString(StringBuilder &builder, size_t lang, uint32_t seed);
347 void GetTownName(StringBuilder &builder, const struct Town *t);
348 void GRFTownNameGenerate(StringBuilder &builder, uint32_t grfid, uint16_t gen, uint32_t seed);
350 char32_t RemapNewGRFStringControlCode(char32_t scc, const char **str, StringParameters &parameters, bool modify_parameters);
352 #endif /* STRINGS_INTERNAL_H */