OpenTTD Source  13.0-beta1
string.cpp
Go to the documentation of this file.
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  */
7 
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"
16 
17 #include "table/control_codes.h"
18 
19 #include <stdarg.h>
20 #include <ctype.h> /* required for tolower() */
21 #include <sstream>
22 #include <iomanip>
23 
24 #ifdef _MSC_VER
25 #include <errno.h> // required by vsnprintf implementation for MSVC
26 #endif
27 
28 #ifdef _WIN32
29 #include "os/windows/win32.h"
30 #endif
31 
32 #ifdef WITH_UNISCRIBE
34 #endif
35 
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 */
42 
43 #if defined(WITH_COCOA)
44 #include "os/macosx/string_osx.h"
45 #endif
46 
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
51 
62 int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
63 {
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));
67 }
68 
85 char *strecat(char *dst, const char *src, const char *last)
86 {
87  assert(dst <= last);
88  while (*dst != '\0') {
89  if (dst == last) return dst;
90  dst++;
91  }
92 
93  return strecpy(dst, src, last);
94 }
95 
96 
113 char *strecpy(char *dst, const char *src, const char *last)
114 {
115  assert(dst <= last);
116  while (dst != last && *src != '\0') {
117  *dst++ = *src++;
118  }
119  *dst = '\0';
120 
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 */
127  }
128  return dst;
129 }
130 
138 char *stredup(const char *s, const char *last)
139 {
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;
144 }
145 
151 char *CDECL str_fmt(const char *str, ...)
152 {
153  char buf[4096];
154  va_list va;
155 
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;
162 }
163 
170 {
171  std::ostringstream ss;
172  ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex;
173 
174  for (auto b : data) {
175  ss << b;
176  }
177 
178  return ss.str();
179 }
180 
187 void str_fix_scc_encoded(char *str, const char *last)
188 {
189  while (str <= last && *str != '\0') {
190  size_t len = Utf8EncodedCharLen(*str);
191  if ((len == 0 && str + 4 > last) || str + len > last) break;
192 
193  WChar c;
194  Utf8Decode(&c, str);
195  if (c == '\0') break;
196 
197  if (c == 0xE028 || c == 0xE02A) {
198  c = SCC_ENCODED;
199  }
200  str += Utf8Encode(str, c);
201  }
202  *str = '\0';
203 }
204 
205 
206 template <class T>
207 static void StrMakeValidInPlace(T &dst, const char *str, const char *last, StringValidationSettings settings)
208 {
209  /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
210 
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.
227  *
228  * The goals here is to get as much valid Utf8 encoded characters from the
229  * source string to the destination string.
230  *
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.
236  */
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;
241  }
242 
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;
256  }
257  /* Replace the undesirable character with a question mark */
258  str += len;
259  if ((settings & SVS_REPLACE_WITH_QUESTION_MARK) != 0) *dst++ = '?';
260  }
261  }
262 
263  /* String termination, if needed, is left to the caller of this function. */
264 }
265 
273 void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
274 {
275  char *dst = str;
276  StrMakeValidInPlace(dst, str, last, settings);
277  *dst = '\0';
278 }
279 
288 {
289  /* We know it is '\0' terminated. */
290  StrMakeValidInPlace(str, str + strlen(str), settings);
291 }
292 
299 std::string StrMakeValid(const std::string &str, StringValidationSettings settings)
300 {
301  auto buf = str.data();
302  auto last = buf + str.size();
303 
304  std::ostringstream dst;
305  std::ostreambuf_iterator<char> dst_iter(dst);
306  StrMakeValidInPlace(dst_iter, buf, last, settings);
307 
308  return dst.str();
309 }
310 
318 bool StrValid(const char *str, const char *last)
319 {
320  /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
321 
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;
329 
330  WChar c;
331  len = Utf8Decode(&c, str);
332  if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
333  return false;
334  }
335 
336  str += len;
337  }
338 
339  return *str == '\0';
340 }
341 
348 static void StrLeftTrimInPlace(std::string &str)
349 {
350  size_t pos = str.find_first_not_of(' ');
351  str.erase(0, pos);
352 }
353 
360 static void StrRightTrimInPlace(std::string &str)
361 {
362  size_t pos = str.find_last_not_of(' ');
363  if (pos != std::string::npos) str.erase(pos + 1);
364 }
365 
373 void StrTrimInPlace(std::string &str)
374 {
375  StrLeftTrimInPlace(str);
376  StrRightTrimInPlace(str);
377 }
378 
385 bool StrStartsWith(const std::string_view str, const std::string_view prefix)
386 {
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;
390 }
391 
398 bool StrEndsWith(const std::string_view str, const std::string_view suffix)
399 {
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;
403 }
404 
405 
407 void str_strip_colours(char *str)
408 {
409  char *dst = str;
410  WChar c;
411  size_t len;
412 
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;
424  }
425  }
426  *dst = '\0';
427 }
428 
435 size_t Utf8StringLength(const char *s)
436 {
437  size_t len = 0;
438  const char *t = s;
439  while (Utf8Consume(&t) != 0) len++;
440  return len;
441 }
442 
449 size_t Utf8StringLength(const std::string &str)
450 {
451  return Utf8StringLength(str.c_str());
452 }
453 
465 bool strtolower(char *str)
466 {
467  bool changed = false;
468  for (; *str != '\0'; str++) {
469  char new_str = tolower(*str);
470  changed |= new_str != *str;
471  *str = new_str;
472  }
473  return changed;
474 }
475 
476 bool strtolower(std::string &str, std::string::size_type offs)
477 {
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;
483  }
484  return changed;
485 }
486 
494 bool IsValidChar(WChar key, CharSetFilter afilter)
495 {
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();
503  }
504 }
505 
506 #ifdef _WIN32
507 #if defined(_MSC_VER) && _MSC_VER < 1900
508 
515 int CDECL vsnprintf(char *str, size_t size, const char *format, va_list ap)
516 {
517  if (size == 0) return 0;
518 
519  errno = 0;
520  int ret = _vsnprintf(str, size, format, ap);
521 
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();
527  }
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;
533  }
534 
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;
539 }
540 #endif /* _MSC_VER */
541 
542 #endif /* _WIN32 */
543 
553 int CDECL seprintf(char *str, const char *last, const char *format, ...)
554 {
555  va_list ap;
556 
557  va_start(ap, format);
558  int ret = vseprintf(str, last, format, ap);
559  va_end(ap);
560  return ret;
561 }
562 
563 
571 char *md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
572 {
573  char *p = buf;
574 
575  for (uint i = 0; i < 16; i++) {
576  p += seprintf(p, last, "%02X", md5sum[i]);
577  }
578 
579  return p;
580 }
581 
582 
583 /* UTF-8 handling routines */
584 
585 
592 size_t Utf8Decode(WChar *c, const char *s)
593 {
594  assert(c != nullptr);
595 
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;
605  }
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;
611  }
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;
617  }
618  }
619 
620  /* Debug(misc, 1, "[utf8] invalid UTF-8 sequence"); */
621  *c = '?';
622  return 1;
623 }
624 
625 
633 template <class T>
634 inline size_t Utf8Encode(T buf, WChar c)
635 {
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;
654  }
655 
656  /* Debug(misc, 1, "[utf8] can't UTF-8 encode value 0x{:X}", c); */
657  *buf = '?';
658  return 1;
659 }
660 
661 size_t Utf8Encode(char *buf, WChar c)
662 {
663  return Utf8Encode<char *>(buf, c);
664 }
665 
666 size_t Utf8Encode(std::ostreambuf_iterator<char> &buf, WChar c)
667 {
668  return Utf8Encode<std::ostreambuf_iterator<char> &>(buf, c);
669 }
670 
678 size_t Utf8TrimString(char *s, size_t maxlen)
679 {
680  size_t length = 0;
681 
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;
686 
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;
692  }
693 
694  *s = '\0';
695  return length;
696 }
697 
698 #ifdef DEFINE_STRCASESTR
699 char *strcasestr(const char *haystack, const char *needle)
700 {
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);
705 
706  haystack++;
707  hay_len--;
708  }
709 
710  return nullptr;
711 }
712 #endif /* DEFINE_STRCASESTR */
713 
722 static const char *SkipGarbage(const char *str)
723 {
724  while (*str != '\0' && (*str < '0' || IsInsideMM(*str, ';', '@' + 1) || IsInsideMM(*str, '[', '`' + 1) || IsInsideMM(*str, '{', '~' + 1))) str++;
725  return str;
726 }
727 
736 int strnatcmp(const char *s1, const char *s2, bool ignore_garbage_at_front)
737 {
738  if (ignore_garbage_at_front) {
739  s1 = SkipGarbage(s1);
740  s2 = SkipGarbage(s2);
741  }
742 
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;
748  }
749 #endif /* WITH_ICU_I18N */
750 
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
755 
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
760 
761  /* Do a normal comparison if ICU is missing or if we cannot create a collator. */
762  return strcasecmp(s1, s2);
763 }
764 
765 #ifdef WITH_UNISCRIBE
766 
768 {
769  return new UniscribeStringIterator();
770 }
771 
772 #elif defined(WITH_ICU_I18N)
773 
774 #include <unicode/utext.h>
775 #include <unicode/brkiter.h>
776 
779 {
780  icu::BreakIterator *char_itr;
781  icu::BreakIterator *word_itr;
782 
783  std::vector<UChar> utf16_str;
784  std::vector<size_t> utf16_to_utf8;
785 
786 public:
787  IcuStringIterator() : char_itr(nullptr), word_itr(nullptr)
788  {
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);
792 
793  this->utf16_str.push_back('\0');
794  this->utf16_to_utf8.push_back(0);
795  }
796 
797  ~IcuStringIterator() override
798  {
799  delete this->char_itr;
800  delete this->word_itr;
801  }
802 
803  void SetString(const char *s) override
804  {
805  const char *string_base = s;
806 
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();
813 
814  while (*s != '\0') {
815  size_t idx = s - string_base;
816 
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);
825  }
826  this->utf16_to_utf8.push_back(idx);
827  }
828  this->utf16_str.push_back('\0');
829  this->utf16_to_utf8.push_back(s - string_base);
830 
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();
838  }
839 
840  size_t SetCurPosition(size_t pos) override
841  {
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;
848  }
849  }
850 
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()];
856  }
857 
858  size_t Next(IterType what) override
859  {
860  int32_t pos;
861  switch (what) {
862  case ITER_CHARACTER:
863  pos = this->char_itr->next();
864  break;
865 
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;
878  }
879 
880  this->char_itr->isBoundary(pos);
881  break;
882 
883  default:
884  NOT_REACHED();
885  }
886 
887  return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
888  }
889 
890  size_t Prev(IterType what) override
891  {
892  int32_t pos;
893  switch (what) {
894  case ITER_CHARACTER:
895  pos = this->char_itr->previous();
896  break;
897 
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;
910  }
911 
912  this->char_itr->isBoundary(pos);
913  break;
914 
915  default:
916  NOT_REACHED();
917  }
918 
919  return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
920  }
921 };
922 
924 {
925  return new IcuStringIterator();
926 }
927 
928 #else
929 
931 class DefaultStringIterator : public StringIterator
932 {
933  const char *string;
934  size_t len;
935  size_t cur_pos;
936 
937 public:
938  DefaultStringIterator() : string(nullptr), len(0), cur_pos(0)
939  {
940  }
941 
942  virtual void SetString(const char *s)
943  {
944  this->string = s;
945  this->len = strlen(s);
946  this->cur_pos = 0;
947  }
948 
949  virtual size_t SetCurPosition(size_t pos)
950  {
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;
955  }
956 
957  virtual size_t Next(IterType what)
958  {
959  assert(this->string != nullptr);
960 
961  /* Already at the end? */
962  if (this->cur_pos >= this->len) return END;
963 
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;
969  }
970 
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);
978  }
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);
983  }
984 
985  return this->cur_pos;
986  }
987 
988  default:
989  NOT_REACHED();
990  }
991 
992  return END;
993  }
994 
995  virtual size_t Prev(IterType what)
996  {
997  assert(this->string != nullptr);
998 
999  /* Already at the beginning? */
1000  if (this->cur_pos == 0) return END;
1001 
1002  switch (what) {
1003  case ITER_CHARACTER:
1004  return this->cur_pos = Utf8PrevChar(this->string + this->cur_pos) - this->string;
1005 
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);
1018  }
1019  /* Move caret back to the beginning of the word. */
1020  if (IsWhitespace(c)) Utf8Consume(&s);
1021 
1022  return this->cur_pos = s - this->string;
1023  }
1024 
1025  default:
1026  NOT_REACHED();
1027  }
1028 
1029  return END;
1030  }
1031 };
1032 
1033 #if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
1034 /* static */ StringIterator *StringIterator::Create()
1035 {
1036  StringIterator *i = OSXStringIterator::Create();
1037  if (i != nullptr) return i;
1038 
1039  return new DefaultStringIterator();
1040 }
1041 #else
1042 /* static */ StringIterator *StringIterator::Create()
1043 {
1044  return new DefaultStringIterator();
1045 }
1046 #endif /* defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN) */
1047 
1048 #endif
IsInsideMM
static constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:204
StringIterator::Prev
virtual size_t Prev(IterType what=ITER_CHARACTER)=0
Move the cursor back by one iteration unit.
IcuStringIterator::utf16_to_utf8
std::vector< size_t > utf16_to_utf8
Mapping from UTF-16 code point position to index in the UTF-8 source string.
Definition: string.cpp:784
WChar
char32_t WChar
Type for wide characters, i.e.
Definition: string_type.h:35
SVS_ALLOW_NEWLINE
@ SVS_ALLOW_NEWLINE
Allow newlines.
Definition: string_type.h:51
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
StringIterator::IterType
IterType
Type of the iterator.
Definition: string_base.h:17
strtolower
bool strtolower(char *str)
Convert a given ASCII string to lowercase.
Definition: string.cpp:465
win32.h
StrRightTrimInPlace
static void StrRightTrimInPlace(std::string &str)
Trim the spaces from the end of given string in place, i.e.
Definition: string.cpp:360
StringIterator::END
static const size_t END
Sentinel to indicate end-of-iteration.
Definition: string_base.h:23
math_func.hpp
str_fix_scc_encoded
void str_fix_scc_encoded(char *str, const char *last)
Scan the string for old values of SCC_ENCODED and fix it to it's new, static value.
Definition: string.cpp:187
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
IcuStringIterator::word_itr
icu::BreakIterator * word_itr
ICU iterator for words.
Definition: string.cpp:781
_current_collator
std::unique_ptr< icu::Collator > _current_collator
Collator for the language currently in use.
Definition: strings.cpp:51
Utf8Encode
size_t Utf8Encode(T buf, WChar c)
Encode a unicode character and place it in the buffer.
Definition: string.cpp:634
StringIterator::Next
virtual size_t Next(IterType what=ITER_CHARACTER)=0
Advance the cursor by one iteration unit.
CS_ALPHA
@ CS_ALPHA
Only alphabetic values.
Definition: string_type.h:30
UniscribeStringIterator
String iterator using Uniscribe as a backend.
Definition: string_uniscribe.h:67
Utf16DecodeChar
static WChar Utf16DecodeChar(const uint16 *c)
Decode an UTF-16 character.
Definition: string_func.h:213
StringIterator::SetString
virtual void SetString(const char *s)=0
Set a new iteration string.
IcuStringIterator::char_itr
icu::BreakIterator * char_itr
ICU iterator for characters.
Definition: string.cpp:780
StringIterator::ITER_CHARACTER
@ ITER_CHARACTER
Iterate over characters (or more exactly grapheme clusters).
Definition: string_base.h:18
control_codes.h
IcuStringIterator::Next
size_t Next(IterType what) override
Advance the cursor by one iteration unit.
Definition: string.cpp:858
string_osx.h
gfx_func.h
FormatArrayAsHex
std::string FormatArrayAsHex(span< const byte > data)
Format a byte array into a continuous hex string.
Definition: string.cpp:169
Utf8StringLength
size_t Utf8StringLength(const char *s)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
Definition: string.cpp:435
StrValid
bool StrValid(const char *str, const char *last)
Checks whether the given string is valid, i.e.
Definition: string.cpp:318
StringIterator::Create
static StringIterator * Create()
Create a new iterator instance.
Definition: string.cpp:923
SVS_ALLOW_CONTROL_CODE
@ SVS_ALLOW_CONTROL_CODE
Allow the special control codes.
Definition: string_type.h:52
StringIterator
Class for iterating over different kind of parts of a string.
Definition: string_base.h:14
IcuStringIterator::SetCurPosition
size_t SetCurPosition(size_t pos) override
Change the current string cursor.
Definition: string.cpp:840
span< const byte >
StringIterator::SetCurPosition
virtual size_t SetCurPosition(size_t pos)=0
Change the current string cursor.
StrMakeValidInPlace
void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:273
StrTrimInPlace
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
Definition: string.cpp:373
str_strip_colours
void str_strip_colours(char *str)
Scans the string for colour codes and strips them.
Definition: string.cpp:407
StrStartsWith
bool StrStartsWith(const std::string_view str, const std::string_view prefix)
Check whether the given string starts with the given prefix.
Definition: string.cpp:385
_current_language
const LanguageMetadata * _current_language
The currently loaded language.
Definition: strings.cpp:46
safeguards.h
IcuStringIterator::utf16_str
std::vector< UChar > utf16_str
UTF-16 copy of the string.
Definition: string.cpp:783
IsValidChar
bool IsValidChar(WChar key, CharSetFilter afilter)
Only allow certain keys.
Definition: string.cpp:494
ttd_strnlen
static size_t ttd_strnlen(const char *str, size_t maxlen)
Get the length of a string, within a limited buffer.
Definition: string_func.h:79
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
vseprintf
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:62
StringIterator::ITER_WORD
@ ITER_WORD
Iterate over words.
Definition: string_base.h:19
language.h
stdafx.h
CS_ALPHANUMERAL
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition: string_type.h:27
LanguagePackHeader::isocode
char isocode[16]
the ISO code for the language (not country code)
Definition: language.h:31
StringValidationSettings
StringValidationSettings
Settings for the string validation.
Definition: string_type.h:48
StrEndsWith
bool StrEndsWith(const std::string_view str, const std::string_view suffix)
Check whether the given string ends with the given suffix.
Definition: string.cpp:398
Utf8Decode
size_t Utf8Decode(WChar *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:592
string_func.h
StrMakeValid
std::string StrMakeValid(const std::string &str, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:299
str_fmt
char *CDECL str_fmt(const char *str,...)
Format, "printf", into a newly allocated string.
Definition: string.cpp:151
alloc_func.hpp
IcuStringIterator::SetString
void SetString(const char *s) override
Set a new iteration string.
Definition: string.cpp:803
StrLeftTrimInPlace
static void StrLeftTrimInPlace(std::string &str)
Trim the spaces from the begin of given string in place, i.e.
Definition: string.cpp:348
IcuStringIterator
String iterator using ICU as a backend.
Definition: string.cpp:778
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:553
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:133
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
Utf8TrimString
size_t Utf8TrimString(char *s, size_t maxlen)
Properly terminate an UTF8 string to some maximum length.
Definition: string.cpp:678
CS_NUMERAL_SPACE
@ CS_NUMERAL_SPACE
Only numbers and spaces.
Definition: string_type.h:29
SkipGarbage
static const char * SkipGarbage(const char *str)
Skip some of the 'garbage' in the string that we don't want to use to sort on.
Definition: string.cpp:722
IsWhitespace
static bool IsWhitespace(WChar c)
Check whether UNICODE character is whitespace or not, i.e.
Definition: string_func.h:260
strnatcmp
int strnatcmp(const char *s1, const char *s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
Definition: string.cpp:736
md5sumToString
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
Definition: string.cpp:571
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:113
CS_HEXADECIMAL
@ CS_HEXADECIMAL
Only hexadecimal characters.
Definition: string_type.h:31
strecat
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: string.cpp:85
MacOSStringCompare
int MacOSStringCompare(const char *s1, const char *s2)
Compares two strings using case insensitive natural sort.
Definition: string_osx.cpp:323
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
SVS_REPLACE_WITH_QUESTION_MARK
@ SVS_REPLACE_WITH_QUESTION_MARK
Replace the unknown/bad bits with question marks.
Definition: string_type.h:50
CS_NUMERAL
@ CS_NUMERAL
Only numeric ones.
Definition: string_type.h:28
CharSetFilter
CharSetFilter
Valid filter types for IsValidChar.
Definition: string_type.h:26
Utf8PrevChar
static char * Utf8PrevChar(char *s)
Retrieve the previous UNICODE character in an UTF-8 encoded string.
Definition: string_func.h:160
debug.h
string_uniscribe.h
Utf8EncodedCharLen
static int8 Utf8EncodedCharLen(char c)
Return the length of an UTF-8 encoded value based on a single char.
Definition: string_func.h:135
IcuStringIterator::Prev
size_t Prev(IterType what) override
Move the cursor back by one iteration unit.
Definition: string.cpp:890