diff options
author | terkhen <terkhen@openttd.org> | 2010-11-27 22:47:29 +0000 |
---|---|---|
committer | terkhen <terkhen@openttd.org> | 2010-11-27 22:47:29 +0000 |
commit | 4b944cb13e6d75662a9246bf06523a320d814ace (patch) | |
tree | e33fd0022fdb6fda524161327738ad9c9c5db53d /src/string.cpp | |
parent | ae78847f0fe2c0bde677e4a9f2ae26913b9d0f20 (diff) | |
download | openttd-4b944cb13e6d75662a9246bf06523a320d814ace.tar.xz |
(svn r21343) -Add: Function that compares strings using case insensitive natural sort.
Diffstat (limited to 'src/string.cpp')
-rw-r--r-- | src/string.cpp | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/string.cpp b/src/string.cpp index bad29649d..c3d6f5bc0 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -24,6 +24,13 @@ #include <errno.h> // required by vsnprintf implementation for MSVC #endif +#ifdef WITH_ICU +/* Required by strnatcmp. */ +#include <unicode/ustring.h> +#include "language.h" +#include "gfx_func.h" +#endif /* WITH_ICU */ + /** * Safer implementation of vsnprintf; same as vsnprintf except: * - last instead of size, i.e. replace sizeof with lastof. @@ -463,3 +470,38 @@ char *strcasestr(const char *haystack, const char *needle) return NULL; } #endif /* DEFINE_STRCASESTR */ + +/** + * Compares two strings using case insensitive natural sort. + * + * @param s1 First string to compare. + * @param s2 Second string to compare. + * @return Less than zero if s1 < s2, zero if s1 == s2, greater than zero if s1 > s2. + */ +int strnatcmp(const char *s1, const char *s2) +{ +#ifdef WITH_ICU + if (_current_collator != NULL) { + UErrorCode status = U_ZERO_ERROR; + int result; + + /* We want to use the new faster method for ICU 4.2 and higher. */ +#if U_ICU_VERSION_MAJOR_NUM > 4 || (U_ICU_VERSION_MAJOR_NUM == 4 && U_ICU_VERSION_MINOR_NUM >= 2) + /* The StringPiece parameter gets implicitly constructed from the char *. */ + result = _current_collator->compareUTF8(s1, s2, status); +#else /* The following for 4.0 and lower. */ + UChar buffer1[DRAW_STRING_BUFFER]; + u_strFromUTF8Lenient(buffer1, lengthof(buffer1), NULL, s1, -1, &status); + UChar buffer2[DRAW_STRING_BUFFER]; + u_strFromUTF8Lenient(buffer2, lengthof(buffer2), NULL, s2, -1, &status); + + result = _current_collator->compare(buffer1, buffer2, status); +#endif /* ICU version check. */ + if (U_SUCCESS(status)) return result; + } + +#endif /* WITH_ICU */ + + /* Do a normal comparison if ICU is missing or if we cannot create a collator. */ + return strcasecmp(s1, s2); +} |