15#include "string_base.h"
21# define strncasecmp strnicmp
34# include <unicode/ustring.h>
39#if defined(WITH_COCOA)
57void strecpy(std::span<char> dst, std::string_view src)
60 if (std::empty(dst) || std::size(src) >= std::size(dst) - 1U) {
61#if defined(STRGEN) || defined(SETTINGSGEN)
62 FatalError(
"String too long for destination buffer");
64 Debug(misc, 0,
"String too long for destination buffer");
65 src = src.substr(0, std::size(dst) - 1U);
69 auto it = std::copy(std::begin(src), std::end(src), std::begin(dst));
81 str.reserve(data.size() * 2 + 1);
84 fmt::format_to(std::back_inserter(str),
"{:02X}", b);
98 case SCC_RECORD_SEPARATOR:
127 while (str <= last && *str !=
'\0') {
153 if (len == 0 || str + len > last + 1 || len !=
Utf8Decode(&c, str)) {
165 }
while (--len != 0);
210 if (str.empty())
return;
212 char *buf = str.data();
213 char *last = buf + str.size() - 1;
216 str.erase(dst - buf, std::string::npos);
228 if (str.empty())
return {};
230 auto buf = str.data();
231 auto last = buf + str.size() - 1;
233 std::ostringstream dst;
234 std::ostreambuf_iterator<char> dst_iter(dst);
251 auto it = std::begin(str);
252 auto last = std::prev(std::end(str));
254 while (it <= last && *it !=
'\0') {
260 if (len == 0 || it + len > last)
return false;
264 if (!IsPrintable(c) || (c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
283 str = StrTrimView(str);
286std::string_view StrTrimView(std::string_view str)
288 size_t first_pos = str.find_first_not_of(
' ');
289 if (first_pos == std::string::npos) {
290 return std::string_view{};
292 size_t last_pos = str.find_last_not_of(
' ');
293 return str.substr(first_pos, last_pos - first_pos + 1);
304 if (str.size() < prefix.size())
return false;
310 static bool eq(
char c1,
char c2) {
return toupper(c1) == toupper(c2); }
311 static bool ne(
char c1,
char c2) {
return toupper(c1) != toupper(c2); }
312 static bool lt(
char c1,
char c2) {
return toupper(c1) < toupper(c2); }
314 static int compare(
const char *s1,
const char *s2,
size_t n)
317 if (toupper(*s1) < toupper(*s2))
return -1;
318 if (toupper(*s1) > toupper(*s2))
return 1;
324 static const char *find(
const char *s,
size_t n,
char a)
326 for (; n > 0; --n, ++s) {
327 if (toupper(*s) == toupper(a))
return s;
344 if (str.size() < suffix.size())
return false;
359 return ci_str1.compare(ci_str2);
370 if (str1.size() != str2.size())
return false;
385 return ci_str.find(ci_value) != ci_str.npos;
397 return std::distance(view.begin(), view.end());
400bool strtolower(std::string &str, std::string::size_type offs)
402 bool changed =
false;
403 for (
auto ch = str.begin() + offs; ch != str.end(); ++ch) {
404 auto new_ch =
static_cast<char>(tolower(
static_cast<unsigned char>(*ch)));
405 changed |= new_ch != *ch;
422 case CS_NUMERAL:
return (key >=
'0' && key <=
'9');
425 case CS_ALPHA:
return IsPrintable(key) && !(key >=
'0' && key <=
'9');
426 case CS_HEXADECIMAL:
return (key >=
'0' && key <=
'9') || (key >=
'a' && key <=
'f') || (key >=
'A' && key <=
'F');
427 default: NOT_REACHED();
443 assert(c !=
nullptr);
449 }
else if (
GB(s[0], 5, 3) == 6) {
450 if (IsUtf8Part(s[1])) {
452 *c =
GB(s[0], 0, 5) << 6 |
GB(s[1], 0, 6);
453 if (*c >= 0x80)
return 2;
455 }
else if (
GB(s[0], 4, 4) == 14) {
456 if (IsUtf8Part(s[1]) && IsUtf8Part(s[2])) {
458 *c =
GB(s[0], 0, 4) << 12 |
GB(s[1], 0, 6) << 6 |
GB(s[2], 0, 6);
459 if (*c >= 0x800)
return 3;
461 }
else if (
GB(s[0], 3, 5) == 30) {
462 if (IsUtf8Part(s[1]) && IsUtf8Part(s[2]) && IsUtf8Part(s[3])) {
464 *c =
GB(s[0], 0, 3) << 18 |
GB(s[1], 0, 6) << 12 |
GB(s[2], 0, 6) << 6 |
GB(s[3], 0, 6);
465 if (*c >= 0x10000 && *c <= 0x10FFFF)
return 4;
480 if (c >=
'0' && c <=
'9')
return false;
481 if (c >=
'A' && c <=
'Z')
return false;
482 if (c >=
'a' && c <=
'z')
return false;
483 if (c >= SCC_CONTROL_START && c <= SCC_CONTROL_END)
return true;
484 if (c >= 0xC0 && c <= 0x10FFFF)
return false;
500 auto it = view.begin();
501 const auto end = view.end();
503 return str.substr(it.GetByteOffset());
516 if (ignore_garbage_at_front) {
523 UErrorCode status = U_ZERO_ERROR;
524 int result =
_current_collator->compareUTF8(icu::StringPiece(s1.data(), s1.size()), icu::StringPiece(s2.data(), s2.size()), status);
525 if (U_SUCCESS(status))
return result;
529#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
530 int res = OTTDStringCompare(s1, s2);
531 if (res != 0)
return res - 2;
534#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
536 if (res != 0)
return res - 2;
545#include <unicode/stsearch.h>
555static int ICUStringContains(
const std::string_view str,
const std::string_view value,
bool case_insensitive)
558 std::unique_ptr<icu::RuleBasedCollator> coll(
dynamic_cast<icu::RuleBasedCollator *
>(
_current_collator->clone()));
560 UErrorCode status = U_ZERO_ERROR;
561 coll->setStrength(case_insensitive ? icu::Collator::SECONDARY : icu::Collator::TERTIARY);
562 coll->setAttribute(UCOL_NUMERIC_COLLATION, UCOL_OFF, status);
564 auto u_str = icu::UnicodeString::fromUTF8(icu::StringPiece(str.data(), str.size()));
565 auto u_value = icu::UnicodeString::fromUTF8(icu::StringPiece(value.data(), value.size()));
566 icu::StringSearch u_searcher(u_value, u_str, coll.get(),
nullptr, status);
567 if (U_SUCCESS(status)) {
568 auto pos = u_searcher.first(status);
569 if (U_SUCCESS(status))
return pos != USEARCH_DONE ? 1 : 0;
589 if (res_u >= 0)
return res_u > 0;
592#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
594 if (res >= 0)
return res > 0;
597#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
599 if (res >= 0)
return res > 0;
602 return str.find(value) != std::string_view::npos;
616 if (res_u >= 0)
return res_u > 0;
619#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
621 if (res >= 0)
return res > 0;
624#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
626 if (res >= 0)
return res > 0;
631 return ci_str.find(ci_value) != CaseInsensitiveStringView::npos;
642 if (c >=
'0' && c <=
'9')
return c -
'0';
643 if (c >=
'A' && c <=
'F')
return c + 10 -
'A';
644 if (c >=
'a' && c <=
'f')
return c + 10 -
'a';
661 if (bytes.size() != hex.size() / 2) {
666 if (hex.size() % 2 != 0) {
670 for (
size_t i = 0; i < hex.size() / 2; i++) {
674 if (hi < 0 || lo < 0) {
678 bytes[i] = (hi << 4) | lo;
688 return std::make_unique<UniscribeStringIterator>();
691#elif defined(WITH_ICU_I18N)
693#include <unicode/utext.h>
694#include <unicode/brkiter.h>
708 UErrorCode status = U_ZERO_ERROR;
712 this->utf16_str.push_back(
'\0');
713 this->utf16_to_utf8.push_back(0);
728 this->utf16_str.clear();
729 this->utf16_to_utf8.clear();
732 for (
auto it = view.begin(), end = view.end(); it != end; ++it) {
733 size_t idx = it.GetByteOffset();
736 this->utf16_str.push_back((UChar)c);
739 this->utf16_str.push_back((UChar)(0xD800 + ((c - 0x10000) >> 10)));
740 this->utf16_str.push_back((UChar)(0xDC00 + ((c - 0x10000) & 0x3FF)));
741 this->utf16_to_utf8.push_back(idx);
743 this->utf16_to_utf8.push_back(idx);
745 this->utf16_str.push_back(
'\0');
746 this->utf16_to_utf8.push_back(s.size());
748 UText text = UTEXT_INITIALIZER;
749 UErrorCode status = U_ZERO_ERROR;
750 utext_openUChars(&text, this->utf16_str.data(), this->utf16_str.size() - 1, &status);
751 this->char_itr->setText(&text, status);
752 this->word_itr->setText(&text, status);
753 this->char_itr->first();
754 this->word_itr->first();
761 for (uint i = 0; i < this->utf16_to_utf8.size(); i++) {
762 if (this->utf16_to_utf8[i] == pos) {
771 this->char_itr->isBoundary(utf16_pos);
772 return this->utf16_to_utf8[this->char_itr->current()];
780 pos = this->char_itr->next();
784 pos = this->word_itr->following(this->char_itr->current());
788 while (pos != icu::BreakIterator::DONE &&
790 int32_t new_pos = this->word_itr->next();
793 if (new_pos == icu::BreakIterator::DONE)
break;
797 this->char_itr->isBoundary(pos);
804 return pos == icu::BreakIterator::DONE ?
END : this->utf16_to_utf8[pos];
812 pos = this->char_itr->previous();
816 pos = this->word_itr->preceding(this->char_itr->current());
820 while (pos != icu::BreakIterator::DONE &&
822 int32_t new_pos = this->word_itr->previous();
825 if (new_pos == icu::BreakIterator::DONE)
break;
829 this->char_itr->isBoundary(pos);
836 return pos == icu::BreakIterator::DONE ?
END : this->utf16_to_utf8[pos];
842 return std::make_unique<IcuStringIterator>();
854 void SetString(std::string_view s)
override
857 this->cur_pos = this->
string.begin();
862 this->cur_pos = this->
string.GetIterAtByte(pos);
863 return this->cur_pos.GetByteOffset();
866 size_t Next(IterType what)
override
868 const auto end = this->
string.end();
870 if (this->cur_pos >= end)
return END;
875 return this->cur_pos.GetByteOffset();
879 while (this->cur_pos != end && !
IsWhitespace(*this->cur_pos)) {
883 while (this->cur_pos != end &&
IsWhitespace(*this->cur_pos)) {
886 return this->cur_pos.GetByteOffset();
895 size_t Prev(IterType what)
override
897 const auto begin = this->
string.begin();
899 if (this->cur_pos == begin)
return END;
904 return this->cur_pos.GetByteOffset();
910 }
while (this->cur_pos != begin &&
IsWhitespace(*this->cur_pos));
912 while (this->cur_pos != begin && !
IsWhitespace(*this->cur_pos)) {
917 return this->cur_pos.GetByteOffset();
927#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
930 std::unique_ptr<StringIterator> i = OSXStringIterator::Create();
931 if (i !=
nullptr)
return i;
933 return std::make_unique<DefaultStringIterator>();
938 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.
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.
void SetString(std::string_view s) override
Set a new iteration 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(std::string_view s)=0
Set a new iteration string.
Bidirectional input iterator over codepoints.
Constant span of UTF-8 encoded data.
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.
size_t Utf8StringLength(std::string_view str)
Get the length of an UTF-8 encoded string in number of characters and thus not the number of bytes th...
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
bool StrContainsIgnoreCase(const std::string_view str, const std::string_view value)
Checks if a string is contained in another string, while ignoring the case of the characters.
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.
void StrMakeValidInPlace(char *str, StringValidationSettings settings)
Scans the string for invalid characters and replaces them with a question mark '?' (if not ignored).
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 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.
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.
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
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.
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.
@ ReplaceWithQuestionMark
Replace the unknown/bad bits with question marks.
@ AllowControlCode
Allow the special control codes.
@ AllowNewline
Allow newlines; replaces '\r ' with ' ' during processing.
@ ReplaceTabCrNlWithSpace
Replace tabs ('\t'), carriage returns ('\r') and newlines (' ') with spaces.
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.
Handling of UTF-8 encoded data.
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