Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #ifndef CStr_CPP_FIRST
21 : #define CStr_CPP_FIRST
22 :
23 : #include "lib/fnv_hash.h"
24 : #include "lib/utf8.h"
25 : #include "lib/byte_order.h"
26 : #include "network/Serialization.h"
27 :
28 : #include <cctype>
29 : #include <cwctype>
30 : #include <iomanip>
31 : #include <sstream>
32 : #include <type_traits>
33 :
34 : namespace
35 : {
36 : // Use a knowingly false expression, as we can't use
37 : // static_assert(false, ...) directly, because it's an ill-formed program
38 : // with a value (false) which doesn't depend on any input parameter.
39 : // We don't use constexpr bool AlwaysFalse = false, because some compilers
40 : // complain about an unused constant.
41 : template<typename T>
42 : struct AlwaysFalse : std::false_type
43 : {};
44 :
45 : template<typename StrBase>
46 : using tstringstream = std::basic_stringstream<typename StrBase::value_type>;
47 :
48 : template<typename Char>
49 102 : bool istspace(const Char chr)
50 : {
51 : if constexpr (std::is_same_v<Char, char>)
52 102 : return static_cast<bool>(std::isspace(chr));
53 : else
54 0 : return static_cast<bool>(std::iswspace(chr));
55 : }
56 :
57 : template<typename Char>
58 11500 : Char totlower(const Char chr)
59 : {
60 : if constexpr (std::is_same_v<Char, char>)
61 11500 : return std::tolower(chr);
62 : else
63 0 : return std::towlower(chr);
64 : }
65 :
66 : template<typename Char>
67 832 : Char totupper(const Char chr)
68 : {
69 : if constexpr (std::is_same_v<Char, char>)
70 832 : return std::toupper(chr);
71 : else
72 0 : return std::towupper(chr);
73 : }
74 :
75 : template<typename StrBase>
76 2 : std::uint8_t* SerializeImpl(const StrBase& str, std::uint8_t* buffer)
77 : {
78 : using Char = typename StrBase::value_type;
79 2 : ENSURE(buffer);
80 : if constexpr (std::is_same_v<Char, char>)
81 : {
82 : // CStr8 is always serialized to / from ASCII(or whatever 8 - bit codepage stored
83 : // in the CStr).
84 2 : size_t len = str.length();
85 2 : Serialize_int_4(buffer, static_cast<std::uint32_t>(len));
86 : size_t i = 0;
87 12 : for (i = 0; i < len; i++)
88 10 : buffer[i] = str[i];
89 2 : return buffer + len;
90 : }
91 : else if constexpr (std::is_same_v<Char, wchar_t>)
92 : {
93 : // CStrW is always serialized to / from UTF - 16.
94 0 : size_t len = str.length();
95 : size_t i = 0;
96 0 : for (i = 0; i < len; i++)
97 : {
98 0 : const std::uint16_t bigEndian = to_be16(str[i]);
99 0 : *reinterpret_cast<std::uint16_t*>(buffer + i * 2) = bigEndian;
100 : }
101 0 : *reinterpret_cast<std::uint16_t*>(buffer + i * 2) = 0;
102 0 : return buffer + len * 2 + 2;
103 : }
104 : else
105 : static_assert(AlwaysFalse<Char>::value, "Not implemented.");
106 : }
107 :
108 : template<typename StrBase>
109 4 : const std::uint8_t* DeserializeImpl(const std::uint8_t* buffer, const std::uint8_t* bufferend,
110 : StrBase& str)
111 : {
112 : using Char = typename StrBase::value_type;
113 4 : ENSURE(buffer);
114 4 : ENSURE(bufferend);
115 : if constexpr (std::is_same_v<Char, char>)
116 : {
117 : std::uint32_t len;
118 4 : Deserialize_int_4(buffer, len);
119 4 : if (buffer + len > bufferend)
120 : return NULL;
121 4 : str = StrBase(buffer, buffer + len);
122 4 : return buffer + len;
123 : }
124 : else if constexpr (std::is_same_v<Char, wchar_t>)
125 : {
126 0 : const std::uint16_t* strend = reinterpret_cast<const std::uint16_t*>(buffer);
127 0 : while (reinterpret_cast<const std::uint8_t*>(strend) < bufferend && *strend)
128 0 : strend++;
129 0 : if (reinterpret_cast<const std::uint8_t*>(strend) >= bufferend)
130 : return nullptr;
131 :
132 0 : str.resize(strend - reinterpret_cast<const std::uint16_t*>(buffer));
133 0 : const std::uint16_t *ptr = reinterpret_cast<const std::uint16_t*>(buffer);
134 :
135 0 : typename StrBase::iterator it = str.begin();
136 0 : while (ptr < strend)
137 : {
138 0 : const std::uint16_t native = to_be16(*(ptr++)); // we want from_be16, but that's the same
139 0 : *(it++) = (Char)native;
140 : }
141 :
142 0 : return reinterpret_cast<const std::uint8_t*>(strend + 1);
143 : }
144 : else
145 : static_assert(AlwaysFalse<Char>::value, "Not implemented.");
146 : }
147 :
148 : template<typename StrBase>
149 2 : size_t GetSerializedLengthImpl(const StrBase& str)
150 : {
151 : using Char = typename StrBase::value_type;
152 : if constexpr (std::is_same_v<Char, char>)
153 2 : return str.length() + 4;
154 : else if constexpr (std::is_same_v<Char, wchar_t>)
155 0 : return str.length() * 2 + 2;
156 : else
157 : static_assert(AlwaysFalse<Char>::value, "Not implemented.");
158 : }
159 :
160 : } // anonymous namespace
161 :
162 : #define UNIDOUBLER_HEADER "CStr.cpp"
163 : #include "UniDoubler.h"
164 :
165 :
166 : // Only include these function definitions in the first instance of CStr.cpp:
167 :
168 : /**
169 : * Convert CStr to UTF-8
170 : *
171 : * @return CStr8 converted string
172 : **/
173 18302 : CStr8 CStrW::ToUTF8() const
174 : {
175 18302 : Status err;
176 53737 : return utf8_from_wstring(*this, &err);
177 : }
178 :
179 : /**
180 : * Convert UTF-8 to CStr
181 : *
182 : * @return CStrW converted string
183 : **/
184 2136 : CStrW CStr8::FromUTF8() const
185 : {
186 2136 : Status err;
187 6381 : return wstring_from_utf8(*this, &err);
188 : }
189 :
190 : #else
191 :
192 : // The following code is compiled twice, as CStrW then as CStr8:
193 :
194 : #include "CStr.h"
195 :
196 0 : CStr CStr::Repeat(const CStr& str, size_t reps)
197 : {
198 0 : CStr ret;
199 0 : ret.reserve(str.length() * reps);
200 0 : while (reps--) ret += str;
201 0 : return ret;
202 0 : }
203 :
204 : // Conversion to numbers:
205 :
206 168 : int CStr::ToInt() const
207 : {
208 168 : int ret = 0;
209 168 : tstringstream<StrBase> str(*this);
210 168 : str >> ret;
211 168 : return ret;
212 168 : }
213 :
214 4 : unsigned int CStr::ToUInt() const
215 : {
216 4 : unsigned int ret = 0;
217 4 : tstringstream<StrBase> str(*this);
218 4 : str >> ret;
219 4 : return ret;
220 4 : }
221 :
222 5 : long CStr::ToLong() const
223 : {
224 5 : long ret = 0;
225 5 : tstringstream<StrBase> str(*this);
226 5 : str >> ret;
227 5 : return ret;
228 5 : }
229 :
230 4 : unsigned long CStr::ToULong() const
231 : {
232 4 : unsigned long ret = 0;
233 4 : tstringstream<StrBase> str(*this);
234 4 : str >> ret;
235 4 : return ret;
236 4 : }
237 :
238 : /**
239 : * libc++ and libstd++ differ on how they handle string-to-number parsing for floating-points numbers.
240 : * See https://gitea.wildfiregames.com/0ad/0ad/issues/2780#comment:4 for details.
241 : * To prevent this, only consider [0-9.-+], replace the others in-place with a neutral character.
242 : */
243 156 : CStr ParseableAsNumber(CStr cleaned_copy)
244 : {
245 716 : for (CStr::Char& c : cleaned_copy)
246 560 : if (!std::isdigit(c) && c != '.' && c != '-' && c != '+')
247 32 : c = ' ';
248 :
249 156 : return cleaned_copy;
250 : }
251 :
252 151 : float CStr::ToFloat() const
253 : {
254 151 : float ret = 0;
255 302 : tstringstream<StrBase> str(ParseableAsNumber(*this));
256 151 : str >> ret;
257 151 : return ret;
258 151 : }
259 :
260 5 : double CStr::ToDouble() const
261 : {
262 5 : double ret = 0;
263 10 : tstringstream<StrBase> str(ParseableAsNumber(*this));
264 5 : str >> ret;
265 5 : return ret;
266 5 : }
267 :
268 : // Lowercase and uppercase
269 2850 : CStr CStr::LowerCase() const
270 : {
271 2850 : StrBase newStr = *this;
272 14350 : for (size_t i = 0; i < length(); i++)
273 11500 : newStr[i] = (Char)totlower((*this)[i]);
274 :
275 5700 : return newStr;
276 2850 : }
277 :
278 13 : CStr CStr::UpperCase() const
279 : {
280 13 : StrBase newStr = *this;
281 845 : for (size_t i = 0; i < length(); i++)
282 832 : newStr[i] = (Char)totupper((*this)[i]);
283 :
284 26 : return newStr;
285 13 : }
286 :
287 : // Retrieve the substring following the last occurrence of Str
288 : // (or the whole string if it doesn't contain Str)
289 0 : CStr CStr::AfterLast(const CStr& str, size_t startPos) const
290 : {
291 0 : size_t pos = rfind(str, startPos);
292 0 : if (pos == npos)
293 0 : return *this;
294 : else
295 0 : return substr(pos + str.length());
296 : }
297 :
298 : // Retrieve the substring preceding the last occurrence of Str
299 : // (or the whole string if it doesn't contain Str)
300 0 : CStr CStr::BeforeLast(const CStr& str, size_t startPos) const
301 : {
302 0 : size_t pos = rfind(str, startPos);
303 0 : if (pos == npos)
304 0 : return *this;
305 : else
306 0 : return substr(0, pos);
307 : }
308 :
309 : // Retrieve the substring following the first occurrence of Str
310 : // (or the whole string if it doesn't contain Str)
311 0 : CStr CStr::AfterFirst(const CStr& str, size_t startPos) const
312 : {
313 0 : size_t pos = find(str, startPos);
314 0 : if (pos == npos)
315 0 : return *this;
316 : else
317 0 : return substr(pos + str.length());
318 : }
319 :
320 : // Retrieve the substring preceding the first occurrence of Str
321 : // (or the whole string if it doesn't contain Str)
322 0 : CStr CStr::BeforeFirst(const CStr& str, size_t startPos) const
323 : {
324 0 : size_t pos = find(str, startPos);
325 0 : if (pos == npos)
326 0 : return *this;
327 : else
328 0 : return substr(0, pos);
329 : }
330 :
331 : // Remove all occurrences of some character or substring
332 0 : void CStr::Remove(const CStr& str)
333 : {
334 0 : size_t foundAt = 0;
335 0 : while (foundAt != npos)
336 : {
337 0 : foundAt = find(str, 0);
338 :
339 0 : if (foundAt != npos)
340 0 : erase(foundAt, str.length());
341 : }
342 0 : }
343 :
344 0 : std::string CStr::EscapeToPrintableASCII() const
345 : {
346 0 : std::string newStr;
347 0 : for (size_t i = 0; i < length(); i++)
348 : {
349 0 : Char ch = (*this)[i];
350 :
351 0 : if (ch == '"') newStr += "\\\"";
352 0 : else if (ch == '\\') newStr += "\\\\";
353 0 : else if (ch == '\b') newStr += "\\b";
354 0 : else if (ch == '\f') newStr += "\\f";
355 0 : else if (ch == '\n') newStr += "\\n";
356 0 : else if (ch == '\r') newStr += "\\r";
357 0 : else if (ch == '\t') newStr += "\\t";
358 0 : else if (ch >= 32 && ch <= 126)
359 0 : newStr += ch;
360 : else
361 : {
362 0 : std::stringstream ss;
363 0 : ss << "\\u" << std::hex << std::setfill('0') << std::setw(4) << (int)(unsigned char)ch;
364 0 : newStr += ss.str();
365 0 : }
366 : }
367 0 : return newStr;
368 0 : }
369 :
370 : // Returns a trimmed string, removes whitespace from the left/right/both
371 8 : CStr CStr::Trim(PS_TRIM_MODE mode) const
372 : {
373 8 : size_t left = 0, right = 0;
374 :
375 8 : switch (mode)
376 : {
377 : case PS_TRIM_LEFT:
378 : {
379 0 : for (left = 0; left < length(); left++)
380 0 : if (istspace((*this)[left]) == false)
381 : break; // end found, trim 0 to Left-1 inclusive
382 : } break;
383 :
384 0 : case PS_TRIM_RIGHT:
385 0 : {
386 0 : right = length();
387 0 : while (right--)
388 0 : if (istspace((*this)[right]) == false)
389 : break; // end found, trim len-1 to Right+1 inclusive
390 : } break;
391 :
392 : case PS_TRIM_BOTH:
393 : {
394 77 : for (left = 0; left < length(); left++)
395 76 : if (istspace((*this)[left]) == false)
396 : break; // end found, trim 0 to Left-1 inclusive
397 :
398 8 : right = length();
399 27 : while (right--)
400 26 : if (istspace((*this)[right]) == false)
401 : break; // end found, trim len-1 to Right+1 inclusive
402 : } break;
403 :
404 0 : default:
405 0 : debug_warn(L"CStr::Trim: invalid Mode");
406 : }
407 :
408 :
409 21 : return substr(left, right - left + 1);
410 : }
411 :
412 76 : size_t CStr::GetHashCode() const
413 : {
414 76 : return (size_t)fnv_hash(data(), length()*sizeof(value_type));
415 : // janwas 2005-03-18: now use 32-bit version; 64 is slower and
416 : // the result was truncated down to 32 anyway.
417 : }
418 :
419 2 : std::uint8_t* CStr::Serialize(std::uint8_t* buffer) const
420 : {
421 2 : return SerializeImpl(*this, buffer);
422 : }
423 :
424 4 : const std::uint8_t* CStr::Deserialize(const std::uint8_t* buffer, const std::uint8_t* bufferend)
425 : {
426 4 : return DeserializeImpl(buffer, bufferend, *this);
427 : }
428 :
429 2 : size_t CStr::GetSerializedLength() const
430 : {
431 2 : return GetSerializedLengthImpl(*this);
432 : }
433 :
434 : #endif // CStr_CPP_FIRST
|