Fix #10117: Decrement object burst limit after build check
[openttd-github.git] / src / string.cpp
blobaeac4fe84f736e35e66f5adec3b074b2a65a9cd7
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 string.cpp Handling of C-type strings (char*). */
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "core/alloc_func.hpp"
13 #include "core/math_func.hpp"
14 #include "string_func.h"
15 #include "string_base.h"
17 #include "table/control_codes.h"
19 #include <stdarg.h>
20 #include <ctype.h> /* required for tolower() */
21 #include <sstream>
22 #include <iomanip>
24 #ifdef _MSC_VER
25 #include <errno.h> // required by vsnprintf implementation for MSVC
26 #endif
28 #ifdef _WIN32
29 #include "os/windows/win32.h"
30 #endif
32 #ifdef WITH_UNISCRIBE
33 #include "os/windows/string_uniscribe.h"
34 #endif
36 #ifdef WITH_ICU_I18N
37 /* Required by strnatcmp. */
38 #include <unicode/ustring.h>
39 #include "language.h"
40 #include "gfx_func.h"
41 #endif /* WITH_ICU_I18N */
43 #if defined(WITH_COCOA)
44 #include "os/macosx/string_osx.h"
45 #endif
47 /* The function vsnprintf is used internally to perform the required formatting
48 * tasks. As such this one must be allowed, and makes sure it's terminated. */
49 #include "safeguards.h"
50 #undef vsnprintf
52 /**
53 * Safer implementation of vsnprintf; same as vsnprintf except:
54 * - last instead of size, i.e. replace sizeof with lastof.
55 * - return gives the amount of characters added, not what it would add.
56 * @param str buffer to write to up to last
57 * @param last last character we may write to
58 * @param format the formatting (see snprintf)
59 * @param ap the list of arguments for the format
60 * @return the number of added characters
62 int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
64 ptrdiff_t diff = last - str;
65 if (diff < 0) return 0;
66 return std::min(static_cast<int>(diff), vsnprintf(str, diff + 1, format, ap));
69 /**
70 * Appends characters from one string to another.
72 * Appends the source string to the destination string with respect of the
73 * terminating null-character and and the last pointer to the last element
74 * in the destination buffer. If the last pointer is set to nullptr no
75 * boundary check is performed.
77 * @note usage: strecat(dst, src, lastof(dst));
78 * @note lastof() applies only to fixed size arrays
80 * @param dst The buffer containing the target string
81 * @param src The buffer containing the string to append
82 * @param last The pointer to the last element of the destination buffer
83 * @return The pointer to the terminating null-character in the destination buffer
85 char *strecat(char *dst, const char *src, const char *last)
87 assert(dst <= last);
88 while (*dst != '\0') {
89 if (dst == last) return dst;
90 dst++;
93 return strecpy(dst, src, last);
97 /**
98 * Copies characters from one buffer to another.
100 * Copies the source string to the destination buffer with respect of the
101 * terminating null-character and the last pointer to the last element in
102 * the destination buffer. If the last pointer is set to nullptr no boundary
103 * check is performed.
105 * @note usage: strecpy(dst, src, lastof(dst));
106 * @note lastof() applies only to fixed size arrays
108 * @param dst The destination buffer
109 * @param src The buffer containing the string to copy
110 * @param last The pointer to the last element of the destination buffer
111 * @return The pointer to the terminating null-character in the destination buffer
113 char *strecpy(char *dst, const char *src, const char *last)
115 assert(dst <= last);
116 while (dst != last && *src != '\0') {
117 *dst++ = *src++;
119 *dst = '\0';
121 if (dst == last && *src != '\0') {
122 #if defined(STRGEN) || defined(SETTINGSGEN)
123 error("String too long for destination buffer");
124 #else /* STRGEN || SETTINGSGEN */
125 Debug(misc, 0, "String too long for destination buffer");
126 #endif /* STRGEN || SETTINGSGEN */
128 return dst;
132 * Create a duplicate of the given string.
133 * @param s The string to duplicate.
134 * @param last The last character that is safe to duplicate. If nullptr, the whole string is duplicated.
135 * @note The maximum length of the resulting string might therefore be last - s + 1.
136 * @return The duplicate of the string.
138 char *stredup(const char *s, const char *last)
140 size_t len = last == nullptr ? strlen(s) : ttd_strnlen(s, last - s + 1);
141 char *tmp = CallocT<char>(len + 1);
142 memcpy(tmp, s, len);
143 return tmp;
147 * Format, "printf", into a newly allocated string.
148 * @param str The formatting string.
149 * @return The formatted string. You must free this!
151 char *CDECL str_fmt(const char *str, ...)
153 char buf[4096];
154 va_list va;
156 va_start(va, str);
157 int len = vseprintf(buf, lastof(buf), str, va);
158 va_end(va);
159 char *p = MallocT<char>(len + 1);
160 memcpy(p, buf, len + 1);
161 return p;
165 * Format a byte array into a continuous hex string.
166 * @param data Array to format
167 * @return Converted string.
169 std::string FormatArrayAsHex(span<const byte> data)
171 std::ostringstream ss;
172 ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex;
174 for (auto b : data) {
175 ss << b;
178 return ss.str();
182 * Scan the string for old values of SCC_ENCODED and fix it to
183 * it's new, static value.
184 * @param str the string to scan
185 * @param last the last valid character of str
187 void str_fix_scc_encoded(char *str, const char *last)
189 while (str <= last && *str != '\0') {
190 size_t len = Utf8EncodedCharLen(*str);
191 if ((len == 0 && str + 4 > last) || str + len > last) break;
193 WChar c;
194 Utf8Decode(&c, str);
195 if (c == '\0') break;
197 if (c == 0xE028 || c == 0xE02A) {
198 c = SCC_ENCODED;
200 str += Utf8Encode(str, c);
202 *str = '\0';
206 template <class T>
207 static void StrMakeValidInPlace(T &dst, const char *str, const char *last, StringValidationSettings settings)
209 /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
211 while (str <= last && *str != '\0') {
212 size_t len = Utf8EncodedCharLen(*str);
213 WChar c;
214 /* If the first byte does not look like the first byte of an encoded
215 * character, i.e. encoded length is 0, then this byte is definitely bad
216 * and it should be skipped.
217 * When the first byte looks like the first byte of an encoded character,
218 * then the remaining bytes in the string are checked whether the whole
219 * encoded character can be there. If that is not the case, this byte is
220 * skipped.
221 * Finally we attempt to decode the encoded character, which does certain
222 * extra validations to see whether the correct number of bytes were used
223 * to encode the character. If that is not the case, the byte is probably
224 * invalid and it is skipped. We could emit a question mark, but then the
225 * logic below cannot just copy bytes, it would need to re-encode the
226 * decoded characters as the length in bytes may have changed.
228 * The goals here is to get as much valid Utf8 encoded characters from the
229 * source string to the destination string.
231 * Note: a multi-byte encoded termination ('\0') will trigger the encoded
232 * char length and the decoded length to differ, so it will be ignored as
233 * invalid character data. If it were to reach the termination, then we
234 * would also reach the "last" byte of the string and a normal '\0'
235 * termination will be placed after it.
237 if (len == 0 || str + len > last || len != Utf8Decode(&c, str)) {
238 /* Maybe the next byte is still a valid character? */
239 str++;
240 continue;
243 if ((IsPrintable(c) && (c < SCC_SPRITE_START || c > SCC_SPRITE_END)) || ((settings & SVS_ALLOW_CONTROL_CODE) != 0 && c == SCC_ENCODED)) {
244 /* Copy the character back. Even if dst is current the same as str
245 * (i.e. no characters have been changed) this is quicker than
246 * moving the pointers ahead by len */
247 do {
248 *dst++ = *str++;
249 } while (--len != 0);
250 } else if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\n') {
251 *dst++ = *str++;
252 } else {
253 if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\r' && str[1] == '\n') {
254 str += len;
255 continue;
257 /* Replace the undesirable character with a question mark */
258 str += len;
259 if ((settings & SVS_REPLACE_WITH_QUESTION_MARK) != 0) *dst++ = '?';
263 /* String termination, if needed, is left to the caller of this function. */
267 * Scans the string for invalid characters and replaces then with a
268 * question mark '?' (if not ignored).
269 * @param str The string to validate.
270 * @param last The last valid character of str.
271 * @param settings The settings for the string validation.
273 void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
275 char *dst = str;
276 StrMakeValidInPlace(dst, str, last, settings);
277 *dst = '\0';
281 * Scans the string for invalid characters and replaces then with a
282 * question mark '?' (if not ignored).
283 * Only use this function when you are sure the string ends with a '\0';
284 * otherwise use StrMakeValidInPlace(str, last, settings) variant.
285 * @param str The string (of which you are sure ends with '\0') to validate.
287 void StrMakeValidInPlace(char *str, StringValidationSettings settings)
289 /* We know it is '\0' terminated. */
290 StrMakeValidInPlace(str, str + strlen(str), settings);
294 * Scans the string for invalid characters and replaces then with a
295 * question mark '?' (if not ignored).
296 * @param str The string to validate.
297 * @param settings The settings for the string validation.
299 std::string StrMakeValid(const std::string &str, StringValidationSettings settings)
301 auto buf = str.data();
302 auto last = buf + str.size();
304 std::ostringstream dst;
305 std::ostreambuf_iterator<char> dst_iter(dst);
306 StrMakeValidInPlace(dst_iter, buf, last, settings);
308 return dst.str();
312 * Checks whether the given string is valid, i.e. contains only
313 * valid (printable) characters and is properly terminated.
314 * @param str The string to validate.
315 * @param last The last character of the string, i.e. the string
316 * must be terminated here or earlier.
318 bool StrValid(const char *str, const char *last)
320 /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
322 while (str <= last && *str != '\0') {
323 size_t len = Utf8EncodedCharLen(*str);
324 /* Encoded length is 0 if the character isn't known.
325 * The length check is needed to prevent Utf8Decode to read
326 * over the terminating '\0' if that happens to be placed
327 * within the encoding of an UTF8 character. */
328 if (len == 0 || str + len > last) return false;
330 WChar c;
331 len = Utf8Decode(&c, str);
332 if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
333 return false;
336 str += len;
339 return *str == '\0';
343 * Trim the spaces from the begin of given string in place, i.e. the string buffer
344 * that is passed will be modified whenever spaces exist in the given string.
345 * When there are spaces at the begin, the whole string is moved forward.
346 * @param str The string to perform the in place left trimming on.
348 static void StrLeftTrimInPlace(std::string &str)
350 size_t pos = str.find_first_not_of(' ');
351 str.erase(0, pos);
355 * Trim the spaces from the end of given string in place, i.e. the string buffer
356 * that is passed will be modified whenever spaces exist in the given string.
357 * When there are spaces at the end, the '\0' will be moved forward.
358 * @param str The string to perform the in place left trimming on.
360 static void StrRightTrimInPlace(std::string &str)
362 size_t pos = str.find_last_not_of(' ');
363 if (pos != std::string::npos) str.erase(pos + 1);
367 * Trim the spaces from given string in place, i.e. the string buffer that
368 * is passed will be modified whenever spaces exist in the given string.
369 * When there are spaces at the begin, the whole string is moved forward
370 * and when there are spaces at the back the '\0' termination is moved.
371 * @param str The string to perform the in place trimming on.
373 void StrTrimInPlace(std::string &str)
375 StrLeftTrimInPlace(str);
376 StrRightTrimInPlace(str);
380 * Check whether the given string starts with the given prefix.
381 * @param str The string to look at.
382 * @param prefix The prefix to look for.
383 * @return True iff the begin of the string is the same as the prefix.
385 bool StrStartsWith(const std::string_view str, const std::string_view prefix)
387 size_t prefix_len = prefix.size();
388 if (str.size() < prefix_len) return false;
389 return str.compare(0, prefix_len, prefix, 0, prefix_len) == 0;
393 * Check whether the given string ends with the given suffix.
394 * @param str The string to look at.
395 * @param suffix The suffix to look for.
396 * @return True iff the end of the string is the same as the suffix.
398 bool StrEndsWith(const std::string_view str, const std::string_view suffix)
400 size_t suffix_len = suffix.size();
401 if (str.size() < suffix_len) return false;
402 return str.compare(str.size() - suffix_len, suffix_len, suffix, 0, suffix_len) == 0;
406 /** Scans the string for colour codes and strips them */
407 void str_strip_colours(char *str)
409 char *dst = str;
410 WChar c;
411 size_t len;
413 for (len = Utf8Decode(&c, str); c != '\0'; len = Utf8Decode(&c, str)) {
414 if (c < SCC_BLUE || c > SCC_BLACK) {
415 /* Copy the character back. Even if dst is current the same as str
416 * (i.e. no characters have been changed) this is quicker than
417 * moving the pointers ahead by len */
418 do {
419 *dst++ = *str++;
420 } while (--len != 0);
421 } else {
422 /* Just skip (strip) the colour codes */
423 str += len;
426 *dst = '\0';
430 * Get the length of an UTF-8 encoded string in number of characters
431 * and thus not the number of bytes that the encoded string contains.
432 * @param s The string to get the length for.
433 * @return The length of the string in characters.
435 size_t Utf8StringLength(const char *s)
437 size_t len = 0;
438 const char *t = s;
439 while (Utf8Consume(&t) != 0) len++;
440 return len;
444 * Get the length of an UTF-8 encoded string in number of characters
445 * and thus not the number of bytes that the encoded string contains.
446 * @param s The string to get the length for.
447 * @return The length of the string in characters.
449 size_t Utf8StringLength(const std::string &str)
451 return Utf8StringLength(str.c_str());
455 * Convert a given ASCII string to lowercase.
456 * NOTE: only support ASCII characters, no UTF8 fancy. As currently
457 * the function is only used to lowercase data-filenames if they are
458 * not found, this is sufficient. If more, or general functionality is
459 * needed, look to r7271 where it was removed because it was broken when
460 * using certain locales: eg in Turkish the uppercase 'I' was converted to
461 * '?', so just revert to the old functionality
462 * @param str string to convert
463 * @return String has changed.
465 bool strtolower(char *str)
467 bool changed = false;
468 for (; *str != '\0'; str++) {
469 char new_str = tolower(*str);
470 changed |= new_str != *str;
471 *str = new_str;
473 return changed;
476 bool strtolower(std::string &str, std::string::size_type offs)
478 bool changed = false;
479 for (auto ch = str.begin() + offs; ch != str.end(); ++ch) {
480 auto new_ch = static_cast<char>(tolower(static_cast<unsigned char>(*ch)));
481 changed |= new_ch != *ch;
482 *ch = new_ch;
484 return changed;
488 * Only allow certain keys. You can define the filter to be used. This makes
489 * sure no invalid keys can get into an editbox, like BELL.
490 * @param key character to be checked
491 * @param afilter the filter to use
492 * @return true or false depending if the character is printable/valid or not
494 bool IsValidChar(WChar key, CharSetFilter afilter)
496 switch (afilter) {
497 case CS_ALPHANUMERAL: return IsPrintable(key);
498 case CS_NUMERAL: return (key >= '0' && key <= '9');
499 case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' ';
500 case CS_ALPHA: return IsPrintable(key) && !(key >= '0' && key <= '9');
501 case CS_HEXADECIMAL: return (key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (key >= 'A' && key <= 'F');
502 default: NOT_REACHED();
506 #ifdef _WIN32
507 #if defined(_MSC_VER) && _MSC_VER < 1900
509 * Almost POSIX compliant implementation of \c vsnprintf for VC compiler.
510 * The difference is in the value returned on output truncation. This
511 * implementation returns size whereas a POSIX implementation returns
512 * size or more (the number of bytes that would be written to str
513 * had size been sufficiently large excluding the terminating null byte).
515 int CDECL vsnprintf(char *str, size_t size, const char *format, va_list ap)
517 if (size == 0) return 0;
519 errno = 0;
520 int ret = _vsnprintf(str, size, format, ap);
522 if (ret < 0) {
523 if (errno != ERANGE) {
524 /* There's a formatting error, better get that looked
525 * at properly instead of ignoring it. */
526 NOT_REACHED();
528 } else if ((size_t)ret < size) {
529 /* The buffer is big enough for the number of
530 * characters stored (excluding null), i.e.
531 * the string has been null-terminated. */
532 return ret;
535 /* The buffer is too small for _vsnprintf to write the
536 * null-terminator at its end and return size. */
537 str[size - 1] = '\0';
538 return (int)size;
540 #endif /* _MSC_VER */
542 #endif /* _WIN32 */
545 * Safer implementation of snprintf; same as snprintf except:
546 * - last instead of size, i.e. replace sizeof with lastof.
547 * - return gives the amount of characters added, not what it would add.
548 * @param str buffer to write to up to last
549 * @param last last character we may write to
550 * @param format the formatting (see snprintf)
551 * @return the number of added characters
553 int CDECL seprintf(char *str, const char *last, const char *format, ...)
555 va_list ap;
557 va_start(ap, format);
558 int ret = vseprintf(str, last, format, ap);
559 va_end(ap);
560 return ret;
565 * Convert the md5sum to a hexadecimal string representation
566 * @param buf buffer to put the md5sum into
567 * @param last last character of buffer (usually lastof(buf))
568 * @param md5sum the md5sum itself
569 * @return a pointer to the next character after the md5sum
571 char *md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
573 char *p = buf;
575 for (uint i = 0; i < 16; i++) {
576 p += seprintf(p, last, "%02X", md5sum[i]);
579 return p;
583 /* UTF-8 handling routines */
587 * Decode and consume the next UTF-8 encoded character.
588 * @param c Buffer to place decoded character.
589 * @param s Character stream to retrieve character from.
590 * @return Number of characters in the sequence.
592 size_t Utf8Decode(WChar *c, const char *s)
594 assert(c != nullptr);
596 if (!HasBit(s[0], 7)) {
597 /* Single byte character: 0xxxxxxx */
598 *c = s[0];
599 return 1;
600 } else if (GB(s[0], 5, 3) == 6) {
601 if (IsUtf8Part(s[1])) {
602 /* Double byte character: 110xxxxx 10xxxxxx */
603 *c = GB(s[0], 0, 5) << 6 | GB(s[1], 0, 6);
604 if (*c >= 0x80) return 2;
606 } else if (GB(s[0], 4, 4) == 14) {
607 if (IsUtf8Part(s[1]) && IsUtf8Part(s[2])) {
608 /* Triple byte character: 1110xxxx 10xxxxxx 10xxxxxx */
609 *c = GB(s[0], 0, 4) << 12 | GB(s[1], 0, 6) << 6 | GB(s[2], 0, 6);
610 if (*c >= 0x800) return 3;
612 } else if (GB(s[0], 3, 5) == 30) {
613 if (IsUtf8Part(s[1]) && IsUtf8Part(s[2]) && IsUtf8Part(s[3])) {
614 /* 4 byte character: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
615 *c = GB(s[0], 0, 3) << 18 | GB(s[1], 0, 6) << 12 | GB(s[2], 0, 6) << 6 | GB(s[3], 0, 6);
616 if (*c >= 0x10000 && *c <= 0x10FFFF) return 4;
620 /* Debug(misc, 1, "[utf8] invalid UTF-8 sequence"); */
621 *c = '?';
622 return 1;
627 * Encode a unicode character and place it in the buffer.
628 * @tparam T Type of the buffer.
629 * @param buf Buffer to place character.
630 * @param c Unicode character to encode.
631 * @return Number of characters in the encoded sequence.
633 template <class T>
634 inline size_t Utf8Encode(T buf, WChar c)
636 if (c < 0x80) {
637 *buf = c;
638 return 1;
639 } else if (c < 0x800) {
640 *buf++ = 0xC0 + GB(c, 6, 5);
641 *buf = 0x80 + GB(c, 0, 6);
642 return 2;
643 } else if (c < 0x10000) {
644 *buf++ = 0xE0 + GB(c, 12, 4);
645 *buf++ = 0x80 + GB(c, 6, 6);
646 *buf = 0x80 + GB(c, 0, 6);
647 return 3;
648 } else if (c < 0x110000) {
649 *buf++ = 0xF0 + GB(c, 18, 3);
650 *buf++ = 0x80 + GB(c, 12, 6);
651 *buf++ = 0x80 + GB(c, 6, 6);
652 *buf = 0x80 + GB(c, 0, 6);
653 return 4;
656 /* Debug(misc, 1, "[utf8] can't UTF-8 encode value 0x{:X}", c); */
657 *buf = '?';
658 return 1;
661 size_t Utf8Encode(char *buf, WChar c)
663 return Utf8Encode<char *>(buf, c);
666 size_t Utf8Encode(std::ostreambuf_iterator<char> &buf, WChar c)
668 return Utf8Encode<std::ostreambuf_iterator<char> &>(buf, c);
672 * Properly terminate an UTF8 string to some maximum length
673 * @param s string to check if it needs additional trimming
674 * @param maxlen the maximum length the buffer can have.
675 * @return the new length in bytes of the string (eg. strlen(new_string))
676 * @note maxlen is the string length _INCLUDING_ the terminating '\0'
678 size_t Utf8TrimString(char *s, size_t maxlen)
680 size_t length = 0;
682 for (const char *ptr = strchr(s, '\0'); *s != '\0';) {
683 size_t len = Utf8EncodedCharLen(*s);
684 /* Silently ignore invalid UTF8 sequences, our only concern trimming */
685 if (len == 0) len = 1;
687 /* Take care when a hard cutoff was made for the string and
688 * the last UTF8 sequence is invalid */
689 if (length + len >= maxlen || (s + len > ptr)) break;
690 s += len;
691 length += len;
694 *s = '\0';
695 return length;
698 #ifdef DEFINE_STRCASESTR
699 char *strcasestr(const char *haystack, const char *needle)
701 size_t hay_len = strlen(haystack);
702 size_t needle_len = strlen(needle);
703 while (hay_len >= needle_len) {
704 if (strncasecmp(haystack, needle, needle_len) == 0) return const_cast<char *>(haystack);
706 haystack++;
707 hay_len--;
710 return nullptr;
712 #endif /* DEFINE_STRCASESTR */
715 * Skip some of the 'garbage' in the string that we don't want to use
716 * to sort on. This way the alphabetical sorting will work better as
717 * we would be actually using those characters instead of some other
718 * characters such as spaces and tildes at the begin of the name.
719 * @param str The string to skip the initial garbage of.
720 * @return The string with the garbage skipped.
722 static const char *SkipGarbage(const char *str)
724 while (*str != '\0' && (*str < '0' || IsInsideMM(*str, ';', '@' + 1) || IsInsideMM(*str, '[', '`' + 1) || IsInsideMM(*str, '{', '~' + 1))) str++;
725 return str;
729 * Compares two strings using case insensitive natural sort.
731 * @param s1 First string to compare.
732 * @param s2 Second string to compare.
733 * @param ignore_garbage_at_front Skip punctuation characters in the front
734 * @return Less than zero if s1 < s2, zero if s1 == s2, greater than zero if s1 > s2.
736 int strnatcmp(const char *s1, const char *s2, bool ignore_garbage_at_front)
738 if (ignore_garbage_at_front) {
739 s1 = SkipGarbage(s1);
740 s2 = SkipGarbage(s2);
743 #ifdef WITH_ICU_I18N
744 if (_current_collator) {
745 UErrorCode status = U_ZERO_ERROR;
746 int result = _current_collator->compareUTF8(s1, s2, status);
747 if (U_SUCCESS(status)) return result;
749 #endif /* WITH_ICU_I18N */
751 #if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
752 int res = OTTDStringCompare(s1, s2);
753 if (res != 0) return res - 2; // Convert to normal C return values.
754 #endif
756 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
757 int res = MacOSStringCompare(s1, s2);
758 if (res != 0) return res - 2; // Convert to normal C return values.
759 #endif
761 /* Do a normal comparison if ICU is missing or if we cannot create a collator. */
762 return strcasecmp(s1, s2);
765 #ifdef WITH_UNISCRIBE
767 /* static */ StringIterator *StringIterator::Create()
769 return new UniscribeStringIterator();
772 #elif defined(WITH_ICU_I18N)
774 #include <unicode/utext.h>
775 #include <unicode/brkiter.h>
777 /** String iterator using ICU as a backend. */
778 class IcuStringIterator : public StringIterator
780 icu::BreakIterator *char_itr; ///< ICU iterator for characters.
781 icu::BreakIterator *word_itr; ///< ICU iterator for words.
783 std::vector<UChar> utf16_str; ///< UTF-16 copy of the string.
784 std::vector<size_t> utf16_to_utf8; ///< Mapping from UTF-16 code point position to index in the UTF-8 source string.
786 public:
787 IcuStringIterator() : char_itr(nullptr), word_itr(nullptr)
789 UErrorCode status = U_ZERO_ERROR;
790 this->char_itr = icu::BreakIterator::createCharacterInstance(icu::Locale(_current_language != nullptr ? _current_language->isocode : "en"), status);
791 this->word_itr = icu::BreakIterator::createWordInstance(icu::Locale(_current_language != nullptr ? _current_language->isocode : "en"), status);
793 this->utf16_str.push_back('\0');
794 this->utf16_to_utf8.push_back(0);
797 ~IcuStringIterator() override
799 delete this->char_itr;
800 delete this->word_itr;
803 void SetString(const char *s) override
805 const char *string_base = s;
807 /* Unfortunately current ICU versions only provide rudimentary support
808 * for word break iterators (especially for CJK languages) in combination
809 * with UTF-8 input. As a work around we have to convert the input to
810 * UTF-16 and create a mapping back to UTF-8 character indices. */
811 this->utf16_str.clear();
812 this->utf16_to_utf8.clear();
814 while (*s != '\0') {
815 size_t idx = s - string_base;
817 WChar c = Utf8Consume(&s);
818 if (c < 0x10000) {
819 this->utf16_str.push_back((UChar)c);
820 } else {
821 /* Make a surrogate pair. */
822 this->utf16_str.push_back((UChar)(0xD800 + ((c - 0x10000) >> 10)));
823 this->utf16_str.push_back((UChar)(0xDC00 + ((c - 0x10000) & 0x3FF)));
824 this->utf16_to_utf8.push_back(idx);
826 this->utf16_to_utf8.push_back(idx);
828 this->utf16_str.push_back('\0');
829 this->utf16_to_utf8.push_back(s - string_base);
831 UText text = UTEXT_INITIALIZER;
832 UErrorCode status = U_ZERO_ERROR;
833 utext_openUChars(&text, this->utf16_str.data(), this->utf16_str.size() - 1, &status);
834 this->char_itr->setText(&text, status);
835 this->word_itr->setText(&text, status);
836 this->char_itr->first();
837 this->word_itr->first();
840 size_t SetCurPosition(size_t pos) override
842 /* Convert incoming position to an UTF-16 string index. */
843 uint utf16_pos = 0;
844 for (uint i = 0; i < this->utf16_to_utf8.size(); i++) {
845 if (this->utf16_to_utf8[i] == pos) {
846 utf16_pos = i;
847 break;
851 /* isBoundary has the documented side-effect of setting the current
852 * position to the first valid boundary equal to or greater than
853 * the passed value. */
854 this->char_itr->isBoundary(utf16_pos);
855 return this->utf16_to_utf8[this->char_itr->current()];
858 size_t Next(IterType what) override
860 int32_t pos;
861 switch (what) {
862 case ITER_CHARACTER:
863 pos = this->char_itr->next();
864 break;
866 case ITER_WORD:
867 pos = this->word_itr->following(this->char_itr->current());
868 /* The ICU word iterator considers both the start and the end of a word a valid
869 * break point, but we only want word starts. Move to the next location in
870 * case the new position points to whitespace. */
871 while (pos != icu::BreakIterator::DONE &&
872 IsWhitespace(Utf16DecodeChar((const uint16 *)&this->utf16_str[pos]))) {
873 int32_t new_pos = this->word_itr->next();
874 /* Don't set it to DONE if it was valid before. Otherwise we'll return END
875 * even though the iterator wasn't at the end of the string before. */
876 if (new_pos == icu::BreakIterator::DONE) break;
877 pos = new_pos;
880 this->char_itr->isBoundary(pos);
881 break;
883 default:
884 NOT_REACHED();
887 return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
890 size_t Prev(IterType what) override
892 int32_t pos;
893 switch (what) {
894 case ITER_CHARACTER:
895 pos = this->char_itr->previous();
896 break;
898 case ITER_WORD:
899 pos = this->word_itr->preceding(this->char_itr->current());
900 /* The ICU word iterator considers both the start and the end of a word a valid
901 * break point, but we only want word starts. Move to the previous location in
902 * case the new position points to whitespace. */
903 while (pos != icu::BreakIterator::DONE &&
904 IsWhitespace(Utf16DecodeChar((const uint16 *)&this->utf16_str[pos]))) {
905 int32_t new_pos = this->word_itr->previous();
906 /* Don't set it to DONE if it was valid before. Otherwise we'll return END
907 * even though the iterator wasn't at the start of the string before. */
908 if (new_pos == icu::BreakIterator::DONE) break;
909 pos = new_pos;
912 this->char_itr->isBoundary(pos);
913 break;
915 default:
916 NOT_REACHED();
919 return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
923 /* static */ StringIterator *StringIterator::Create()
925 return new IcuStringIterator();
928 #else
930 /** Fallback simple string iterator. */
931 class DefaultStringIterator : public StringIterator
933 const char *string; ///< Current string.
934 size_t len; ///< String length.
935 size_t cur_pos; ///< Current iteration position.
937 public:
938 DefaultStringIterator() : string(nullptr), len(0), cur_pos(0)
942 virtual void SetString(const char *s)
944 this->string = s;
945 this->len = strlen(s);
946 this->cur_pos = 0;
949 virtual size_t SetCurPosition(size_t pos)
951 assert(this->string != nullptr && pos <= this->len);
952 /* Sanitize in case we get a position inside an UTF-8 sequence. */
953 while (pos > 0 && IsUtf8Part(this->string[pos])) pos--;
954 return this->cur_pos = pos;
957 virtual size_t Next(IterType what)
959 assert(this->string != nullptr);
961 /* Already at the end? */
962 if (this->cur_pos >= this->len) return END;
964 switch (what) {
965 case ITER_CHARACTER: {
966 WChar c;
967 this->cur_pos += Utf8Decode(&c, this->string + this->cur_pos);
968 return this->cur_pos;
971 case ITER_WORD: {
972 WChar c;
973 /* Consume current word. */
974 size_t offs = Utf8Decode(&c, this->string + this->cur_pos);
975 while (this->cur_pos < this->len && !IsWhitespace(c)) {
976 this->cur_pos += offs;
977 offs = Utf8Decode(&c, this->string + this->cur_pos);
979 /* Consume whitespace to the next word. */
980 while (this->cur_pos < this->len && IsWhitespace(c)) {
981 this->cur_pos += offs;
982 offs = Utf8Decode(&c, this->string + this->cur_pos);
985 return this->cur_pos;
988 default:
989 NOT_REACHED();
992 return END;
995 virtual size_t Prev(IterType what)
997 assert(this->string != nullptr);
999 /* Already at the beginning? */
1000 if (this->cur_pos == 0) return END;
1002 switch (what) {
1003 case ITER_CHARACTER:
1004 return this->cur_pos = Utf8PrevChar(this->string + this->cur_pos) - this->string;
1006 case ITER_WORD: {
1007 const char *s = this->string + this->cur_pos;
1008 WChar c;
1009 /* Consume preceding whitespace. */
1010 do {
1011 s = Utf8PrevChar(s);
1012 Utf8Decode(&c, s);
1013 } while (s > this->string && IsWhitespace(c));
1014 /* Consume preceding word. */
1015 while (s > this->string && !IsWhitespace(c)) {
1016 s = Utf8PrevChar(s);
1017 Utf8Decode(&c, s);
1019 /* Move caret back to the beginning of the word. */
1020 if (IsWhitespace(c)) Utf8Consume(&s);
1022 return this->cur_pos = s - this->string;
1025 default:
1026 NOT_REACHED();
1029 return END;
1033 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
1034 /* static */ StringIterator *StringIterator::Create()
1036 StringIterator *i = OSXStringIterator::Create();
1037 if (i != nullptr) return i;
1039 return new DefaultStringIterator();
1041 #else
1042 /* static */ StringIterator *StringIterator::Create()
1044 return new DefaultStringIterator();
1046 #endif /* defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN) */
1048 #endif