string.cpp

Go to the documentation of this file.
00001 /* $Id: string.cpp 23706 2012-01-01 17:36:19Z smatz $ */
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 #if defined(STRGEN) || defined(SETTINGSGEN)
00155     error("String too long for destination buffer");
00156 #else /* STRGEN || SETTINGSGEN */
00157     DEBUG(misc, 0, "String too long for destination buffer");
00158 #endif /* STRGEN || SETTINGSGEN */
00159   }
00160   return dst;
00161 }
00162 
00168 char *CDECL str_fmt(const char *str, ...)
00169 {
00170   char buf[4096];
00171   va_list va;
00172 
00173   va_start(va, str);
00174   int len = vseprintf(buf, lastof(buf), str, va);
00175   va_end(va);
00176   char *p = MallocT<char>(len + 1);
00177   memcpy(p, buf, len + 1);
00178   return p;
00179 }
00180 
00181 
00189 void str_validate(char *str, const char *last, StringValidationSettings settings)
00190 {
00191   /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
00192 
00193   char *dst = str;
00194   while (str <= last && *str != '\0') {
00195     size_t len = Utf8EncodedCharLen(*str);
00196     /* If the character is unknown, i.e. encoded length is 0
00197      * we assume worst case for the length check.
00198      * The length check is needed to prevent Utf8Decode to read
00199      * over the terminating '\0' if that happens to be placed
00200      * within the encoding of an UTF8 character. */
00201     if ((len == 0 && str + 4 > last) || str + len > last) break;
00202 
00203     WChar c;
00204     len = Utf8Decode(&c, str);
00205     /* It's possible to encode the string termination character
00206      * into a multiple bytes. This prevents those termination
00207      * characters to be skipped */
00208     if (c == '\0') break;
00209 
00210     if ((IsPrintable(c) && (c < SCC_SPRITE_START || c > SCC_SPRITE_END)) || ((settings & SVS_ALLOW_CONTROL_CODE) != 0 && IsInsideMM(c, SCC_CONTROL_START, SCC_CONTROL_END))) {
00211       /* Copy the character back. Even if dst is current the same as str
00212        * (i.e. no characters have been changed) this is quicker than
00213        * moving the pointers ahead by len */
00214       do {
00215         *dst++ = *str++;
00216       } while (--len != 0);
00217     } else if ((settings & SVS_ALLOW_NEWLINE) != 0  && c == '\n') {
00218       *dst++ = *str++;
00219     } else {
00220       if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\r' && str[1] == '\n') {
00221         str += len;
00222         continue;
00223       }
00224       /* Replace the undesirable character with a question mark */
00225       str += len;
00226       if ((settings & SVS_REPLACE_WITH_QUESTION_MARK) != 0) *dst++ = '?';
00227 
00228       /* In case of these two special cases assume that they really
00229        * mean SETX/SETXY and also "eat" the paramater. If this was
00230        * not the case the string was broken to begin with and this
00231        * would not break much more. */
00232       if (c == SCC_SETX) {
00233         str++;
00234       } else if (c == SCC_SETXY) {
00235         str += 2;
00236       }
00237     }
00238   }
00239 
00240   *dst = '\0';
00241 }
00242 
00250 bool StrValid(const char *str, const char *last)
00251 {
00252   /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
00253 
00254   while (str <= last && *str != '\0') {
00255     size_t len = Utf8EncodedCharLen(*str);
00256     /* Encoded length is 0 if the character isn't known.
00257      * The length check is needed to prevent Utf8Decode to read
00258      * over the terminating '\0' if that happens to be placed
00259      * within the encoding of an UTF8 character. */
00260     if (len == 0 || str + len > last) return false;
00261 
00262     WChar c;
00263     len = Utf8Decode(&c, str);
00264     if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
00265       return false;
00266     }
00267 
00268     str += len;
00269   }
00270 
00271   return *str == '\0';
00272 }
00273 
00275 void str_strip_colours(char *str)
00276 {
00277   char *dst = str;
00278   WChar c;
00279   size_t len;
00280 
00281   for (len = Utf8Decode(&c, str); c != '\0'; len = Utf8Decode(&c, str)) {
00282     if (c < SCC_BLUE || c > SCC_BLACK) {
00283       /* Copy the character back. Even if dst is current the same as str
00284        * (i.e. no characters have been changed) this is quicker than
00285        * moving the pointers ahead by len */
00286       do {
00287         *dst++ = *str++;
00288       } while (--len != 0);
00289     } else {
00290       /* Just skip (strip) the colour codes */
00291       str += len;
00292     }
00293   }
00294   *dst = '\0';
00295 }
00296 
00303 size_t Utf8StringLength(const char *s)
00304 {
00305   size_t len = 0;
00306   const char *t = s;
00307   while (Utf8Consume(&t) != 0) len++;
00308   return len;
00309 }
00310 
00311 
00323 bool strtolower(char *str)
00324 {
00325   bool changed = false;
00326   for (; *str != '\0'; str++) {
00327     char new_str = tolower(*str);
00328     changed |= new_str != *str;
00329     *str = new_str;
00330   }
00331   return changed;
00332 }
00333 
00341 bool IsValidChar(WChar key, CharSetFilter afilter)
00342 {
00343   switch (afilter) {
00344     case CS_ALPHANUMERAL:  return IsPrintable(key);
00345     case CS_NUMERAL:       return (key >= '0' && key <= '9');
00346     case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' ';
00347     case CS_ALPHA:         return IsPrintable(key) && !(key >= '0' && key <= '9');
00348     case CS_HEXADECIMAL:   return (key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (key >= 'A' && key <= 'F');
00349   }
00350 
00351   return false;
00352 }
00353 
00354 #ifdef WIN32
00355 /* Since version 3.14, MinGW Runtime has snprintf() and vsnprintf() conform to C99 but it's not the case for older versions */
00356 #if (__MINGW32_MAJOR_VERSION < 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION < 14))
00357 int CDECL snprintf(char *str, size_t size, const char *format, ...)
00358 {
00359   va_list ap;
00360   int ret;
00361 
00362   va_start(ap, format);
00363   ret = vsnprintf(str, size, format, ap);
00364   va_end(ap);
00365   return ret;
00366 }
00367 #endif /* MinGW Runtime < 3.14 */
00368 
00369 #ifdef _MSC_VER
00370 
00377 int CDECL vsnprintf(char *str, size_t size, const char *format, va_list ap)
00378 {
00379   if (size == 0) return 0;
00380 
00381   errno = 0;
00382   int ret = _vsnprintf(str, size, format, ap);
00383 
00384   if (ret < 0) {
00385     if (errno != ERANGE) {
00386       /* There's a formatting error, better get that looked
00387        * at properly instead of ignoring it. */
00388       NOT_REACHED();
00389     }
00390   } else if ((size_t)ret < size) {
00391     /* The buffer is big enough for the number of
00392      * characers stored (excluding null), i.e.
00393      * the string has been null-terminated. */
00394     return ret;
00395   }
00396 
00397   /* The buffer is too small for _vsnprintf to write the
00398    * null-terminator at its end and return size. */
00399   str[size - 1] = '\0';
00400   return (int)size;
00401 }
00402 #endif /* _MSC_VER */
00403 
00404 #endif /* WIN32 */
00405 
00415 int CDECL seprintf(char *str, const char *last, const char *format, ...)
00416 {
00417   va_list ap;
00418 
00419   va_start(ap, format);
00420   int ret = vseprintf(str, last, format, ap);
00421   va_end(ap);
00422   return ret;
00423 }
00424 
00425 
00433 char *md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
00434 {
00435   char *p = buf;
00436 
00437   for (uint i = 0; i < 16; i++) {
00438     p += seprintf(p, last, "%02X", md5sum[i]);
00439   }
00440 
00441   return p;
00442 }
00443 
00444 
00445 /* UTF-8 handling routines */
00446 
00447 
00454 size_t Utf8Decode(WChar *c, const char *s)
00455 {
00456   assert(c != NULL);
00457 
00458   if (!HasBit(s[0], 7)) {
00459     /* Single byte character: 0xxxxxxx */
00460     *c = s[0];
00461     return 1;
00462   } else if (GB(s[0], 5, 3) == 6) {
00463     if (IsUtf8Part(s[1])) {
00464       /* Double byte character: 110xxxxx 10xxxxxx */
00465       *c = GB(s[0], 0, 5) << 6 | GB(s[1], 0, 6);
00466       if (*c >= 0x80) return 2;
00467     }
00468   } else if (GB(s[0], 4, 4) == 14) {
00469     if (IsUtf8Part(s[1]) && IsUtf8Part(s[2])) {
00470       /* Triple byte character: 1110xxxx 10xxxxxx 10xxxxxx */
00471       *c = GB(s[0], 0, 4) << 12 | GB(s[1], 0, 6) << 6 | GB(s[2], 0, 6);
00472       if (*c >= 0x800) return 3;
00473     }
00474   } else if (GB(s[0], 3, 5) == 30) {
00475     if (IsUtf8Part(s[1]) && IsUtf8Part(s[2]) && IsUtf8Part(s[3])) {
00476       /* 4 byte character: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
00477       *c = GB(s[0], 0, 3) << 18 | GB(s[1], 0, 6) << 12 | GB(s[2], 0, 6) << 6 | GB(s[3], 0, 6);
00478       if (*c >= 0x10000 && *c <= 0x10FFFF) return 4;
00479     }
00480   }
00481 
00482   /* DEBUG(misc, 1, "[utf8] invalid UTF-8 sequence"); */
00483   *c = '?';
00484   return 1;
00485 }
00486 
00487 
00494 size_t Utf8Encode(char *buf, WChar c)
00495 {
00496   if (c < 0x80) {
00497     *buf = c;
00498     return 1;
00499   } else if (c < 0x800) {
00500     *buf++ = 0xC0 + GB(c,  6, 5);
00501     *buf   = 0x80 + GB(c,  0, 6);
00502     return 2;
00503   } else if (c < 0x10000) {
00504     *buf++ = 0xE0 + GB(c, 12, 4);
00505     *buf++ = 0x80 + GB(c,  6, 6);
00506     *buf   = 0x80 + GB(c,  0, 6);
00507     return 3;
00508   } else if (c < 0x110000) {
00509     *buf++ = 0xF0 + GB(c, 18, 3);
00510     *buf++ = 0x80 + GB(c, 12, 6);
00511     *buf++ = 0x80 + GB(c,  6, 6);
00512     *buf   = 0x80 + GB(c,  0, 6);
00513     return 4;
00514   }
00515 
00516   /* DEBUG(misc, 1, "[utf8] can't UTF-8 encode value 0x%X", c); */
00517   *buf = '?';
00518   return 1;
00519 }
00520 
00528 size_t Utf8TrimString(char *s, size_t maxlen)
00529 {
00530   size_t length = 0;
00531 
00532   for (const char *ptr = strchr(s, '\0'); *s != '\0';) {
00533     size_t len = Utf8EncodedCharLen(*s);
00534     /* Silently ignore invalid UTF8 sequences, our only concern trimming */
00535     if (len == 0) len = 1;
00536 
00537     /* Take care when a hard cutoff was made for the string and
00538      * the last UTF8 sequence is invalid */
00539     if (length + len >= maxlen || (s + len > ptr)) break;
00540     s += len;
00541     length += len;
00542   }
00543 
00544   *s = '\0';
00545   return length;
00546 }
00547 
00548 #ifdef DEFINE_STRNDUP
00549 #include "core/math_func.hpp"
00550 char *strndup(const char *s, size_t len)
00551 {
00552   len = min(strlen(s), len);
00553   char *tmp = CallocT<char>(len + 1);
00554   memcpy(tmp, s, len);
00555   return tmp;
00556 }
00557 #endif /* DEFINE_STRNDUP */
00558 
00559 #ifdef DEFINE_STRCASESTR
00560 char *strcasestr(const char *haystack, const char *needle)
00561 {
00562   size_t hay_len = strlen(haystack);
00563   size_t needle_len = strlen(needle);
00564   while (hay_len >= needle_len) {
00565     if (strncasecmp(haystack, needle, needle_len) == 0) return const_cast<char *>(haystack);
00566 
00567     haystack++;
00568     hay_len--;
00569   }
00570 
00571   return NULL;
00572 }
00573 #endif /* DEFINE_STRCASESTR */
00574 
00582 int strnatcmp(const char *s1, const char *s2)
00583 {
00584 #ifdef WITH_ICU
00585   if (_current_collator != NULL) {
00586     UErrorCode status = U_ZERO_ERROR;
00587     int result;
00588 
00589     /* We want to use the new faster method for ICU 4.2 and higher. */
00590 #if U_ICU_VERSION_MAJOR_NUM > 4 || (U_ICU_VERSION_MAJOR_NUM == 4 && U_ICU_VERSION_MINOR_NUM >= 2)
00591     /* The StringPiece parameter gets implicitly constructed from the char *. */
00592     result = _current_collator->compareUTF8(s1, s2, status);
00593 #else /* The following for 4.0 and lower. */
00594     UChar buffer1[DRAW_STRING_BUFFER];
00595     u_strFromUTF8Lenient(buffer1, lengthof(buffer1), NULL, s1, -1, &status);
00596     UChar buffer2[DRAW_STRING_BUFFER];
00597     u_strFromUTF8Lenient(buffer2, lengthof(buffer2), NULL, s2, -1, &status);
00598 
00599     result = _current_collator->compare(buffer1, buffer2, status);
00600 #endif /* ICU version check. */
00601     if (U_SUCCESS(status)) return result;
00602   }
00603 
00604 #endif /* WITH_ICU */
00605 
00606   /* Do a normal comparison if ICU is missing or if we cannot create a collator. */
00607   return strcasecmp(s1, s2);
00608 }