15#include "string_base.h"
23# define strncasecmp strnicmp
36# include <unicode/ustring.h>
41#if defined(WITH_COCOA)
59void strecpy(std::span<char> dst, std::string_view src)
62 if (std::empty(dst) || std::size(src) >= std::size(dst) - 1U) {
63#if defined(STRGEN) || defined(SETTINGSGEN)
64 FatalError(
"String too long for destination buffer");
66 Debug(misc, 0,
"String too long for destination buffer");
67 src = src.substr(0, std::size(dst) - 1U);
71 auto it = std::copy(std::begin(src), std::end(src), std::begin(dst));
83 str.reserve(data.size() * 2 + 1);
86 fmt::format_to(std::back_inserter(str),
"{:02X}", b);
100 case SCC_RECORD_SEPARATOR:
129 while (str <= last && *str !=
'\0') {
155 if (len == 0 || str + len > last + 1 || len !=
Utf8Decode(&c, str)) {
167 }
while (--len != 0);
225 if (str.empty())
return {};
227 auto buf = str.data();
228 auto last = buf + str.size() - 1;
230 std::ostringstream dst;
231 std::ostreambuf_iterator<char> dst_iter(dst);
248 auto it = std::begin(str);
249 auto last = std::prev(std::end(str));
251 while (it <= last && *it !=
'\0') {
257 if (len == 0 || it + len > last)
return false;
261 if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
280 str = StrTrimView(str);
283std::string_view StrTrimView(std::string_view str)
285 size_t first_pos = str.find_first_not_of(
' ');
286 if (first_pos == std::string::npos) {
287 return std::string_view{};
289 size_t last_pos = str.find_last_not_of(
' ');
290 return str.substr(first_pos, last_pos - first_pos + 1);
301 if (str.size() < prefix.size())
return false;
307 static bool eq(
char c1,
char c2) {
return toupper(c1) == toupper(c2); }
308 static bool ne(
char c1,
char c2) {
return toupper(c1) != toupper(c2); }
309 static bool lt(
char c1,
char c2) {
return toupper(c1) < toupper(c2); }
311 static int compare(
const char *s1,
const char *s2,
size_t n)
314 if (toupper(*s1) < toupper(*s2))
return -1;
315 if (toupper(*s1) > toupper(*s2))
return 1;
321 static const char *find(
const char *s,
size_t n,
char a)
323 for (; n > 0; --n, ++s) {
324 if (toupper(*s) == toupper(a))
return s;
341 if (str.size() < suffix.size())
return false;
356 return ci_str1.compare(ci_str2);
367 if (str1.size() != str2.size())
return false;
381 while (Utf8Consume(&t) != 0) len++;
396bool strtolower(std::string &str, std::string::size_type offs)
398 bool changed =
false;
399 for (
auto ch = str.begin() + offs; ch != str.end(); ++ch) {
400 auto new_ch =
static_cast<char>(tolower(
static_cast<unsigned char>(*ch)));
401 changed |= new_ch != *ch;
418 case CS_NUMERAL:
return (key >=
'0' && key <=
'9');
421 case CS_ALPHA:
return IsPrintable(key) && !(key >=
'0' && key <=
'9');
422 case CS_HEXADECIMAL:
return (key >=
'0' && key <=
'9') || (key >=
'a' && key <=
'f') || (key >=
'A' && key <=
'F');
423 default: NOT_REACHED();
439 assert(c !=
nullptr);
445 }
else if (
GB(s[0], 5, 3) == 6) {
446 if (IsUtf8Part(s[1])) {
448 *c =
GB(s[0], 0, 5) << 6 |
GB(s[1], 0, 6);
449 if (*c >= 0x80)
return 2;
451 }
else if (
GB(s[0], 4, 4) == 14) {
452 if (IsUtf8Part(s[1]) && IsUtf8Part(s[2])) {
454 *c =
GB(s[0], 0, 4) << 12 |
GB(s[1], 0, 6) << 6 |
GB(s[2], 0, 6);
455 if (*c >= 0x800)
return 3;
457 }
else if (
GB(s[0], 3, 5) == 30) {
458 if (IsUtf8Part(s[1]) && IsUtf8Part(s[2]) && IsUtf8Part(s[3])) {
460 *c =
GB(s[0], 0, 3) << 18 |
GB(s[1], 0, 6) << 12 |
GB(s[2], 0, 6) << 6 |
GB(s[3], 0, 6);
461 if (*c >= 0x10000 && *c <= 0x10FFFF)
return 4;
483 }
else if (c < 0x800) {
484 *buf++ = 0xC0 +
GB(c, 6, 5);
485 *buf = 0x80 +
GB(c, 0, 6);
487 }
else if (c < 0x10000) {
488 *buf++ = 0xE0 +
GB(c, 12, 4);
489 *buf++ = 0x80 +
GB(c, 6, 6);
490 *buf = 0x80 +
GB(c, 0, 6);
492 }
else if (c < 0x110000) {
493 *buf++ = 0xF0 +
GB(c, 18, 3);
494 *buf++ = 0x80 +
GB(c, 12, 6);
495 *buf++ = 0x80 +
GB(c, 6, 6);
496 *buf = 0x80 +
GB(c, 0, 6);
506 return Utf8Encode<char *>(buf, c);
509size_t Utf8Encode(std::ostreambuf_iterator<char> &buf,
char32_t c)
511 return Utf8Encode<std::ostreambuf_iterator<char> &>(buf, c);
514size_t Utf8Encode(std::back_insert_iterator<std::string> &buf,
char32_t c)
516 return Utf8Encode<std::back_insert_iterator<std::string> &>(buf, c);
530 for (
const char *ptr = strchr(s,
'\0'); *s !=
'\0';) {
533 if (len == 0) len = 1;
537 if (length + len >= maxlen || (s + len > ptr))
break;
546#ifdef DEFINE_STRCASESTR
547char *strcasestr(
const char *haystack,
const char *needle)
549 size_t hay_len = strlen(haystack);
550 size_t needle_len = strlen(needle);
551 while (hay_len >= needle_len) {
552 if (strncasecmp(haystack, needle, needle_len) == 0)
return const_cast<char *
>(haystack);
569 if (c >=
'0' && c <=
'9')
return false;
570 if (c >=
'A' && c <=
'Z')
return false;
571 if (c >=
'a' && c <=
'z')
return false;
572 if (c >= SCC_CONTROL_START && c <= SCC_CONTROL_END)
return true;
573 if (c >= 0xC0 && c <= 0x10FFFF)
return false;
588 auto first = std::begin(str);
589 auto last = std::end(str);
590 while (first < last) {
596 return {first, last};
609 if (ignore_garbage_at_front) {
616 UErrorCode status = U_ZERO_ERROR;
617 int result =
_current_collator->compareUTF8(icu::StringPiece(s1.data(), s1.size()), icu::StringPiece(s2.data(), s2.size()), status);
618 if (U_SUCCESS(status))
return result;
622#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
623 int res = OTTDStringCompare(s1, s2);
624 if (res != 0)
return res - 2;
627#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
629 if (res != 0)
return res - 2;
638#include <unicode/stsearch.h>
648static int ICUStringContains(
const std::string_view str,
const std::string_view value,
bool case_insensitive)
651 std::unique_ptr<icu::RuleBasedCollator> coll(
dynamic_cast<icu::RuleBasedCollator *
>(
_current_collator->clone()));
653 UErrorCode status = U_ZERO_ERROR;
654 coll->setStrength(case_insensitive ? icu::Collator::SECONDARY : icu::Collator::TERTIARY);
655 coll->setAttribute(UCOL_NUMERIC_COLLATION, UCOL_OFF, status);
657 auto u_str = icu::UnicodeString::fromUTF8(icu::StringPiece(str.data(), str.size()));
658 auto u_value = icu::UnicodeString::fromUTF8(icu::StringPiece(value.data(), value.size()));
659 icu::StringSearch u_searcher(u_value, u_str, coll.get(),
nullptr, status);
660 if (U_SUCCESS(status)) {
661 auto pos = u_searcher.first(status);
662 if (U_SUCCESS(status))
return pos != USEARCH_DONE ? 1 : 0;
682 if (res_u >= 0)
return res_u > 0;
685#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
687 if (res >= 0)
return res > 0;
690#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
692 if (res >= 0)
return res > 0;
695 return str.find(value) != std::string_view::npos;
709 if (res_u >= 0)
return res_u > 0;
712#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
714 if (res >= 0)
return res > 0;
717#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
719 if (res >= 0)
return res > 0;
724 return ci_str.find(ci_value) != CaseInsensitiveStringView::npos;
735 if (c >=
'0' && c <=
'9')
return c -
'0';
736 if (c >=
'A' && c <=
'F')
return c + 10 -
'A';
737 if (c >=
'a' && c <=
'f')
return c + 10 -
'a';
754 if (bytes.size() != hex.size() / 2) {
759 if (hex.size() % 2 != 0) {
763 for (
size_t i = 0; i < hex.size() / 2; i++) {
767 if (hi < 0 || lo < 0) {
771 bytes[i] = (hi << 4) | lo;
781 return std::make_unique<UniscribeStringIterator>();
784#elif defined(WITH_ICU_I18N)
786#include <unicode/utext.h>
787#include <unicode/brkiter.h>
801 UErrorCode status = U_ZERO_ERROR;
805 this->utf16_str.push_back(
'\0');
806 this->utf16_to_utf8.push_back(0);
817 const char *string_base = s;
823 this->utf16_str.clear();
824 this->utf16_to_utf8.clear();
827 size_t idx = s - string_base;
829 char32_t c = Utf8Consume(&s);
831 this->utf16_str.push_back((UChar)c);
834 this->utf16_str.push_back((UChar)(0xD800 + ((c - 0x10000) >> 10)));
835 this->utf16_str.push_back((UChar)(0xDC00 + ((c - 0x10000) & 0x3FF)));
836 this->utf16_to_utf8.push_back(idx);
838 this->utf16_to_utf8.push_back(idx);
840 this->utf16_str.push_back(
'\0');
841 this->utf16_to_utf8.push_back(s - string_base);
843 UText text = UTEXT_INITIALIZER;
844 UErrorCode status = U_ZERO_ERROR;
845 utext_openUChars(&text, this->utf16_str.data(), this->utf16_str.size() - 1, &status);
846 this->char_itr->setText(&text, status);
847 this->word_itr->setText(&text, status);
848 this->char_itr->first();
849 this->word_itr->first();
856 for (uint i = 0; i < this->utf16_to_utf8.size(); i++) {
857 if (this->utf16_to_utf8[i] == pos) {
866 this->char_itr->isBoundary(utf16_pos);
867 return this->utf16_to_utf8[this->char_itr->current()];
875 pos = this->char_itr->next();
879 pos = this->word_itr->following(this->char_itr->current());
883 while (pos != icu::BreakIterator::DONE &&
885 int32_t new_pos = this->word_itr->next();
888 if (new_pos == icu::BreakIterator::DONE)
break;
892 this->char_itr->isBoundary(pos);
899 return pos == icu::BreakIterator::DONE ?
END : this->utf16_to_utf8[pos];
907 pos = this->char_itr->previous();
911 pos = this->word_itr->preceding(this->char_itr->current());
915 while (pos != icu::BreakIterator::DONE &&
917 int32_t new_pos = this->word_itr->previous();
920 if (new_pos == icu::BreakIterator::DONE)
break;
924 this->char_itr->isBoundary(pos);
931 return pos == icu::BreakIterator::DONE ?
END : this->utf16_to_utf8[pos];
937 return std::make_unique<IcuStringIterator>();
950 DefaultStringIterator() : string(nullptr), len(0), cur_pos(0)
957 this->len = strlen(s);
963 assert(this->
string !=
nullptr && pos <= this->len);
965 while (pos > 0 && IsUtf8Part(this->
string[pos])) pos--;
966 return this->cur_pos = pos;
969 size_t Next(IterType what)
override
971 assert(this->
string !=
nullptr);
974 if (this->cur_pos >= this->len)
return END;
979 this->cur_pos +=
Utf8Decode(&c, this->
string + this->cur_pos);
980 return this->cur_pos;
986 size_t offs =
Utf8Decode(&c, this->
string + this->cur_pos);
988 this->cur_pos += offs;
989 offs =
Utf8Decode(&c, this->
string + this->cur_pos);
993 this->cur_pos += offs;
994 offs =
Utf8Decode(&c, this->
string + this->cur_pos);
997 return this->cur_pos;
1007 size_t Prev(IterType what)
override
1009 assert(this->
string !=
nullptr);
1012 if (this->cur_pos == 0)
return END;
1016 return this->cur_pos =
Utf8PrevChar(this->
string + this->cur_pos) - this->string;
1019 const char *s = this->
string + this->cur_pos;
1034 return this->cur_pos = s - this->string;
1045#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
1048 std::unique_ptr<StringIterator> i = OSXStringIterator::Create();
1049 if (i !=
nullptr)
return i;
1051 return std::make_unique<DefaultStringIterator>();
1056 return std::make_unique<DefaultStringIterator>();
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
String iterator using ICU as a backend.
void SetString(const char *s) override
Set a new iteration string.
size_t Prev(IterType what) override
Move the cursor back by one iteration unit.
size_t Next(IterType what) override
Advance the cursor by one iteration unit.
std::vector< size_t > utf16_to_utf8
Mapping from UTF-16 code point position to index in the UTF-8 source string.
size_t SetCurPosition(size_t pos) override
Change the current string cursor.
std::vector< UChar > utf16_str
UTF-16 copy of the string.
icu::BreakIterator * char_itr
ICU iterator for characters.
icu::BreakIterator * word_itr
ICU iterator for words.
Class for iterating over different kind of parts of a string.
static const size_t END
Sentinel to indicate end-of-iteration.
virtual size_t Prev(IterType what=ITER_CHARACTER)=0
Move the cursor back by one iteration unit.
virtual size_t SetCurPosition(size_t pos)=0
Change the current string cursor.
virtual size_t Next(IterType what=ITER_CHARACTER)=0
Advance the cursor by one iteration unit.
static std::unique_ptr< StringIterator > Create()
Create a new iterator instance.
IterType
Type of the iterator.
@ ITER_WORD
Iterate over words.
@ ITER_CHARACTER
Iterate over characters (or more exactly grapheme clusters).
virtual void SetString(const char *s)=0
Set a new iteration string.
Control codes that are embedded in the translation strings.
@ SCC_ENCODED
Encoded string marker and sub-string parameter.
@ SCC_ENCODED_NUMERIC
Encoded numeric parameter.
@ SCC_ENCODED_STRING
Encoded string parameter.
@ SCC_ENCODED_INTERNAL
Encoded text from OpenTTD.
Functions related to debugging.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Error reporting related functions.
fluid_settings_t * settings
FluidSynth settings handle.
Functions related to the gfx engine.
Information about languages and their files.
const LanguageMetadata * _current_language
The currently loaded language.
std::unique_ptr< icu::Collator > _current_collator
Collator for the language currently in use.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
bool ConvertHexToBytes(std::string_view hex, std::span< uint8_t > bytes)
Convert a hex-string to a byte-array, while validating it was actually hex.
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
bool StrEqualsIgnoreCase(const std::string_view str1, const std::string_view str2)
Compares two string( view)s for equality, while ignoring the case of the characters.
bool StrNaturalContains(const std::string_view str, const std::string_view value)
Checks if a string is contained in another string with a locale-aware comparison that is case sensiti...
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).
void strecpy(std::span< char > dst, std::string_view src)
Copies characters from one buffer to another.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
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...
bool StrStartsWithIgnoreCase(std::string_view str, const std::string_view prefix)
Check whether the given string starts with the given prefix, ignoring case.
bool StrValid(std::span< const char > str)
Checks whether the given string is valid, i.e.
static int ConvertHexNibbleToByte(char c)
Convert a single hex-nibble to a byte.
static int ICUStringContains(const std::string_view str, const std::string_view value, bool case_insensitive)
Search if a string is contained in another string using the current locale.
static std::string_view SkipGarbage(std::string_view str)
Skip some of the 'garbage' in the string that we don't want to use to sort on.
static bool IsSccEncodedCode(char32_t c)
Test if a character is (only) part of an encoded string.
size_t Utf8Decode(char32_t *c, const char *s)
Decode and consume the next UTF-8 encoded character.
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
bool StrNaturalContainsIgnoreCase(const std::string_view str, const std::string_view value)
Checks if a string is contained in another string with a locale-aware comparison that is case insensi...
std::basic_string_view< char, CaseInsensitiveCharTraits > CaseInsensitiveStringView
Case insensitive string view.
int StrCompareIgnoreCase(const std::string_view str1, const std::string_view str2)
Compares two string( view)s, while ignoring the case of the characters.
bool StrEndsWithIgnoreCase(std::string_view str, const std::string_view suffix)
Check whether the given string ends with the given suffix, ignoring case.
size_t Utf8TrimString(char *s, size_t maxlen)
Properly terminate an UTF8 string to some maximum length.
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
size_t Utf8Encode(T buf, char32_t c)
Encode a unicode character and place it in the buffer.
static bool IsGarbageCharacter(char32_t c)
Test if a unicode character is considered garbage to be skipped.
Functions related to low-level strings.
char32_t Utf16DecodeChar(const uint16_t *c)
Decode an UTF-16 character.
bool IsWhitespace(char32_t c)
Check whether UNICODE character is whitespace or not, i.e.
int8_t Utf8EncodedCharLen(char c)
Return the length of an UTF-8 encoded value based on a single char.
char * Utf8PrevChar(char *s)
Retrieve the previous UNICODE character in an UTF-8 encoded string.
int MacOSStringCompare(std::string_view s1, std::string_view s2)
Compares two strings using case insensitive natural sort.
int MacOSStringContains(const std::string_view str, const std::string_view value, bool case_insensitive)
Search if a string is contained in another string using the current locale.
Functions related to localized text support on OSX.
StringValidationSettings
Settings for the string validation.
@ SVS_ALLOW_CONTROL_CODE
Allow the special control codes.
@ SVS_REPLACE_TAB_CR_NL_WITH_SPACE
Replace tabs ('\t'), carriage returns ('\r') and newlines (' ') with spaces.
@ SVS_ALLOW_NEWLINE
Allow newlines; replaces '\r ' with ' ' during processing.
@ SVS_REPLACE_WITH_QUESTION_MARK
Replace the unknown/bad bits with question marks.
CharSetFilter
Valid filter types for IsValidChar.
@ CS_NUMERAL_SPACE
Only numbers and spaces.
@ CS_HEXADECIMAL
Only hexadecimal characters.
@ CS_NUMERAL
Only numeric ones.
@ CS_NUMERAL_SIGNED
Only numbers and '-' for negative values.
@ CS_ALPHA
Only alphabetic values.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Functions related to laying out text on Win32.
Case insensitive implementation of the standard character type traits.
int Win32StringContains(const std::string_view str, const std::string_view value, bool case_insensitive)
Search if a string is contained in another string using the current locale.
declarations of functions for MS windows systems