Fix: Data races on cursor state in OpenGL backends
[openttd-github.git] / src / string.cpp
blobadc757b871ecb310556f3bd36c9edecd5e19fe25
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>
23 #ifdef _MSC_VER
24 #include <errno.h> // required by vsnprintf implementation for MSVC
25 #endif
27 #ifdef _WIN32
28 #include "os/windows/win32.h"
29 #endif
31 #ifdef WITH_UNISCRIBE
32 #include "os/windows/string_uniscribe.h"
33 #endif
35 #ifdef WITH_ICU_I18N
36 /* Required by strnatcmp. */
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"
44 #endif
46 /* The function vsnprintf is used internally to perform the required formatting
47 * tasks. As such this one must be allowed, and makes sure it's terminated. */
48 #include "safeguards.h"
49 #undef vsnprintf
51 /**
52 * Safer implementation of vsnprintf; same as vsnprintf except:
53 * - last instead of size, i.e. replace sizeof with lastof.
54 * - return gives the amount of characters added, not what it would add.
55 * @param str buffer to write to up to last
56 * @param last last character we may write to
57 * @param format the formatting (see snprintf)
58 * @param ap the list of arguments for the format
59 * @return the number of added characters
61 int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
63 ptrdiff_t diff = last - str;
64 if (diff < 0) return 0;
65 return std::min(static_cast<int>(diff), vsnprintf(str, diff + 1, format, ap));
68 /**
69 * Appends characters from one string to another.
71 * Appends the source string to the destination string with respect of the
72 * terminating null-character and and the last pointer to the last element
73 * in the destination buffer. If the last pointer is set to nullptr no
74 * boundary check is performed.
76 * @note usage: strecat(dst, src, lastof(dst));
77 * @note lastof() applies only to fixed size arrays
79 * @param dst The buffer containing the target string
80 * @param src The buffer containing the string to append
81 * @param last The pointer to the last element of the destination buffer
82 * @return The pointer to the terminating null-character in the destination buffer
84 char *strecat(char *dst, const char *src, const char *last)
86 assert(dst <= last);
87 while (*dst != '\0') {
88 if (dst == last) return dst;
89 dst++;
92 return strecpy(dst, src, last);
96 /**
97 * Copies characters from one buffer to another.
99 * Copies the source string to the destination buffer with respect of the
100 * terminating null-character and the last pointer to the last element in
101 * the destination buffer. If the last pointer is set to nullptr no boundary
102 * check is performed.
104 * @note usage: strecpy(dst, src, lastof(dst));
105 * @note lastof() applies only to fixed size arrays
107 * @param dst The destination buffer
108 * @param src The buffer containing the string to copy
109 * @param last The pointer to the last element of the destination buffer
110 * @return The pointer to the terminating null-character in the destination buffer
112 char *strecpy(char *dst, const char *src, const char *last)
114 assert(dst <= last);
115 while (dst != last && *src != '\0') {
116 *dst++ = *src++;
118 *dst = '\0';
120 if (dst == last && *src != '\0') {
121 #if defined(STRGEN) || defined(SETTINGSGEN)
122 error("String too long for destination buffer");
123 #else /* STRGEN || SETTINGSGEN */
124 DEBUG(misc, 0, "String too long for destination buffer");
125 #endif /* STRGEN || SETTINGSGEN */
127 return dst;
131 * Create a duplicate of the given string.
132 * @param s The string to duplicate.
133 * @param last The last character that is safe to duplicate. If nullptr, the whole string is duplicated.
134 * @note The maximum length of the resulting string might therefore be last - s + 1.
135 * @return The duplicate of the string.
137 char *stredup(const char *s, const char *last)
139 size_t len = last == nullptr ? strlen(s) : ttd_strnlen(s, last - s + 1);
140 char *tmp = CallocT<char>(len + 1);
141 memcpy(tmp, s, len);
142 return tmp;
146 * Format, "printf", into a newly allocated string.
147 * @param str The formatting string.
148 * @return The formatted string. You must free this!
150 char *CDECL str_fmt(const char *str, ...)
152 char buf[4096];
153 va_list va;
155 va_start(va, str);
156 int len = vseprintf(buf, lastof(buf), str, va);
157 va_end(va);
158 char *p = MallocT<char>(len + 1);
159 memcpy(p, buf, len + 1);
160 return p;
164 * Scan the string for old values of SCC_ENCODED and fix it to
165 * it's new, static value.
166 * @param str the string to scan
167 * @param last the last valid character of str
169 void str_fix_scc_encoded(char *str, const char *last)
171 while (str <= last && *str != '\0') {
172 size_t len = Utf8EncodedCharLen(*str);
173 if ((len == 0 && str + 4 > last) || str + len > last) break;
175 WChar c;
176 Utf8Decode(&c, str);
177 if (c == '\0') break;
179 if (c == 0xE028 || c == 0xE02A) {
180 c = SCC_ENCODED;
182 str += Utf8Encode(str, c);
184 *str = '\0';
188 template <class T>
189 static void str_validate(T &dst, const char *str, const char *last, StringValidationSettings settings)
191 /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
193 while (str <= last && *str != '\0') {
194 size_t len = Utf8EncodedCharLen(*str);
195 /* If the character is unknown, i.e. encoded length is 0
196 * we assume worst case for the length check.
197 * The length check is needed to prevent Utf8Decode to read
198 * over the terminating '\0' if that happens to be placed
199 * within the encoding of an UTF8 character. */
200 if ((len == 0 && str + 4 > last) || str + len > last) break;
202 WChar c;
203 len = Utf8Decode(&c, str);
204 /* It's possible to encode the string termination character
205 * into a multiple bytes. This prevents those termination
206 * characters to be skipped */
207 if (c == '\0') break;
209 if ((IsPrintable(c) && (c < SCC_SPRITE_START || c > SCC_SPRITE_END)) || ((settings & SVS_ALLOW_CONTROL_CODE) != 0 && c == SCC_ENCODED)) {
210 /* Copy the character back. Even if dst is current the same as str
211 * (i.e. no characters have been changed) this is quicker than
212 * moving the pointers ahead by len */
213 do {
214 *dst++ = *str++;
215 } while (--len != 0);
216 } else if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\n') {
217 *dst++ = *str++;
218 } else {
219 if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\r' && str[1] == '\n') {
220 str += len;
221 continue;
223 /* Replace the undesirable character with a question mark */
224 str += len;
225 if ((settings & SVS_REPLACE_WITH_QUESTION_MARK) != 0) *dst++ = '?';
231 * Scans the string for valid characters and if it finds invalid ones,
232 * replaces them with a question mark '?' (if not ignored)
233 * @param str the string to validate
234 * @param last the last valid character of str
235 * @param settings the settings for the string validation.
237 void str_validate(char *str, const char *last, StringValidationSettings settings)
239 char *dst = str;
240 str_validate(dst, str, last, settings);
241 *dst = '\0';
245 * Scans the string for valid characters and if it finds invalid ones,
246 * replaces them with a question mark '?' (if not ignored)
247 * @param str the string to validate
248 * @param settings the settings for the string validation.
250 std::string str_validate(const std::string &str, StringValidationSettings settings)
252 auto buf = str.data();
253 auto last = buf + str.size();
255 std::ostringstream dst;
256 std::ostreambuf_iterator<char> dst_iter(dst);
257 str_validate(dst_iter, buf, last, settings);
259 return dst.str();
263 * Scans the string for valid characters and if it finds invalid ones,
264 * replaces them with a question mark '?'.
265 * @param str the string to validate
267 void ValidateString(const char *str)
269 /* We know it is '\0' terminated. */
270 str_validate(const_cast<char *>(str), str + strlen(str) + 1);
275 * Checks whether the given string is valid, i.e. contains only
276 * valid (printable) characters and is properly terminated.
277 * @param str The string to validate.
278 * @param last The last character of the string, i.e. the string
279 * must be terminated here or earlier.
281 bool StrValid(const char *str, const char *last)
283 /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
285 while (str <= last && *str != '\0') {
286 size_t len = Utf8EncodedCharLen(*str);
287 /* Encoded length is 0 if the character isn't known.
288 * The length check is needed to prevent Utf8Decode to read
289 * over the terminating '\0' if that happens to be placed
290 * within the encoding of an UTF8 character. */
291 if (len == 0 || str + len > last) return false;
293 WChar c;
294 len = Utf8Decode(&c, str);
295 if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
296 return false;
299 str += len;
302 return *str == '\0';
305 /** Scans the string for colour codes and strips them */
306 void str_strip_colours(char *str)
308 char *dst = str;
309 WChar c;
310 size_t len;
312 for (len = Utf8Decode(&c, str); c != '\0'; len = Utf8Decode(&c, str)) {
313 if (c < SCC_BLUE || c > SCC_BLACK) {
314 /* Copy the character back. Even if dst is current the same as str
315 * (i.e. no characters have been changed) this is quicker than
316 * moving the pointers ahead by len */
317 do {
318 *dst++ = *str++;
319 } while (--len != 0);
320 } else {
321 /* Just skip (strip) the colour codes */
322 str += len;
325 *dst = '\0';
329 * Get the length of an UTF-8 encoded string in number of characters
330 * and thus not the number of bytes that the encoded string contains.
331 * @param s The string to get the length for.
332 * @return The length of the string in characters.
334 size_t Utf8StringLength(const char *s)
336 size_t len = 0;
337 const char *t = s;
338 while (Utf8Consume(&t) != 0) len++;
339 return len;
344 * Convert a given ASCII string to lowercase.
345 * NOTE: only support ASCII characters, no UTF8 fancy. As currently
346 * the function is only used to lowercase data-filenames if they are
347 * not found, this is sufficient. If more, or general functionality is
348 * needed, look to r7271 where it was removed because it was broken when
349 * using certain locales: eg in Turkish the uppercase 'I' was converted to
350 * '?', so just revert to the old functionality
351 * @param str string to convert
352 * @return String has changed.
354 bool strtolower(char *str)
356 bool changed = false;
357 for (; *str != '\0'; str++) {
358 char new_str = tolower(*str);
359 changed |= new_str != *str;
360 *str = new_str;
362 return changed;
365 bool strtolower(std::string &str, std::string::size_type offs)
367 bool changed = false;
368 for (auto ch = str.begin() + offs; ch != str.end(); ++ch) {
369 auto new_ch = static_cast<char>(tolower(static_cast<unsigned char>(*ch)));
370 changed |= new_ch != *ch;
371 *ch = new_ch;
373 return changed;
377 * Only allow certain keys. You can define the filter to be used. This makes
378 * sure no invalid keys can get into an editbox, like BELL.
379 * @param key character to be checked
380 * @param afilter the filter to use
381 * @return true or false depending if the character is printable/valid or not
383 bool IsValidChar(WChar key, CharSetFilter afilter)
385 switch (afilter) {
386 case CS_ALPHANUMERAL: return IsPrintable(key);
387 case CS_NUMERAL: return (key >= '0' && key <= '9');
388 case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' ';
389 case CS_ALPHA: return IsPrintable(key) && !(key >= '0' && key <= '9');
390 case CS_HEXADECIMAL: return (key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (key >= 'A' && key <= 'F');
391 default: NOT_REACHED();
395 #ifdef _WIN32
396 #if defined(_MSC_VER) && _MSC_VER < 1900
398 * Almost POSIX compliant implementation of \c vsnprintf for VC compiler.
399 * The difference is in the value returned on output truncation. This
400 * implementation returns size whereas a POSIX implementation returns
401 * size or more (the number of bytes that would be written to str
402 * had size been sufficiently large excluding the terminating null byte).
404 int CDECL vsnprintf(char *str, size_t size, const char *format, va_list ap)
406 if (size == 0) return 0;
408 errno = 0;
409 int ret = _vsnprintf(str, size, format, ap);
411 if (ret < 0) {
412 if (errno != ERANGE) {
413 /* There's a formatting error, better get that looked
414 * at properly instead of ignoring it. */
415 NOT_REACHED();
417 } else if ((size_t)ret < size) {
418 /* The buffer is big enough for the number of
419 * characters stored (excluding null), i.e.
420 * the string has been null-terminated. */
421 return ret;
424 /* The buffer is too small for _vsnprintf to write the
425 * null-terminator at its end and return size. */
426 str[size - 1] = '\0';
427 return (int)size;
429 #endif /* _MSC_VER */
431 #endif /* _WIN32 */
434 * Safer implementation of snprintf; same as snprintf except:
435 * - last instead of size, i.e. replace sizeof with lastof.
436 * - return gives the amount of characters added, not what it would add.
437 * @param str buffer to write to up to last
438 * @param last last character we may write to
439 * @param format the formatting (see snprintf)
440 * @return the number of added characters
442 int CDECL seprintf(char *str, const char *last, const char *format, ...)
444 va_list ap;
446 va_start(ap, format);
447 int ret = vseprintf(str, last, format, ap);
448 va_end(ap);
449 return ret;
454 * Convert the md5sum to a hexadecimal string representation
455 * @param buf buffer to put the md5sum into
456 * @param last last character of buffer (usually lastof(buf))
457 * @param md5sum the md5sum itself
458 * @return a pointer to the next character after the md5sum
460 char *md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
462 char *p = buf;
464 for (uint i = 0; i < 16; i++) {
465 p += seprintf(p, last, "%02X", md5sum[i]);
468 return p;
472 /* UTF-8 handling routines */
476 * Decode and consume the next UTF-8 encoded character.
477 * @param c Buffer to place decoded character.
478 * @param s Character stream to retrieve character from.
479 * @return Number of characters in the sequence.
481 size_t Utf8Decode(WChar *c, const char *s)
483 assert(c != nullptr);
485 if (!HasBit(s[0], 7)) {
486 /* Single byte character: 0xxxxxxx */
487 *c = s[0];
488 return 1;
489 } else if (GB(s[0], 5, 3) == 6) {
490 if (IsUtf8Part(s[1])) {
491 /* Double byte character: 110xxxxx 10xxxxxx */
492 *c = GB(s[0], 0, 5) << 6 | GB(s[1], 0, 6);
493 if (*c >= 0x80) return 2;
495 } else if (GB(s[0], 4, 4) == 14) {
496 if (IsUtf8Part(s[1]) && IsUtf8Part(s[2])) {
497 /* Triple byte character: 1110xxxx 10xxxxxx 10xxxxxx */
498 *c = GB(s[0], 0, 4) << 12 | GB(s[1], 0, 6) << 6 | GB(s[2], 0, 6);
499 if (*c >= 0x800) return 3;
501 } else if (GB(s[0], 3, 5) == 30) {
502 if (IsUtf8Part(s[1]) && IsUtf8Part(s[2]) && IsUtf8Part(s[3])) {
503 /* 4 byte character: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
504 *c = GB(s[0], 0, 3) << 18 | GB(s[1], 0, 6) << 12 | GB(s[2], 0, 6) << 6 | GB(s[3], 0, 6);
505 if (*c >= 0x10000 && *c <= 0x10FFFF) return 4;
509 /* DEBUG(misc, 1, "[utf8] invalid UTF-8 sequence"); */
510 *c = '?';
511 return 1;
516 * Encode a unicode character and place it in the buffer.
517 * @tparam T Type of the buffer.
518 * @param buf Buffer to place character.
519 * @param c Unicode character to encode.
520 * @return Number of characters in the encoded sequence.
522 template <class T>
523 inline size_t Utf8Encode(T buf, WChar c)
525 if (c < 0x80) {
526 *buf = c;
527 return 1;
528 } else if (c < 0x800) {
529 *buf++ = 0xC0 + GB(c, 6, 5);
530 *buf = 0x80 + GB(c, 0, 6);
531 return 2;
532 } else if (c < 0x10000) {
533 *buf++ = 0xE0 + GB(c, 12, 4);
534 *buf++ = 0x80 + GB(c, 6, 6);
535 *buf = 0x80 + GB(c, 0, 6);
536 return 3;
537 } else if (c < 0x110000) {
538 *buf++ = 0xF0 + GB(c, 18, 3);
539 *buf++ = 0x80 + GB(c, 12, 6);
540 *buf++ = 0x80 + GB(c, 6, 6);
541 *buf = 0x80 + GB(c, 0, 6);
542 return 4;
545 /* DEBUG(misc, 1, "[utf8] can't UTF-8 encode value 0x%X", c); */
546 *buf = '?';
547 return 1;
550 size_t Utf8Encode(char *buf, WChar c)
552 return Utf8Encode<char *>(buf, c);
555 size_t Utf8Encode(std::ostreambuf_iterator<char> &buf, WChar c)
557 return Utf8Encode<std::ostreambuf_iterator<char> &>(buf, c);
561 * Properly terminate an UTF8 string to some maximum length
562 * @param s string to check if it needs additional trimming
563 * @param maxlen the maximum length the buffer can have.
564 * @return the new length in bytes of the string (eg. strlen(new_string))
565 * @note maxlen is the string length _INCLUDING_ the terminating '\0'
567 size_t Utf8TrimString(char *s, size_t maxlen)
569 size_t length = 0;
571 for (const char *ptr = strchr(s, '\0'); *s != '\0';) {
572 size_t len = Utf8EncodedCharLen(*s);
573 /* Silently ignore invalid UTF8 sequences, our only concern trimming */
574 if (len == 0) len = 1;
576 /* Take care when a hard cutoff was made for the string and
577 * the last UTF8 sequence is invalid */
578 if (length + len >= maxlen || (s + len > ptr)) break;
579 s += len;
580 length += len;
583 *s = '\0';
584 return length;
587 #ifdef DEFINE_STRCASESTR
588 char *strcasestr(const char *haystack, const char *needle)
590 size_t hay_len = strlen(haystack);
591 size_t needle_len = strlen(needle);
592 while (hay_len >= needle_len) {
593 if (strncasecmp(haystack, needle, needle_len) == 0) return const_cast<char *>(haystack);
595 haystack++;
596 hay_len--;
599 return nullptr;
601 #endif /* DEFINE_STRCASESTR */
604 * Skip some of the 'garbage' in the string that we don't want to use
605 * to sort on. This way the alphabetical sorting will work better as
606 * we would be actually using those characters instead of some other
607 * characters such as spaces and tildes at the begin of the name.
608 * @param str The string to skip the initial garbage of.
609 * @return The string with the garbage skipped.
611 static const char *SkipGarbage(const char *str)
613 while (*str != '\0' && (*str < '0' || IsInsideMM(*str, ';', '@' + 1) || IsInsideMM(*str, '[', '`' + 1) || IsInsideMM(*str, '{', '~' + 1))) str++;
614 return str;
618 * Compares two strings using case insensitive natural sort.
620 * @param s1 First string to compare.
621 * @param s2 Second string to compare.
622 * @param ignore_garbage_at_front Skip punctuation characters in the front
623 * @return Less than zero if s1 < s2, zero if s1 == s2, greater than zero if s1 > s2.
625 int strnatcmp(const char *s1, const char *s2, bool ignore_garbage_at_front)
627 if (ignore_garbage_at_front) {
628 s1 = SkipGarbage(s1);
629 s2 = SkipGarbage(s2);
632 #ifdef WITH_ICU_I18N
633 if (_current_collator) {
634 UErrorCode status = U_ZERO_ERROR;
635 int result = _current_collator->compareUTF8(s1, s2, status);
636 if (U_SUCCESS(status)) return result;
638 #endif /* WITH_ICU_I18N */
640 #if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
641 int res = OTTDStringCompare(s1, s2);
642 if (res != 0) return res - 2; // Convert to normal C return values.
643 #endif
645 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
646 int res = MacOSStringCompare(s1, s2);
647 if (res != 0) return res - 2; // Convert to normal C return values.
648 #endif
650 /* Do a normal comparison if ICU is missing or if we cannot create a collator. */
651 return strcasecmp(s1, s2);
654 #ifdef WITH_UNISCRIBE
656 /* static */ StringIterator *StringIterator::Create()
658 return new UniscribeStringIterator();
661 #elif defined(WITH_ICU_I18N)
663 #include <unicode/utext.h>
664 #include <unicode/brkiter.h>
666 /** String iterator using ICU as a backend. */
667 class IcuStringIterator : public StringIterator
669 icu::BreakIterator *char_itr; ///< ICU iterator for characters.
670 icu::BreakIterator *word_itr; ///< ICU iterator for words.
672 std::vector<UChar> utf16_str; ///< UTF-16 copy of the string.
673 std::vector<size_t> utf16_to_utf8; ///< Mapping from UTF-16 code point position to index in the UTF-8 source string.
675 public:
676 IcuStringIterator() : char_itr(nullptr), word_itr(nullptr)
678 UErrorCode status = U_ZERO_ERROR;
679 this->char_itr = icu::BreakIterator::createCharacterInstance(icu::Locale(_current_language != nullptr ? _current_language->isocode : "en"), status);
680 this->word_itr = icu::BreakIterator::createWordInstance(icu::Locale(_current_language != nullptr ? _current_language->isocode : "en"), status);
682 this->utf16_str.push_back('\0');
683 this->utf16_to_utf8.push_back(0);
686 ~IcuStringIterator() override
688 delete this->char_itr;
689 delete this->word_itr;
692 void SetString(const char *s) override
694 const char *string_base = s;
696 /* Unfortunately current ICU versions only provide rudimentary support
697 * for word break iterators (especially for CJK languages) in combination
698 * with UTF-8 input. As a work around we have to convert the input to
699 * UTF-16 and create a mapping back to UTF-8 character indices. */
700 this->utf16_str.clear();
701 this->utf16_to_utf8.clear();
703 while (*s != '\0') {
704 size_t idx = s - string_base;
706 WChar c = Utf8Consume(&s);
707 if (c < 0x10000) {
708 this->utf16_str.push_back((UChar)c);
709 } else {
710 /* Make a surrogate pair. */
711 this->utf16_str.push_back((UChar)(0xD800 + ((c - 0x10000) >> 10)));
712 this->utf16_str.push_back((UChar)(0xDC00 + ((c - 0x10000) & 0x3FF)));
713 this->utf16_to_utf8.push_back(idx);
715 this->utf16_to_utf8.push_back(idx);
717 this->utf16_str.push_back('\0');
718 this->utf16_to_utf8.push_back(s - string_base);
720 UText text = UTEXT_INITIALIZER;
721 UErrorCode status = U_ZERO_ERROR;
722 utext_openUChars(&text, this->utf16_str.data(), this->utf16_str.size() - 1, &status);
723 this->char_itr->setText(&text, status);
724 this->word_itr->setText(&text, status);
725 this->char_itr->first();
726 this->word_itr->first();
729 size_t SetCurPosition(size_t pos) override
731 /* Convert incoming position to an UTF-16 string index. */
732 uint utf16_pos = 0;
733 for (uint i = 0; i < this->utf16_to_utf8.size(); i++) {
734 if (this->utf16_to_utf8[i] == pos) {
735 utf16_pos = i;
736 break;
740 /* isBoundary has the documented side-effect of setting the current
741 * position to the first valid boundary equal to or greater than
742 * the passed value. */
743 this->char_itr->isBoundary(utf16_pos);
744 return this->utf16_to_utf8[this->char_itr->current()];
747 size_t Next(IterType what) override
749 int32_t pos;
750 switch (what) {
751 case ITER_CHARACTER:
752 pos = this->char_itr->next();
753 break;
755 case ITER_WORD:
756 pos = this->word_itr->following(this->char_itr->current());
757 /* The ICU word iterator considers both the start and the end of a word a valid
758 * break point, but we only want word starts. Move to the next location in
759 * case the new position points to whitespace. */
760 while (pos != icu::BreakIterator::DONE &&
761 IsWhitespace(Utf16DecodeChar((const uint16 *)&this->utf16_str[pos]))) {
762 int32_t new_pos = this->word_itr->next();
763 /* Don't set it to DONE if it was valid before. Otherwise we'll return END
764 * even though the iterator wasn't at the end of the string before. */
765 if (new_pos == icu::BreakIterator::DONE) break;
766 pos = new_pos;
769 this->char_itr->isBoundary(pos);
770 break;
772 default:
773 NOT_REACHED();
776 return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
779 size_t Prev(IterType what) override
781 int32_t pos;
782 switch (what) {
783 case ITER_CHARACTER:
784 pos = this->char_itr->previous();
785 break;
787 case ITER_WORD:
788 pos = this->word_itr->preceding(this->char_itr->current());
789 /* The ICU word iterator considers both the start and the end of a word a valid
790 * break point, but we only want word starts. Move to the previous location in
791 * case the new position points to whitespace. */
792 while (pos != icu::BreakIterator::DONE &&
793 IsWhitespace(Utf16DecodeChar((const uint16 *)&this->utf16_str[pos]))) {
794 int32_t new_pos = this->word_itr->previous();
795 /* Don't set it to DONE if it was valid before. Otherwise we'll return END
796 * even though the iterator wasn't at the start of the string before. */
797 if (new_pos == icu::BreakIterator::DONE) break;
798 pos = new_pos;
801 this->char_itr->isBoundary(pos);
802 break;
804 default:
805 NOT_REACHED();
808 return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
812 /* static */ StringIterator *StringIterator::Create()
814 return new IcuStringIterator();
817 #else
819 /** Fallback simple string iterator. */
820 class DefaultStringIterator : public StringIterator
822 const char *string; ///< Current string.
823 size_t len; ///< String length.
824 size_t cur_pos; ///< Current iteration position.
826 public:
827 DefaultStringIterator() : string(nullptr), len(0), cur_pos(0)
831 virtual void SetString(const char *s)
833 this->string = s;
834 this->len = strlen(s);
835 this->cur_pos = 0;
838 virtual size_t SetCurPosition(size_t pos)
840 assert(this->string != nullptr && pos <= this->len);
841 /* Sanitize in case we get a position inside an UTF-8 sequence. */
842 while (pos > 0 && IsUtf8Part(this->string[pos])) pos--;
843 return this->cur_pos = pos;
846 virtual size_t Next(IterType what)
848 assert(this->string != nullptr);
850 /* Already at the end? */
851 if (this->cur_pos >= this->len) return END;
853 switch (what) {
854 case ITER_CHARACTER: {
855 WChar c;
856 this->cur_pos += Utf8Decode(&c, this->string + this->cur_pos);
857 return this->cur_pos;
860 case ITER_WORD: {
861 WChar c;
862 /* Consume current word. */
863 size_t offs = Utf8Decode(&c, this->string + this->cur_pos);
864 while (this->cur_pos < this->len && !IsWhitespace(c)) {
865 this->cur_pos += offs;
866 offs = Utf8Decode(&c, this->string + this->cur_pos);
868 /* Consume whitespace to the next word. */
869 while (this->cur_pos < this->len && IsWhitespace(c)) {
870 this->cur_pos += offs;
871 offs = Utf8Decode(&c, this->string + this->cur_pos);
874 return this->cur_pos;
877 default:
878 NOT_REACHED();
881 return END;
884 virtual size_t Prev(IterType what)
886 assert(this->string != nullptr);
888 /* Already at the beginning? */
889 if (this->cur_pos == 0) return END;
891 switch (what) {
892 case ITER_CHARACTER:
893 return this->cur_pos = Utf8PrevChar(this->string + this->cur_pos) - this->string;
895 case ITER_WORD: {
896 const char *s = this->string + this->cur_pos;
897 WChar c;
898 /* Consume preceding whitespace. */
899 do {
900 s = Utf8PrevChar(s);
901 Utf8Decode(&c, s);
902 } while (s > this->string && IsWhitespace(c));
903 /* Consume preceding word. */
904 while (s > this->string && !IsWhitespace(c)) {
905 s = Utf8PrevChar(s);
906 Utf8Decode(&c, s);
908 /* Move caret back to the beginning of the word. */
909 if (IsWhitespace(c)) Utf8Consume(&s);
911 return this->cur_pos = s - this->string;
914 default:
915 NOT_REACHED();
918 return END;
922 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
923 /* static */ StringIterator *StringIterator::Create()
925 StringIterator *i = OSXStringIterator::Create();
926 if (i != nullptr) return i;
928 return new DefaultStringIterator();
930 #else
931 /* static */ StringIterator *StringIterator::Create()
933 return new DefaultStringIterator();
935 #endif /* defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN) */
937 #endif