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 #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 
00190 void str_validate(char *str, const char *last, bool allow_newlines, bool ignore)
00191 {
00192   /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
00193 
00194   char *dst = str;
00195   while (str <= last && *str != '\0') {
00196     size_t len = Utf8EncodedCharLen(*str);
00197     /* If the character is unknown, i.e. encoded length is 0
00198      * we assume worst case for the length check.
00199      * The length check is needed to prevent Utf8Decode to read
00200      * over the terminating '\0' if that happens to be placed
00201      * within the encoding of an UTF8 character. */
00202     if ((len == 0 && str + 4 > last) || str + len > last) break;
00203 
00204     WChar c;
00205     len = Utf8Decode(&c, str);
00206     /* It's possible to encode the string termination character
00207      * into a multiple bytes. This prevents those termination
00208      * characters to be skipped */
00209     if (c == '\0') break;
00210 
00211     if (IsPrintable(c) && (c < SCC_SPRITE_START || c > SCC_SPRITE_END)) {
00212       /* Copy the character back. Even if dst is current the same as str
00213        * (i.e. no characters have been changed) this is quicker than
00214        * moving the pointers ahead by len */
00215       do {
00216         *dst++ = *str++;
00217       } while (--len != 0);
00218     } else if (allow_newlines && c == '\n') {
00219       *dst++ = *str++;
00220     } else {
00221       if (allow_newlines && c == '\r' && str[1] == '\n') {
00222         str += len;
00223         continue;
00224       }
00225       /* Replace the undesirable character with a question mark */
00226       str += len;
00227       if (!ignore) *dst++ = '?';
00228 
00229       /* In case of these two special cases assume that they really
00230        * mean SETX/SETXY and also "eat" the paramater. If this was
00231        * not the case the string was broken to begin with and this
00232        * would not break much more. */
00233       if (c == SCC_SETX) {
00234         str++;
00235       } else if (c == SCC_SETXY) {
00236         str += 2;
00237       }
00238     }
00239   }
00240 
00241   *dst = '\0';
00242 }
00243 
00251 bool StrValid(const char *str, const char *last)
00252 {
00253   /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
00254 
00255   while (str <= last && *str != '\0') {
00256     size_t len = Utf8EncodedCharLen(*str);
00257     /* Encoded length is 0 if the character isn't known.
00258      * The length check is needed to prevent Utf8Decode to read
00259      * over the terminating '\0' if that happens to be placed
00260      * within the encoding of an UTF8 character. */
00261     if (len == 0 || str + len > last) return false;
00262 
00263     WChar c;
00264     len = Utf8Decode(&c, str);
00265     if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
00266       return false;
00267     }
00268 
00269     str += len;
00270   }
00271 
00272   return *str == '\0';
00273 }
00274 
00276 void str_strip_colours(char *str)
00277 {
00278   char *dst = str;
00279   WChar c;
00280   size_t len;
00281 
00282   for (len = Utf8Decode(&c, str); c != '\0'; len = Utf8Decode(&c, str)) {
00283     if (c < SCC_BLUE || c > SCC_BLACK) {
00284       /* Copy the character back. Even if dst is current the same as str
00285        * (i.e. no characters have been changed) this is quicker than
00286        * moving the pointers ahead by len */
00287       do {
00288         *dst++ = *str++;
00289       } while (--len != 0);
00290     } else {
00291       /* Just skip (strip) the colour codes */
00292       str += len;
00293     }
00294   }
00295   *dst = '\0';
00296 }
00297 
00304 size_t Utf8StringLength(const char *s)
00305 {
00306   size_t len = 0;
00307   const char *t = s;
00308   while (Utf8Consume(&t) != 0) len++;
00309   return len;
00310 }
00311 
00312 
00323 void strtolower(char *str)
00324 {
00325   for (; *str != '\0'; str++) *str = tolower(*str);
00326 }
00327 
00335 bool IsValidChar(WChar key, CharSetFilter afilter)
00336 {
00337   switch (afilter) {
00338     case CS_ALPHANUMERAL:  return IsPrintable(key);
00339     case CS_NUMERAL:       return (key >= '0' && key <= '9');
00340     case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' ';
00341     case CS_ALPHA:         return IsPrintable(key) && !(key >= '0' && key <= '9');
00342     case CS_HEXADECIMAL:   return (key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (key >= 'A' && key <= 'F');
00343   }
00344 
00345   return false;
00346 }
00347 
00348 #ifdef WIN32
00349 /* Since version 3.14, MinGW Runtime has snprintf() and vsnprintf() conform to C99 but it's not the case for older versions */
00350 #if (__MINGW32_MAJOR_VERSION < 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION < 14))
00351 int CDECL snprintf(char *str, size_t size, const char *format, ...)
00352 {
00353   va_list ap;
00354   int ret;
00355 
00356   va_start(ap, format);
00357   ret = vsnprintf(str, size, format, ap);
00358   va_end(ap);
00359   return ret;
00360 }
00361 #endif /* MinGW Runtime < 3.14 */
00362 
00363 #ifdef _MSC_VER
00364 
00371 int CDECL vsnprintf(char *str, size_t size, const char *format, va_list ap)
00372 {
00373   if (size == 0) return 0;
00374 
00375   errno = 0;
00376   int ret = _vsnprintf(str, size, format, ap);
00377 
00378   if (ret < 0) {
00379     if (errno != ERANGE) {
00380       /* There's a formatting error, better get that looked
00381        * at properly instead of ignoring it. */
00382       NOT_REACHED();
00383     }
00384   } else if ((size_t)ret < size) {
00385     /* The buffer is big enough for the number of
00386      * characers stored (excluding null), i.e.
00387      * the string has been null-terminated. */
00388     return ret;
00389   }
00390 
00391   /* The buffer is too small for _vsnprintf to write the
00392    * null-terminator at its end and return size. */
00393   str[size - 1] = '\0';
00394   return (int)size;
00395 }
00396 #endif /* _MSC_VER */
00397 
00398 #endif /* WIN32 */
00399 
00409 int CDECL seprintf(char *str, const char *last, const char *format, ...)
00410 {
00411   va_list ap;
00412 
00413   va_start(ap, format);
00414   int ret = vseprintf(str, last, format, ap);
00415   va_end(ap);
00416   return ret;
00417 }
00418 
00419 
00427 char *md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
00428 {
00429   char *p = buf;
00430 
00431   for (uint i = 0; i < 16; i++) {
00432     p += seprintf(p, last, "%02X", md5sum[i]);
00433   }
00434 
00435   return p;
00436 }
00437 
00438 
00439 /* UTF-8 handling routines */
00440 
00441 
00448 size_t Utf8Decode(WChar *c, const char *s)
00449 {
00450   assert(c != NULL);
00451 
00452   if (!HasBit(s[0], 7)) {
00453     /* Single byte character: 0xxxxxxx */
00454     *c = s[0];
00455     return 1;
00456   } else if (GB(s[0], 5, 3) == 6) {
00457     if (IsUtf8Part(s[1])) {
00458       /* Double byte character: 110xxxxx 10xxxxxx */
00459       *c = GB(s[0], 0, 5) << 6 | GB(s[1], 0, 6);
00460       if (*c >= 0x80) return 2;
00461     }
00462   } else if (GB(s[0], 4, 4) == 14) {
00463     if (IsUtf8Part(s[1]) && IsUtf8Part(s[2])) {
00464       /* Triple byte character: 1110xxxx 10xxxxxx 10xxxxxx */
00465       *c = GB(s[0], 0, 4) << 12 | GB(s[1], 0, 6) << 6 | GB(s[2], 0, 6);
00466       if (*c >= 0x800) return 3;
00467     }
00468   } else if (GB(s[0], 3, 5) == 30) {
00469     if (IsUtf8Part(s[1]) && IsUtf8Part(s[2]) && IsUtf8Part(s[3])) {
00470       /* 4 byte character: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
00471       *c = GB(s[0], 0, 3) << 18 | GB(s[1], 0, 6) << 12 | GB(s[2], 0, 6) << 6 | GB(s[3], 0, 6);
00472       if (*c >= 0x10000 && *c <= 0x10FFFF) return 4;
00473     }
00474   }
00475 
00476   /* DEBUG(misc, 1, "[utf8] invalid UTF-8 sequence"); */
00477   *c = '?';
00478   return 1;
00479 }
00480 
00481 
00488 size_t Utf8Encode(char *buf, WChar c)
00489 {
00490   if (c < 0x80) {
00491     *buf = c;
00492     return 1;
00493   } else if (c < 0x800) {
00494     *buf++ = 0xC0 + GB(c,  6, 5);
00495     *buf   = 0x80 + GB(c,  0, 6);
00496     return 2;
00497   } else if (c < 0x10000) {
00498     *buf++ = 0xE0 + GB(c, 12, 4);
00499     *buf++ = 0x80 + GB(c,  6, 6);
00500     *buf   = 0x80 + GB(c,  0, 6);
00501     return 3;
00502   } else if (c < 0x110000) {
00503     *buf++ = 0xF0 + GB(c, 18, 3);
00504     *buf++ = 0x80 + GB(c, 12, 6);
00505     *buf++ = 0x80 + GB(c,  6, 6);
00506     *buf   = 0x80 + GB(c,  0, 6);
00507     return 4;
00508   }
00509 
00510   /* DEBUG(misc, 1, "[utf8] can't UTF-8 encode value 0x%X", c); */
00511   *buf = '?';
00512   return 1;
00513 }
00514 
00522 size_t Utf8TrimString(char *s, size_t maxlen)
00523 {
00524   size_t length = 0;
00525 
00526   for (const char *ptr = strchr(s, '\0'); *s != '\0';) {
00527     size_t len = Utf8EncodedCharLen(*s);
00528     /* Silently ignore invalid UTF8 sequences, our only concern trimming */
00529     if (len == 0) len = 1;
00530 
00531     /* Take care when a hard cutoff was made for the string and
00532      * the last UTF8 sequence is invalid */
00533     if (length + len >= maxlen || (s + len > ptr)) break;
00534     s += len;
00535     length += len;
00536   }
00537 
00538   *s = '\0';
00539   return length;
00540 }
00541 
00542 #ifdef DEFINE_STRNDUP
00543 #include "core/math_func.hpp"
00544 char *strndup(const char *s, size_t len)
00545 {
00546   len = min(strlen(s), len);
00547   char *tmp = CallocT<char>(len + 1);
00548   memcpy(tmp, s, len);
00549   return tmp;
00550 }
00551 #endif /* DEFINE_STRNDUP */
00552 
00553 #ifdef DEFINE_STRCASESTR
00554 char *strcasestr(const char *haystack, const char *needle)
00555 {
00556   size_t hay_len = strlen(haystack);
00557   size_t needle_len = strlen(needle);
00558   while (hay_len >= needle_len) {
00559     if (strncasecmp(haystack, needle, needle_len) == 0) return const_cast<char *>(haystack);
00560 
00561     haystack++;
00562     hay_len--;
00563   }
00564 
00565   return NULL;
00566 }
00567 #endif /* DEFINE_STRCASESTR */
00568 
00576 int strnatcmp(const char *s1, const char *s2)
00577 {
00578 #ifdef WITH_ICU
00579   if (_current_collator != NULL) {
00580     UErrorCode status = U_ZERO_ERROR;
00581     int result;
00582 
00583     /* We want to use the new faster method for ICU 4.2 and higher. */
00584 #if U_ICU_VERSION_MAJOR_NUM > 4 || (U_ICU_VERSION_MAJOR_NUM == 4 && U_ICU_VERSION_MINOR_NUM >= 2)
00585     /* The StringPiece parameter gets implicitly constructed from the char *. */
00586     result = _current_collator->compareUTF8(s1, s2, status);
00587 #else /* The following for 4.0 and lower. */
00588     UChar buffer1[DRAW_STRING_BUFFER];
00589     u_strFromUTF8Lenient(buffer1, lengthof(buffer1), NULL, s1, -1, &status);
00590     UChar buffer2[DRAW_STRING_BUFFER];
00591     u_strFromUTF8Lenient(buffer2, lengthof(buffer2), NULL, s2, -1, &status);
00592 
00593     result = _current_collator->compare(buffer1, buffer2, status);
00594 #endif /* ICU version check. */
00595     if (U_SUCCESS(status)) return result;
00596   }
00597 
00598 #endif /* WITH_ICU */
00599 
00600   /* Do a normal comparison if ICU is missing or if we cannot create a collator. */
00601   return strcasecmp(s1, s2);
00602 }

Generated on Fri Jun 3 05:18:58 2011 for OpenTTD by  doxygen 1.6.1