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 string.cpp Handling of C-type strings (char*). */
12 #include "core/alloc_func.hpp"
13 #include "core/math_func.hpp"
14 #include "error_func.h"
15 #include "string_func.h"
16 #include "string_base.h"
18 #include "table/control_codes.h"
24 # define strncasecmp strnicmp
28 # include "os/windows/win32.h"
32 # include "os/windows/string_uniscribe.h"
36 /* Required by StrNaturalCompare. */
37 # include <unicode/ustring.h>
38 # include "language.h"
39 # include "gfx_func.h"
40 #endif /* WITH_ICU_I18N */
42 #if defined(WITH_COCOA)
43 # include "os/macosx/string_osx.h"
46 #include "safeguards.h"
50 * Copies characters from one buffer to another.
52 * Copies the source string to the destination buffer with respect of the
53 * terminating null-character and the size of the destination buffer.
55 * @note usage: strecpy(dst, src);
57 * @param dst The destination buffer
58 * @param src The buffer containing the string to copy
60 void strecpy(std::span
<char> dst
, std::string_view src
)
62 /* Ensure source string fits with NUL terminator; dst must be at least 1 character longer than src. */
63 if (std::empty(dst
) || std::size(src
) >= std::size(dst
) - 1U) {
64 #if defined(STRGEN) || defined(SETTINGSGEN)
65 FatalError("String too long for destination buffer");
66 #else /* STRGEN || SETTINGSGEN */
67 Debug(misc
, 0, "String too long for destination buffer");
68 src
= src
.substr(0, std::size(dst
) - 1U);
69 #endif /* STRGEN || SETTINGSGEN */
72 auto it
= std::copy(std::begin(src
), std::end(src
), std::begin(dst
));
77 * Format a byte array into a continuous hex string.
78 * @param data Array to format
79 * @return Converted string.
81 std::string
FormatArrayAsHex(std::span
<const uint8_t> data
)
84 str
.reserve(data
.size() * 2 + 1);
87 fmt::format_to(std::back_inserter(str
), "{:02X}", b
);
95 * Copies the valid (UTF-8) characters from \c str up to \c last to the \c dst.
96 * Depending on the \c settings invalid characters can be replaced with a
97 * question mark, as well as determining what characters are deemed invalid.
99 * It is allowed for \c dst to be the same as \c src, in which case the string
100 * is make valid in place.
101 * @param dst The destination to write to.
102 * @param str The string to validate.
103 * @param last The last valid character of str.
104 * @param settings The settings for the string validation.
107 static void StrMakeValid(T
&dst
, const char *str
, const char *last
, StringValidationSettings settings
)
109 /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
111 while (str
<= last
&& *str
!= '\0') {
112 size_t len
= Utf8EncodedCharLen(*str
);
114 /* If the first byte does not look like the first byte of an encoded
115 * character, i.e. encoded length is 0, then this byte is definitely bad
116 * and it should be skipped.
117 * When the first byte looks like the first byte of an encoded character,
118 * then the remaining bytes in the string are checked whether the whole
119 * encoded character can be there. If that is not the case, this byte is
121 * Finally we attempt to decode the encoded character, which does certain
122 * extra validations to see whether the correct number of bytes were used
123 * to encode the character. If that is not the case, the byte is probably
124 * invalid and it is skipped. We could emit a question mark, but then the
125 * logic below cannot just copy bytes, it would need to re-encode the
126 * decoded characters as the length in bytes may have changed.
128 * The goals here is to get as much valid Utf8 encoded characters from the
129 * source string to the destination string.
131 * Note: a multi-byte encoded termination ('\0') will trigger the encoded
132 * char length and the decoded length to differ, so it will be ignored as
133 * invalid character data. If it were to reach the termination, then we
134 * would also reach the "last" byte of the string and a normal '\0'
135 * termination will be placed after it.
137 if (len
== 0 || str
+ len
> last
+ 1 || len
!= Utf8Decode(&c
, str
)) {
138 /* Maybe the next byte is still a valid character? */
143 if ((IsPrintable(c
) && (c
< SCC_SPRITE_START
|| c
> SCC_SPRITE_END
)) || ((settings
& SVS_ALLOW_CONTROL_CODE
) != 0 && c
== SCC_ENCODED
)) {
144 /* Copy the character back. Even if dst is current the same as str
145 * (i.e. no characters have been changed) this is quicker than
146 * moving the pointers ahead by len */
149 } while (--len
!= 0);
150 } else if ((settings
& SVS_ALLOW_NEWLINE
) != 0 && c
== '\n') {
153 if ((settings
& SVS_ALLOW_NEWLINE
) != 0 && c
== '\r' && str
[1] == '\n') {
158 if ((settings
& SVS_REPLACE_TAB_CR_NL_WITH_SPACE
) != 0 && (c
== '\r' || c
== '\n' || c
== '\t')) {
159 /* Replace the tab, carriage return or newline with a space. */
161 } else if ((settings
& SVS_REPLACE_WITH_QUESTION_MARK
) != 0) {
162 /* Replace the undesirable character with a question mark */
168 /* String termination, if needed, is left to the caller of this function. */
172 * Scans the string for invalid characters and replaces then with a
173 * question mark '?' (if not ignored).
174 * @param str The string to validate.
175 * @param last The last valid character of str.
176 * @param settings The settings for the string validation.
178 void StrMakeValidInPlace(char *str
, const char *last
, StringValidationSettings settings
)
181 StrMakeValid(dst
, str
, last
, settings
);
186 * Scans the string for invalid characters and replaces then with a
187 * question mark '?' (if not ignored).
188 * Only use this function when you are sure the string ends with a '\0';
189 * otherwise use StrMakeValidInPlace(str, last, settings) variant.
190 * @param str The string (of which you are sure ends with '\0') to validate.
192 void StrMakeValidInPlace(char *str
, StringValidationSettings settings
)
194 /* We know it is '\0' terminated. */
195 StrMakeValidInPlace(str
, str
+ strlen(str
), settings
);
199 * Copies the valid (UTF-8) characters from \c str to the returned string.
200 * Depending on the \c settings invalid characters can be replaced with a
201 * question mark, as well as determining what characters are deemed invalid.
202 * @param str The string to validate.
203 * @param settings The settings for the string validation.
205 std::string
StrMakeValid(std::string_view str
, StringValidationSettings settings
)
207 if (str
.empty()) return {};
209 auto buf
= str
.data();
210 auto last
= buf
+ str
.size() - 1;
212 std::ostringstream dst
;
213 std::ostreambuf_iterator
<char> dst_iter(dst
);
214 StrMakeValid(dst_iter
, buf
, last
, settings
);
220 * Checks whether the given string is valid, i.e. contains only
221 * valid (printable) characters and is properly terminated.
222 * @note std::span is used instead of std::string_view as we are validating fixed-length string buffers, and
223 * std::string_view's constructor will assume a C-string that ends with a NUL terminator, which is one of the things
225 * @param str Span of chars to validate.
227 bool StrValid(std::span
<const char> str
)
229 /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
230 auto it
= std::begin(str
);
231 auto last
= std::prev(std::end(str
));
233 while (it
<= last
&& *it
!= '\0') {
234 size_t len
= Utf8EncodedCharLen(*it
);
235 /* Encoded length is 0 if the character isn't known.
236 * The length check is needed to prevent Utf8Decode to read
237 * over the terminating '\0' if that happens to be placed
238 * within the encoding of an UTF8 character. */
239 if (len
== 0 || it
+ len
> last
) return false;
242 len
= Utf8Decode(&c
, &*it
);
243 if (!IsPrintable(c
) || (c
>= SCC_SPRITE_START
&& c
<= SCC_SPRITE_END
)) {
254 * Trim the spaces from given string in place, i.e. the string buffer that
255 * is passed will be modified whenever spaces exist in the given string.
256 * When there are spaces at the begin, the whole string is moved forward
257 * and when there are spaces at the back the '\0' termination is moved.
258 * @param str The string to perform the in place trimming on.
260 void StrTrimInPlace(std::string
&str
)
262 str
= StrTrimView(str
);
265 std::string_view
StrTrimView(std::string_view str
)
267 size_t first_pos
= str
.find_first_not_of(' ');
268 if (first_pos
== std::string::npos
) {
269 return std::string_view
{};
271 size_t last_pos
= str
.find_last_not_of(' ');
272 return str
.substr(first_pos
, last_pos
- first_pos
+ 1);
276 * Check whether the given string starts with the given prefix, ignoring case.
277 * @param str The string to look at.
278 * @param prefix The prefix to look for.
279 * @return True iff the begin of the string is the same as the prefix, ignoring case.
281 bool StrStartsWithIgnoreCase(std::string_view str
, const std::string_view prefix
)
283 if (str
.size() < prefix
.size()) return false;
284 return StrEqualsIgnoreCase(str
.substr(0, prefix
.size()), prefix
);
287 /** Case insensitive implementation of the standard character type traits. */
288 struct CaseInsensitiveCharTraits
: public std::char_traits
<char> {
289 static bool eq(char c1
, char c2
) { return toupper(c1
) == toupper(c2
); }
290 static bool ne(char c1
, char c2
) { return toupper(c1
) != toupper(c2
); }
291 static bool lt(char c1
, char c2
) { return toupper(c1
) < toupper(c2
); }
293 static int compare(const char *s1
, const char *s2
, size_t n
)
296 if (toupper(*s1
) < toupper(*s2
)) return -1;
297 if (toupper(*s1
) > toupper(*s2
)) return 1;
303 static const char *find(const char *s
, size_t n
, char a
)
305 for (; n
> 0; --n
, ++s
) {
306 if (toupper(*s
) == toupper(a
)) return s
;
312 /** Case insensitive string view. */
313 typedef std::basic_string_view
<char, CaseInsensitiveCharTraits
> CaseInsensitiveStringView
;
316 * Check whether the given string ends with the given suffix, ignoring case.
317 * @param str The string to look at.
318 * @param suffix The suffix to look for.
319 * @return True iff the end of the string is the same as the suffix, ignoring case.
321 bool StrEndsWithIgnoreCase(std::string_view str
, const std::string_view suffix
)
323 if (str
.size() < suffix
.size()) return false;
324 return StrEqualsIgnoreCase(str
.substr(str
.size() - suffix
.size()), suffix
);
328 * Compares two string( view)s, while ignoring the case of the characters.
329 * @param str1 The first string.
330 * @param str2 The second string.
331 * @return Less than zero if str1 < str2, zero if str1 == str2, greater than
332 * zero if str1 > str2. All ignoring the case of the characters.
334 int StrCompareIgnoreCase(const std::string_view str1
, const std::string_view str2
)
336 CaseInsensitiveStringView ci_str1
{ str1
.data(), str1
.size() };
337 CaseInsensitiveStringView ci_str2
{ str2
.data(), str2
.size() };
338 return ci_str1
.compare(ci_str2
);
342 * Compares two string( view)s for equality, while ignoring the case of the characters.
343 * @param str1 The first string.
344 * @param str2 The second string.
345 * @return True iff both strings are equal, barring the case of the characters.
347 bool StrEqualsIgnoreCase(const std::string_view str1
, const std::string_view str2
)
349 if (str1
.size() != str2
.size()) return false;
350 return StrCompareIgnoreCase(str1
, str2
) == 0;
354 * Get the length of an UTF-8 encoded string in number of characters
355 * and thus not the number of bytes that the encoded string contains.
356 * @param s The string to get the length for.
357 * @return The length of the string in characters.
359 size_t Utf8StringLength(const char *s
)
363 while (Utf8Consume(&t
) != 0) len
++;
368 * Get the length of an UTF-8 encoded string in number of characters
369 * and thus not the number of bytes that the encoded string contains.
370 * @param s The string to get the length for.
371 * @return The length of the string in characters.
373 size_t Utf8StringLength(const std::string
&str
)
375 return Utf8StringLength(str
.c_str());
378 bool strtolower(std::string
&str
, std::string::size_type offs
)
380 bool changed
= false;
381 for (auto ch
= str
.begin() + offs
; ch
!= str
.end(); ++ch
) {
382 auto new_ch
= static_cast<char>(tolower(static_cast<unsigned char>(*ch
)));
383 changed
|= new_ch
!= *ch
;
390 * Only allow certain keys. You can define the filter to be used. This makes
391 * sure no invalid keys can get into an editbox, like BELL.
392 * @param key character to be checked
393 * @param afilter the filter to use
394 * @return true or false depending if the character is printable/valid or not
396 bool IsValidChar(char32_t key
, CharSetFilter afilter
)
399 case CS_ALPHANUMERAL
: return IsPrintable(key
);
400 case CS_NUMERAL
: return (key
>= '0' && key
<= '9');
401 case CS_NUMERAL_SPACE
: return (key
>= '0' && key
<= '9') || key
== ' ';
402 case CS_NUMERAL_SIGNED
: return (key
>= '0' && key
<= '9') || key
== '-';
403 case CS_ALPHA
: return IsPrintable(key
) && !(key
>= '0' && key
<= '9');
404 case CS_HEXADECIMAL
: return (key
>= '0' && key
<= '9') || (key
>= 'a' && key
<= 'f') || (key
>= 'A' && key
<= 'F');
405 default: NOT_REACHED();
410 /* UTF-8 handling routines */
414 * Decode and consume the next UTF-8 encoded character.
415 * @param c Buffer to place decoded character.
416 * @param s Character stream to retrieve character from.
417 * @return Number of characters in the sequence.
419 size_t Utf8Decode(char32_t
*c
, const char *s
)
421 assert(c
!= nullptr);
423 if (!HasBit(s
[0], 7)) {
424 /* Single byte character: 0xxxxxxx */
427 } else if (GB(s
[0], 5, 3) == 6) {
428 if (IsUtf8Part(s
[1])) {
429 /* Double byte character: 110xxxxx 10xxxxxx */
430 *c
= GB(s
[0], 0, 5) << 6 | GB(s
[1], 0, 6);
431 if (*c
>= 0x80) return 2;
433 } else if (GB(s
[0], 4, 4) == 14) {
434 if (IsUtf8Part(s
[1]) && IsUtf8Part(s
[2])) {
435 /* Triple byte character: 1110xxxx 10xxxxxx 10xxxxxx */
436 *c
= GB(s
[0], 0, 4) << 12 | GB(s
[1], 0, 6) << 6 | GB(s
[2], 0, 6);
437 if (*c
>= 0x800) return 3;
439 } else if (GB(s
[0], 3, 5) == 30) {
440 if (IsUtf8Part(s
[1]) && IsUtf8Part(s
[2]) && IsUtf8Part(s
[3])) {
441 /* 4 byte character: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
442 *c
= GB(s
[0], 0, 3) << 18 | GB(s
[1], 0, 6) << 12 | GB(s
[2], 0, 6) << 6 | GB(s
[3], 0, 6);
443 if (*c
>= 0x10000 && *c
<= 0x10FFFF) return 4;
453 * Encode a unicode character and place it in the buffer.
454 * @tparam T Type of the buffer.
455 * @param buf Buffer to place character.
456 * @param c Unicode character to encode.
457 * @return Number of characters in the encoded sequence.
460 inline size_t Utf8Encode(T buf
, char32_t c
)
465 } else if (c
< 0x800) {
466 *buf
++ = 0xC0 + GB(c
, 6, 5);
467 *buf
= 0x80 + GB(c
, 0, 6);
469 } else if (c
< 0x10000) {
470 *buf
++ = 0xE0 + GB(c
, 12, 4);
471 *buf
++ = 0x80 + GB(c
, 6, 6);
472 *buf
= 0x80 + GB(c
, 0, 6);
474 } else if (c
< 0x110000) {
475 *buf
++ = 0xF0 + GB(c
, 18, 3);
476 *buf
++ = 0x80 + GB(c
, 12, 6);
477 *buf
++ = 0x80 + GB(c
, 6, 6);
478 *buf
= 0x80 + GB(c
, 0, 6);
486 size_t Utf8Encode(char *buf
, char32_t c
)
488 return Utf8Encode
<char *>(buf
, c
);
491 size_t Utf8Encode(std::ostreambuf_iterator
<char> &buf
, char32_t c
)
493 return Utf8Encode
<std::ostreambuf_iterator
<char> &>(buf
, c
);
496 size_t Utf8Encode(std::back_insert_iterator
<std::string
> &buf
, char32_t c
)
498 return Utf8Encode
<std::back_insert_iterator
<std::string
> &>(buf
, c
);
502 * Properly terminate an UTF8 string to some maximum length
503 * @param s string to check if it needs additional trimming
504 * @param maxlen the maximum length the buffer can have.
505 * @return the new length in bytes of the string (eg. strlen(new_string))
506 * @note maxlen is the string length _INCLUDING_ the terminating '\0'
508 size_t Utf8TrimString(char *s
, size_t maxlen
)
512 for (const char *ptr
= strchr(s
, '\0'); *s
!= '\0';) {
513 size_t len
= Utf8EncodedCharLen(*s
);
514 /* Silently ignore invalid UTF8 sequences, our only concern trimming */
515 if (len
== 0) len
= 1;
517 /* Take care when a hard cutoff was made for the string and
518 * the last UTF8 sequence is invalid */
519 if (length
+ len
>= maxlen
|| (s
+ len
> ptr
)) break;
528 #ifdef DEFINE_STRCASESTR
529 char *strcasestr(const char *haystack
, const char *needle
)
531 size_t hay_len
= strlen(haystack
);
532 size_t needle_len
= strlen(needle
);
533 while (hay_len
>= needle_len
) {
534 if (strncasecmp(haystack
, needle
, needle_len
) == 0) return const_cast<char *>(haystack
);
542 #endif /* DEFINE_STRCASESTR */
545 * Test if a unicode character is considered garbage to be skipped.
546 * @param c Character to test.
547 * @returns true iff the character should be skipped.
549 static bool IsGarbageCharacter(char32_t c
)
551 if (c
>= '0' && c
<= '9') return false;
552 if (c
>= 'A' && c
<= 'Z') return false;
553 if (c
>= 'a' && c
<= 'z') return false;
554 if (c
>= SCC_CONTROL_START
&& c
<= SCC_CONTROL_END
) return true;
555 if (c
>= 0xC0 && c
<= 0x10FFFF) return false;
561 * Skip some of the 'garbage' in the string that we don't want to use
562 * to sort on. This way the alphabetical sorting will work better as
563 * we would be actually using those characters instead of some other
564 * characters such as spaces and tildes at the begin of the name.
565 * @param str The string to skip the initial garbage of.
566 * @return The string with the garbage skipped.
568 static std::string_view
SkipGarbage(std::string_view str
)
570 auto first
= std::begin(str
);
571 auto last
= std::end(str
);
572 while (first
< last
) {
574 size_t len
= Utf8Decode(&c
, &*first
);
575 if (!IsGarbageCharacter(c
)) break;
578 return {first
, last
};
582 * Compares two strings using case insensitive natural sort.
584 * @param s1 First string to compare.
585 * @param s2 Second string to compare.
586 * @param ignore_garbage_at_front Skip punctuation characters in the front
587 * @return Less than zero if s1 < s2, zero if s1 == s2, greater than zero if s1 > s2.
589 int StrNaturalCompare(std::string_view s1
, std::string_view s2
, bool ignore_garbage_at_front
)
591 if (ignore_garbage_at_front
) {
592 s1
= SkipGarbage(s1
);
593 s2
= SkipGarbage(s2
);
597 if (_current_collator
) {
598 UErrorCode status
= U_ZERO_ERROR
;
599 int result
= _current_collator
->compareUTF8(icu::StringPiece(s1
.data(), s1
.size()), icu::StringPiece(s2
.data(), s2
.size()), status
);
600 if (U_SUCCESS(status
)) return result
;
602 #endif /* WITH_ICU_I18N */
604 #if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
605 int res
= OTTDStringCompare(s1
, s2
);
606 if (res
!= 0) return res
- 2; // Convert to normal C return values.
609 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
610 int res
= MacOSStringCompare(s1
, s2
);
611 if (res
!= 0) return res
- 2; // Convert to normal C return values.
614 /* Do a normal comparison if ICU is missing or if we cannot create a collator. */
615 return StrCompareIgnoreCase(s1
, s2
);
620 #include <unicode/stsearch.h>
623 * Search if a string is contained in another string using the current locale.
625 * @param str String to search in.
626 * @param value String to search for.
627 * @param case_insensitive Search case-insensitive.
628 * @return 1 if value was found, 0 if it was not found, or -1 if not supported by the OS.
630 static int ICUStringContains(const std::string_view str
, const std::string_view value
, bool case_insensitive
)
632 if (_current_collator
) {
633 std::unique_ptr
<icu::RuleBasedCollator
> coll(dynamic_cast<icu::RuleBasedCollator
*>(_current_collator
->clone()));
635 UErrorCode status
= U_ZERO_ERROR
;
636 coll
->setStrength(case_insensitive
? icu::Collator::SECONDARY
: icu::Collator::TERTIARY
);
637 coll
->setAttribute(UCOL_NUMERIC_COLLATION
, UCOL_OFF
, status
);
639 auto u_str
= icu::UnicodeString::fromUTF8(icu::StringPiece(str
.data(), str
.size()));
640 auto u_value
= icu::UnicodeString::fromUTF8(icu::StringPiece(value
.data(), value
.size()));
641 icu::StringSearch
u_searcher(u_value
, u_str
, coll
.get(), nullptr, status
);
642 if (U_SUCCESS(status
)) {
643 auto pos
= u_searcher
.first(status
);
644 if (U_SUCCESS(status
)) return pos
!= USEARCH_DONE
? 1 : 0;
651 #endif /* WITH_ICU_I18N */
654 * Checks if a string is contained in another string with a locale-aware comparison that is case sensitive.
656 * @param str The string to search in.
657 * @param value The string to search for.
658 * @return True if a match was found.
660 [[nodiscard
]] bool StrNaturalContains(const std::string_view str
, const std::string_view value
)
663 int res_u
= ICUStringContains(str
, value
, false);
664 if (res_u
>= 0) return res_u
> 0;
665 #endif /* WITH_ICU_I18N */
667 #if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
668 int res
= Win32StringContains(str
, value
, false);
669 if (res
>= 0) return res
> 0;
672 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
673 int res
= MacOSStringContains(str
, value
, false);
674 if (res
>= 0) return res
> 0;
677 return str
.find(value
) != std::string_view::npos
;
681 * Checks if a string is contained in another string with a locale-aware comparison that is case insensitive.
683 * @param str The string to search in.
684 * @param value The string to search for.
685 * @return True if a match was found.
687 [[nodiscard
]] bool StrNaturalContainsIgnoreCase(const std::string_view str
, const std::string_view value
)
690 int res_u
= ICUStringContains(str
, value
, true);
691 if (res_u
>= 0) return res_u
> 0;
692 #endif /* WITH_ICU_I18N */
694 #if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
695 int res
= Win32StringContains(str
, value
, true);
696 if (res
>= 0) return res
> 0;
699 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
700 int res
= MacOSStringContains(str
, value
, true);
701 if (res
>= 0) return res
> 0;
704 CaseInsensitiveStringView ci_str
{ str
.data(), str
.size() };
705 CaseInsensitiveStringView ci_value
{ value
.data(), value
.size() };
706 return ci_str
.find(ci_value
) != CaseInsensitiveStringView::npos
;
710 * Convert a single hex-nibble to a byte.
712 * @param c The hex-nibble to convert.
713 * @return The byte the hex-nibble represents, or -1 if it is not a valid hex-nibble.
715 static int ConvertHexNibbleToByte(char c
)
717 if (c
>= '0' && c
<= '9') return c
- '0';
718 if (c
>= 'A' && c
<= 'F') return c
+ 10 - 'A';
719 if (c
>= 'a' && c
<= 'f') return c
+ 10 - 'a';
724 * Convert a hex-string to a byte-array, while validating it was actually hex.
726 * @param hex The hex-string to convert.
727 * @param bytes The byte-array to write the result to.
729 * @note The length of the hex-string has to be exactly twice that of the length
730 * of the byte-array, otherwise conversion will fail.
732 * @return True iff the hex-string was valid and the conversion succeeded.
734 bool ConvertHexToBytes(std::string_view hex
, std::span
<uint8_t> bytes
)
736 if (bytes
.size() != hex
.size() / 2) {
740 /* Hex-string lengths are always divisible by 2. */
741 if (hex
.size() % 2 != 0) {
745 for (size_t i
= 0; i
< hex
.size() / 2; i
++) {
746 auto hi
= ConvertHexNibbleToByte(hex
[i
* 2]);
747 auto lo
= ConvertHexNibbleToByte(hex
[i
* 2 + 1]);
749 if (hi
< 0 || lo
< 0) {
753 bytes
[i
] = (hi
<< 4) | lo
;
759 #ifdef WITH_UNISCRIBE
761 /* static */ std::unique_ptr
<StringIterator
> StringIterator::Create()
763 return std::make_unique
<UniscribeStringIterator
>();
766 #elif defined(WITH_ICU_I18N)
768 #include <unicode/utext.h>
769 #include <unicode/brkiter.h>
771 /** String iterator using ICU as a backend. */
772 class IcuStringIterator
: public StringIterator
774 icu::BreakIterator
*char_itr
; ///< ICU iterator for characters.
775 icu::BreakIterator
*word_itr
; ///< ICU iterator for words.
777 std::vector
<UChar
> utf16_str
; ///< UTF-16 copy of the string.
778 std::vector
<size_t> utf16_to_utf8
; ///< Mapping from UTF-16 code point position to index in the UTF-8 source string.
781 IcuStringIterator() : char_itr(nullptr), word_itr(nullptr)
783 UErrorCode status
= U_ZERO_ERROR
;
784 this->char_itr
= icu::BreakIterator::createCharacterInstance(icu::Locale(_current_language
!= nullptr ? _current_language
->isocode
: "en"), status
);
785 this->word_itr
= icu::BreakIterator::createWordInstance(icu::Locale(_current_language
!= nullptr ? _current_language
->isocode
: "en"), status
);
787 this->utf16_str
.push_back('\0');
788 this->utf16_to_utf8
.push_back(0);
791 ~IcuStringIterator() override
793 delete this->char_itr
;
794 delete this->word_itr
;
797 void SetString(const char *s
) override
799 const char *string_base
= s
;
801 /* Unfortunately current ICU versions only provide rudimentary support
802 * for word break iterators (especially for CJK languages) in combination
803 * with UTF-8 input. As a work around we have to convert the input to
804 * UTF-16 and create a mapping back to UTF-8 character indices. */
805 this->utf16_str
.clear();
806 this->utf16_to_utf8
.clear();
809 size_t idx
= s
- string_base
;
811 char32_t c
= Utf8Consume(&s
);
813 this->utf16_str
.push_back((UChar
)c
);
815 /* Make a surrogate pair. */
816 this->utf16_str
.push_back((UChar
)(0xD800 + ((c
- 0x10000) >> 10)));
817 this->utf16_str
.push_back((UChar
)(0xDC00 + ((c
- 0x10000) & 0x3FF)));
818 this->utf16_to_utf8
.push_back(idx
);
820 this->utf16_to_utf8
.push_back(idx
);
822 this->utf16_str
.push_back('\0');
823 this->utf16_to_utf8
.push_back(s
- string_base
);
825 UText text
= UTEXT_INITIALIZER
;
826 UErrorCode status
= U_ZERO_ERROR
;
827 utext_openUChars(&text
, this->utf16_str
.data(), this->utf16_str
.size() - 1, &status
);
828 this->char_itr
->setText(&text
, status
);
829 this->word_itr
->setText(&text
, status
);
830 this->char_itr
->first();
831 this->word_itr
->first();
834 size_t SetCurPosition(size_t pos
) override
836 /* Convert incoming position to an UTF-16 string index. */
838 for (uint i
= 0; i
< this->utf16_to_utf8
.size(); i
++) {
839 if (this->utf16_to_utf8
[i
] == pos
) {
845 /* isBoundary has the documented side-effect of setting the current
846 * position to the first valid boundary equal to or greater than
847 * the passed value. */
848 this->char_itr
->isBoundary(utf16_pos
);
849 return this->utf16_to_utf8
[this->char_itr
->current()];
852 size_t Next(IterType what
) override
857 pos
= this->char_itr
->next();
861 pos
= this->word_itr
->following(this->char_itr
->current());
862 /* The ICU word iterator considers both the start and the end of a word a valid
863 * break point, but we only want word starts. Move to the next location in
864 * case the new position points to whitespace. */
865 while (pos
!= icu::BreakIterator::DONE
&&
866 IsWhitespace(Utf16DecodeChar((const uint16_t *)&this->utf16_str
[pos
]))) {
867 int32_t new_pos
= this->word_itr
->next();
868 /* Don't set it to DONE if it was valid before. Otherwise we'll return END
869 * even though the iterator wasn't at the end of the string before. */
870 if (new_pos
== icu::BreakIterator::DONE
) break;
874 this->char_itr
->isBoundary(pos
);
881 return pos
== icu::BreakIterator::DONE
? END
: this->utf16_to_utf8
[pos
];
884 size_t Prev(IterType what
) override
889 pos
= this->char_itr
->previous();
893 pos
= this->word_itr
->preceding(this->char_itr
->current());
894 /* The ICU word iterator considers both the start and the end of a word a valid
895 * break point, but we only want word starts. Move to the previous location in
896 * case the new position points to whitespace. */
897 while (pos
!= icu::BreakIterator::DONE
&&
898 IsWhitespace(Utf16DecodeChar((const uint16_t *)&this->utf16_str
[pos
]))) {
899 int32_t new_pos
= this->word_itr
->previous();
900 /* Don't set it to DONE if it was valid before. Otherwise we'll return END
901 * even though the iterator wasn't at the start of the string before. */
902 if (new_pos
== icu::BreakIterator::DONE
) break;
906 this->char_itr
->isBoundary(pos
);
913 return pos
== icu::BreakIterator::DONE
? END
: this->utf16_to_utf8
[pos
];
917 /* static */ std::unique_ptr
<StringIterator
> StringIterator::Create()
919 return std::make_unique
<IcuStringIterator
>();
924 /** Fallback simple string iterator. */
925 class DefaultStringIterator
: public StringIterator
927 const char *string
; ///< Current string.
928 size_t len
; ///< String length.
929 size_t cur_pos
; ///< Current iteration position.
932 DefaultStringIterator() : string(nullptr), len(0), cur_pos(0)
936 void SetString(const char *s
) override
939 this->len
= strlen(s
);
943 size_t SetCurPosition(size_t pos
) override
945 assert(this->string
!= nullptr && pos
<= this->len
);
946 /* Sanitize in case we get a position inside an UTF-8 sequence. */
947 while (pos
> 0 && IsUtf8Part(this->string
[pos
])) pos
--;
948 return this->cur_pos
= pos
;
951 size_t Next(IterType what
) override
953 assert(this->string
!= nullptr);
955 /* Already at the end? */
956 if (this->cur_pos
>= this->len
) return END
;
959 case ITER_CHARACTER
: {
961 this->cur_pos
+= Utf8Decode(&c
, this->string
+ this->cur_pos
);
962 return this->cur_pos
;
967 /* Consume current word. */
968 size_t offs
= Utf8Decode(&c
, this->string
+ this->cur_pos
);
969 while (this->cur_pos
< this->len
&& !IsWhitespace(c
)) {
970 this->cur_pos
+= offs
;
971 offs
= Utf8Decode(&c
, this->string
+ this->cur_pos
);
973 /* Consume whitespace to the next word. */
974 while (this->cur_pos
< this->len
&& IsWhitespace(c
)) {
975 this->cur_pos
+= offs
;
976 offs
= Utf8Decode(&c
, this->string
+ this->cur_pos
);
979 return this->cur_pos
;
989 size_t Prev(IterType what
) override
991 assert(this->string
!= nullptr);
993 /* Already at the beginning? */
994 if (this->cur_pos
== 0) return END
;
998 return this->cur_pos
= Utf8PrevChar(this->string
+ this->cur_pos
) - this->string
;
1001 const char *s
= this->string
+ this->cur_pos
;
1003 /* Consume preceding whitespace. */
1005 s
= Utf8PrevChar(s
);
1007 } while (s
> this->string
&& IsWhitespace(c
));
1008 /* Consume preceding word. */
1009 while (s
> this->string
&& !IsWhitespace(c
)) {
1010 s
= Utf8PrevChar(s
);
1013 /* Move caret back to the beginning of the word. */
1014 if (IsWhitespace(c
)) Utf8Consume(&s
);
1016 return this->cur_pos
= s
- this->string
;
1027 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
1028 /* static */ std::unique_ptr
<StringIterator
> StringIterator::Create()
1030 std::unique_ptr
<StringIterator
> i
= OSXStringIterator::Create();
1031 if (i
!= nullptr) return i
;
1033 return std::make_unique
<DefaultStringIterator
>();
1036 /* static */ std::unique_ptr
<StringIterator
> StringIterator::Create()
1038 return std::make_unique
<DefaultStringIterator
>();
1040 #endif /* defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN) */