# string.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "debug.h"
    00014 #include "core/alloc_func.hpp"
    00015 #include "core/math_func.hpp"
    00016 #include "string_func.h"
    00017
    00018 #include "table/control_codes.h"
    00019
    00020 #include <stdarg.h>
    00021 #include <ctype.h> /* required for tolower() */
    00022
    00023 #ifdef _MSC_VER
    00024 #include <errno.h> // required by vsnprintf implementation for MSVC
    00025 #endif
    00026
    00027 #ifdef WITH_ICU
    00028 /* Required by strnatcmp. */
    00029 #include <unicode/ustring.h>
    00030 #include "language.h"
    00031 #include "gfx_func.h"
    00032 #endif /* WITH_ICU */
    00033
    00044 static int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
    00045 {
    00046   ptrdiff_t diff = last - str;
    00047   if (diff < 0) return 0;
    00048   return min((int)diff, vsnprintf(str, diff + 1, format, ap));
    00049 }
    00050
    00065 void ttd_strlcat(char *dst, const char *src, size_t size)
    00066 {
    00067   assert(size > 0);
    00068   while (size > 0 && *dst != '\0') {
    00069     size--;
    00070     dst++;
    00071   }
    00072
    00073   ttd_strlcpy(dst, src, size);
    00074 }
    00075
    00076
    00091 void ttd_strlcpy(char *dst, const char *src, size_t size)
    00092 {
    00093   assert(size > 0);
    00094   while (--size > 0 && *src != '\0') {
    00095     *dst++ = *src++;
    00096   }
    00097   *dst = '\0';
    00098 }
    00099
    00100
    00117 char *strecat(char *dst, const char *src, const char *last)
    00118 {
    00119   assert(dst <= last);
    00120   while (*dst != '\0') {
    00121     if (dst == last) return dst;
    00122     dst++;
    00123   }
    00124
    00125   return strecpy(dst, src, last);
    00126 }
    00127
    00128
    00145 char *strecpy(char *dst, const char *src, const char *last)
    00146 {
    00147   assert(dst <= last);
    00148   while (dst != last && *src != '\0') {
    00149     *dst++ = *src++;
    00150   }
    00151   *dst = '\0';
    00152
    00153   if (dst == last && *src != '\0') {
    00154 #ifdef STRGEN
    00155     error("String too long for destination buffer");
    00156 #else /* STRGEN */
    00157     DEBUG(misc, 0, "String too long for destination buffer");
    00158 #endif /* STRGEN */
    00159   }
    00160   return dst;
    00161 }
    00162
    00163
    00164 char *CDECL str_fmt(const char *str, ...)
    00165 {
    00166   char buf[4096];
    00167   va_list va;
    00168
    00169   va_start(va, str);
    00170   int len = vseprintf(buf, lastof(buf), str, va);
    00171   va_end(va);
    00172   char *p = MallocT<char>(len + 1);
    00173   memcpy(p, buf, len + 1);
    00174   return p;
    00175 }
    00176
    00177
    00186 void str_validate(char *str, const char *last, bool allow_newlines, bool ignore)
    00187 {
    00188   /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
    00189
    00190   char *dst = str;
    00191   while (str <= last && *str != '\0') {
    00192     size_t len = Utf8EncodedCharLen(*str);
    00193     /* If the character is unknown, i.e. encoded length is 0
    00194      * we assume worst case for the length check.
    00195      * The length check is needed to prevent Utf8Decode to read
    00196      * over the terminating '\0' if that happens to be placed
    00197      * within the encoding of an UTF8 character. */
    00198     if ((len == 0 && str + 4 > last) || str + len > last) break;
    00199
    00200     WChar c;
    00201     len = Utf8Decode(&c, str);
    00202     /* It's possible to encode the string termination character
    00203      * into a multiple bytes. This prevents those termination
    00204      * characters to be skipped */
    00205     if (c == '\0') break;
    00206
    00207     if (IsPrintable(c) && (c < SCC_SPRITE_START || c > SCC_SPRITE_END)) {
    00208       /* Copy the character back. Even if dst is current the same as str
    00209        * (i.e. no characters have been changed) this is quicker than
    00210        * moving the pointers ahead by len */
    00211       do {
    00212         *dst++ = *str++;
    00213       } while (--len != 0);
    00214     } else if (allow_newlines && c == '\n') {
    00215       *dst++ = *str++;
    00216     } else {
    00217       if (allow_newlines && c == '\r' && str[1] == '\n') {
    00218         str += len;
    00219         continue;
    00220       }
    00221       /* Replace the undesirable character with a question mark */
    00222       str += len;
    00223       if (!ignore) *dst++ = '?';
    00224
    00225       /* In case of these two special cases assume that they really
    00226        * mean SETX/SETXY and also "eat" the paramater. If this was
    00227        * not the case the string was broken to begin with and this
    00228        * would not break much more. */
    00229       if (c == SCC_SETX) {
    00230         str++;
    00231       } else if (c == SCC_SETXY) {
    00232         str += 2;
    00233       }
    00234     }
    00235   }
    00236
    00237   *dst = '\0';
    00238 }
    00239
    00247 bool StrValid(const char *str, const char *last)
    00248 {
    00249   /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
    00250
    00251   while (str <= last && *str != '\0') {
    00252     size_t len = Utf8EncodedCharLen(*str);
    00253     /* Encoded length is 0 if the character isn't known.
    00254      * The length check is needed to prevent Utf8Decode to read
    00255      * over the terminating '\0' if that happens to be placed
    00256      * within the encoding of an UTF8 character. */
    00257     if (len == 0 || str + len > last) return false;
    00258
    00259     WChar c;
    00260     len = Utf8Decode(&c, str);
    00261     if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
    00262       return false;
    00263     }
    00264
    00265     str += len;
    00266   }
    00267
    00268   return *str == '\0';
    00269 }
    00270
    00272 void str_strip_colours(char *str)
    00273 {
    00274   char *dst = str;
    00275   WChar c;
    00276   size_t len;
    00277
    00278   for (len = Utf8Decode(&c, str); c != '\0'; len = Utf8Decode(&c, str)) {
    00279     if (c < SCC_BLUE || c > SCC_BLACK) {
    00280       /* Copy the character back. Even if dst is current the same as str
    00281        * (i.e. no characters have been changed) this is quicker than
    00282        * moving the pointers ahead by len */
    00283       do {
    00284         *dst++ = *str++;
    00285       } while (--len != 0);
    00286     } else {
    00287       /* Just skip (strip) the colour codes */
    00288       str += len;
    00289     }
    00290   }
    00291   *dst = '\0';
    00292 }
    00293
    00300 size_t Utf8StringLength(const char *s)
    00301 {
    00302   size_t len = 0;
    00303   const char *t = s;
    00304   while (Utf8Consume(&t) != 0) len++;
    00305   return len;
    00306 }
    00307
    00308
    00319 void strtolower(char *str)
    00320 {
    00321   for (; *str != '\0'; str++) *str = tolower(*str);
    00322 }
    00323
    00331 bool IsValidChar(WChar key, CharSetFilter afilter)
    00332 {
    00333   switch (afilter) {
    00334     case CS_ALPHANUMERAL:  return IsPrintable(key);
    00335     case CS_NUMERAL:       return (key >= '0' && key <= '9');
    00336     case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' ';
    00337     case CS_ALPHA:         return IsPrintable(key) && !(key >= '0' && key <= '9');
    00338     case CS_HEXADECIMAL:   return (key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (key >= 'A' && key <= 'F');
    00339   }
    00340
    00341   return false;
    00342 }
    00343
    00344 #ifdef WIN32
    00345 /* Since version 3.14, MinGW Runtime has snprintf() and vsnprintf() conform to C99 but it's not the case for older versions */
    00346 #if (__MINGW32_MAJOR_VERSION < 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION < 14))
    00347 int CDECL snprintf(char *str, size_t size, const char *format, ...)
    00348 {
    00349   va_list ap;
    00350   int ret;
    00351
    00352   va_start(ap, format);
    00353   ret = vsnprintf(str, size, format, ap);
    00354   va_end(ap);
    00355   return ret;
    00356 }
    00357 #endif /* MinGW Runtime < 3.14 */
    00358
    00359 #ifdef _MSC_VER
    00360
    00367 int CDECL vsnprintf(char *str, size_t size, const char *format, va_list ap)
    00368 {
    00369   if (size == 0) return 0;
    00370
    00371   errno = 0;
    00372   int ret = _vsnprintf(str, size, format, ap);
    00373
    00374   if (ret < 0) {
    00375     if (errno != ERANGE) {
    00376       /* There's a formatting error, better get that looked
    00377        * at properly instead of ignoring it. */
    00378       NOT_REACHED();
    00379     }
    00380   } else if ((size_t)ret < size) {
    00381     /* The buffer is big enough for the number of
    00382      * characers stored (excluding null), i.e.
    00383      * the string has been null-terminated. */
    00384     return ret;
    00385   }
    00386
    00387   /* The buffer is too small for _vsnprintf to write the
    00388    * null-terminator at its end and return size. */
    00389   str[size - 1] = '\0';
    00390   return (int)size;
    00391 }
    00392 #endif /* _MSC_VER */
    00393
    00394 #endif /* WIN32 */
    00395
    00405 int CDECL seprintf(char *str, const char *last, const char *format, ...)
    00406 {
    00407   va_list ap;
    00408
    00409   va_start(ap, format);
    00410   int ret = vseprintf(str, last, format, ap);
    00411   va_end(ap);
    00412   return ret;
    00413 }
    00414
    00415
    00423 char *md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
    00424 {
    00425   char *p = buf;
    00426
    00427   for (uint i = 0; i < 16; i++) {
    00428     p += seprintf(p, last, "%02X", md5sum[i]);
    00429   }
    00430
    00431   return p;
    00432 }
    00433
    00434
    00435 /* UTF-8 handling routines */
    00436
    00437
    00444 size_t Utf8Decode(WChar *c, const char *s)
    00445 {
    00446   assert(c != NULL);
    00447
    00448   if (!HasBit(s[0], 7)) {
    00449     /* Single byte character: 0xxxxxxx */
    00450     *c = s[0];
    00451     return 1;
    00452   } else if (GB(s[0], 5, 3) == 6) {
    00453     if (IsUtf8Part(s[1])) {
    00454       /* Double byte character: 110xxxxx 10xxxxxx */
    00455       *c = GB(s[0], 0, 5) << 6 | GB(s[1], 0, 6);
    00456       if (*c >= 0x80) return 2;
    00457     }
    00458   } else if (GB(s[0], 4, 4) == 14) {
    00459     if (IsUtf8Part(s[1]) && IsUtf8Part(s[2])) {
    00460       /* Triple byte character: 1110xxxx 10xxxxxx 10xxxxxx */
    00461       *c = GB(s[0], 0, 4) << 12 | GB(s[1], 0, 6) << 6 | GB(s[2], 0, 6);
    00462       if (*c >= 0x800) return 3;
    00463     }
    00464   } else if (GB(s[0], 3, 5) == 30) {
    00465     if (IsUtf8Part(s[1]) && IsUtf8Part(s[2]) && IsUtf8Part(s[3])) {
    00466       /* 4 byte character: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
    00467       *c = GB(s[0], 0, 3) << 18 | GB(s[1], 0, 6) << 12 | GB(s[2], 0, 6) << 6 | GB(s[3], 0, 6);
    00468       if (*c >= 0x10000 && *c <= 0x10FFFF) return 4;
    00469     }
    00470   }
    00471
    00472   /* DEBUG(misc, 1, "[utf8] invalid UTF-8 sequence"); */
    00473   *c = '?';
    00474   return 1;
    00475 }
    00476
    00477
    00484 size_t Utf8Encode(char *buf, WChar c)
    00485 {
    00486   if (c < 0x80) {
    00487     *buf = c;
    00488     return 1;
    00489   } else if (c < 0x800) {
    00490     *buf++ = 0xC0 + GB(c,  6, 5);
    00491     *buf   = 0x80 + GB(c,  0, 6);
    00492     return 2;
    00493   } else if (c < 0x10000) {
    00494     *buf++ = 0xE0 + GB(c, 12, 4);
    00495     *buf++ = 0x80 + GB(c,  6, 6);
    00496     *buf   = 0x80 + GB(c,  0, 6);
    00497     return 3;
    00498   } else if (c < 0x110000) {
    00499     *buf++ = 0xF0 + GB(c, 18, 3);
    00500     *buf++ = 0x80 + GB(c, 12, 6);
    00501     *buf++ = 0x80 + GB(c,  6, 6);
    00502     *buf   = 0x80 + GB(c,  0, 6);
    00503     return 4;
    00504   }
    00505
    00506   /* DEBUG(misc, 1, "[utf8] can't UTF-8 encode value 0x%X", c); */
    00507   *buf = '?';
    00508   return 1;
    00509 }
    00510
    00518 size_t Utf8TrimString(char *s, size_t maxlen)
    00519 {
    00520   size_t length = 0;
    00521
    00522   for (const char *ptr = strchr(s, '\0'); *s != '\0';) {
    00523     size_t len = Utf8EncodedCharLen(*s);
    00524     /* Silently ignore invalid UTF8 sequences, our only concern trimming */
    00525     if (len == 0) len = 1;
    00526
    00527     /* Take care when a hard cutoff was made for the string and
    00528      * the last UTF8 sequence is invalid */
    00529     if (length + len >= maxlen || (s + len > ptr)) break;
    00530     s += len;
    00531     length += len;
    00532   }
    00533
    00534   *s = '\0';
    00535   return length;
    00536 }
    00537
    00538 #ifdef DEFINE_STRNDUP
    00539 #include "core/math_func.hpp"
    00540 char *strndup(const char *s, size_t len)
    00541 {
    00542   len = min(strlen(s), len);
    00543   char *tmp = CallocT<char>(len + 1);
    00544   memcpy(tmp, s, len);
    00545   return tmp;
    00546 }
    00547 #endif /* DEFINE_STRNDUP */
    00548
    00549 #ifdef DEFINE_STRCASESTR
    00550 char *strcasestr(const char *haystack, const char *needle)
    00551 {
    00552   size_t hay_len = strlen(haystack);
    00553   size_t needle_len = strlen(needle);
    00554   while (hay_len >= needle_len) {
    00555     if (strncasecmp(haystack, needle, needle_len) == 0) return const_cast<char *>(haystack);
    00556
    00557     haystack++;
    00558     hay_len--;
    00559   }
    00560
    00561   return NULL;
    00562 }
    00563 #endif /* DEFINE_STRCASESTR */
    00564
    00572 int strnatcmp(const char *s1, const char *s2)
    00573 {
    00574 #ifdef WITH_ICU
    00575   if (_current_collator != NULL) {
    00576     UErrorCode status = U_ZERO_ERROR;
    00577     int result;
    00578
    00579     /* We want to use the new faster method for ICU 4.2 and higher. */
    00580 #if U_ICU_VERSION_MAJOR_NUM > 4 || (U_ICU_VERSION_MAJOR_NUM == 4 && U_ICU_VERSION_MINOR_NUM >= 2)
    00581     /* The StringPiece parameter gets implicitly constructed from the char *. */
    00582     result = _current_collator->compareUTF8(s1, s2, status);
    00583 #else /* The following for 4.0 and lower. */
    00584     UChar buffer1[DRAW_STRING_BUFFER];
    00585     u_strFromUTF8Lenient(buffer1, lengthof(buffer1), NULL, s1, -1, &status);
    00586     UChar buffer2[DRAW_STRING_BUFFER];
    00587     u_strFromUTF8Lenient(buffer2, lengthof(buffer2), NULL, s2, -1, &status);
    00588
    00589     result = _current_collator->compare(buffer1, buffer2, status);
    00590 #endif /* ICU version check. */
    00591     if (U_SUCCESS(status)) return result;
    00592   }
    00593
    00594 #endif /* WITH_ICU */
    00595
    00596   /* Do a normal comparison if ICU is missing or if we cannot create a collator. */
    00597   return strcasecmp(s1, s2);
    00598 }