15#include "string_base.h"
31# include <unicode/brkiter.h>
32# include <unicode/stsearch.h>
33# include <unicode/ustring.h>
34# include <unicode/utext.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 format_append(str,
"{:02X}", b);
98 case SCC_RECORD_SEPARATOR:
119template <
class Builder>
125 if (!c.has_value()) {
132 if ((IsPrintable(*c) && (*c < SCC_SPRITE_START || *c > SCC_SPRITE_END)) ||
141 builder.PutChar(
' ');
144 builder.PutChar(
'?');
175 if (str.empty())
return;
212 if (!c.has_value())
return false;
213 if (*c == 0)
return true;
214 if (!IsPrintable(*c) || (*c >= SCC_SPRITE_START && *c <= SCC_SPRITE_END)) {
232 if (first_pos == std::string::npos) {
236 str.erase(0, first_pos);
239 str.erase(last_pos + 1);
242std::string_view StrTrimView(std::string_view str, std::string_view characters_to_trim)
244 size_t first_pos = str.find_first_not_of(characters_to_trim);
245 if (first_pos == std::string::npos) {
246 return std::string_view{};
248 size_t last_pos = str.find_last_not_of(characters_to_trim);
249 return str.substr(first_pos, last_pos - first_pos + 1);
260 if (str.size() < prefix.size())
return false;
266 static bool eq(
char c1,
char c2) {
return toupper(c1) == toupper(c2); }
267 static bool ne(
char c1,
char c2) {
return toupper(c1) != toupper(c2); }
268 static bool lt(
char c1,
char c2) {
return toupper(c1) < toupper(c2); }
270 static int compare(
const char *s1,
const char *s2,
size_t n)
273 if (toupper(*s1) < toupper(*s2))
return -1;
274 if (toupper(*s1) > toupper(*s2))
return 1;
280 static const char *find(
const char *s,
size_t n,
char a)
282 for (; n > 0; --n, ++s) {
283 if (toupper(*s) == toupper(a))
return s;
300 if (str.size() < suffix.size())
return false;
315 return ci_str1.compare(ci_str2);
326 if (str1.size() != str2.size())
return false;
341 return ci_str.find(ci_value) != ci_str.npos;
353 return std::distance(view.begin(), view.end());
356bool strtolower(std::string &str, std::string::size_type offs)
358 bool changed =
false;
359 for (
auto ch = str.begin() + offs; ch != str.end(); ++ch) {
360 auto new_ch =
static_cast<char>(tolower(
static_cast<unsigned char>(*ch)));
361 changed |= new_ch != *ch;
378 case CS_NUMERAL:
return (key >=
'0' && key <=
'9');
381 case CS_ALPHA:
return IsPrintable(key) && !(key >=
'0' && key <=
'9');
382 case CS_HEXADECIMAL:
return (key >=
'0' && key <=
'9') || (key >=
'a' && key <=
'f') || (key >=
'A' && key <=
'F');
383 default: NOT_REACHED();
394 if (c >=
'0' && c <=
'9')
return false;
395 if (c >=
'A' && c <=
'Z')
return false;
396 if (c >=
'a' && c <=
'z')
return false;
397 if (c >= SCC_CONTROL_START && c <= SCC_CONTROL_END)
return true;
398 if (c >= 0xC0 && c <= 0x10FFFF)
return false;
414 auto it = view.begin();
415 const auto end = view.end();
417 return str.substr(it.GetByteOffset());
430 if (ignore_garbage_at_front) {
437 UErrorCode status = U_ZERO_ERROR;
438 int result =
_current_collator->compareUTF8(icu::StringPiece(s1.data(), s1.size()), icu::StringPiece(s2.data(), s2.size()), status);
439 if (U_SUCCESS(status))
return result;
443#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
444 int res = OTTDStringCompare(s1, s2);
445 if (res != 0)
return res - 2;
448#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
450 if (res != 0)
return res - 2;
467static int ICUStringContains(std::string_view str, std::string_view value,
bool case_insensitive)
470 std::unique_ptr<icu::RuleBasedCollator> coll(
dynamic_cast<icu::RuleBasedCollator *
>(
_current_collator->clone()));
472 UErrorCode status = U_ZERO_ERROR;
473 coll->setStrength(case_insensitive ? icu::Collator::SECONDARY : icu::Collator::TERTIARY);
474 coll->setAttribute(UCOL_NUMERIC_COLLATION, UCOL_OFF, status);
476 auto u_str = icu::UnicodeString::fromUTF8(icu::StringPiece(str.data(), str.size()));
477 auto u_value = icu::UnicodeString::fromUTF8(icu::StringPiece(value.data(), value.size()));
478 icu::StringSearch u_searcher(u_value, u_str, coll.get(),
nullptr, status);
479 if (U_SUCCESS(status)) {
480 auto pos = u_searcher.first(status);
481 if (U_SUCCESS(status))
return pos != USEARCH_DONE ? 1 : 0;
501 if (res_u >= 0)
return res_u > 0;
504#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
506 if (res >= 0)
return res > 0;
509#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
511 if (res >= 0)
return res > 0;
514 return str.find(value) != std::string_view::npos;
528 if (res_u >= 0)
return res_u > 0;
531#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
533 if (res >= 0)
return res > 0;
536#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
538 if (res >= 0)
return res > 0;
543 return ci_str.find(ci_value) != CaseInsensitiveStringView::npos;
554 if (c >=
'0' && c <=
'9')
return c -
'0';
555 if (c >=
'A' && c <=
'F')
return c + 10 -
'A';
556 if (c >=
'a' && c <=
'f')
return c + 10 -
'a';
573 if (bytes.size() != hex.size() / 2) {
578 if (hex.size() % 2 != 0) {
582 for (
size_t i = 0; i < hex.size() / 2; i++) {
586 if (hi < 0 || lo < 0) {
590 bytes[i] = (hi << 4) | lo;
600 return std::make_unique<UniscribeStringIterator>();
603#elif defined(WITH_ICU_I18N)
617 UErrorCode status = U_ZERO_ERROR;
619 this->char_itr.reset(icu::BreakIterator::createCharacterInstance(locale, status));
620 this->word_itr.reset(icu::BreakIterator::createWordInstance(locale, status));
622 this->utf16_str.push_back(
'\0');
623 this->utf16_to_utf8.push_back(0);
634 this->utf16_str.clear();
635 this->utf16_to_utf8.clear();
638 for (
auto it = view.begin(), end = view.end(); it != end; ++it) {
639 size_t idx = it.GetByteOffset();
642 this->utf16_str.push_back((UChar)c);
645 this->utf16_str.push_back((UChar)(0xD800 + ((c - 0x10000) >> 10)));
646 this->utf16_str.push_back((UChar)(0xDC00 + ((c - 0x10000) & 0x3FF)));
647 this->utf16_to_utf8.push_back(idx);
649 this->utf16_to_utf8.push_back(idx);
651 this->utf16_str.push_back(
'\0');
652 this->utf16_to_utf8.push_back(s.size());
654 UText text = UTEXT_INITIALIZER;
655 UErrorCode status = U_ZERO_ERROR;
656 utext_openUChars(&text, this->utf16_str.data(), this->utf16_str.size() - 1, &status);
657 this->char_itr->setText(&text, status);
658 this->word_itr->setText(&text, status);
659 this->char_itr->first();
660 this->word_itr->first();
667 for (uint i = 0; i < this->utf16_to_utf8.size(); i++) {
668 if (this->utf16_to_utf8[i] == pos) {
677 this->char_itr->isBoundary(utf16_pos);
678 return this->utf16_to_utf8[this->char_itr->current()];
686 pos = this->char_itr->next();
690 pos = this->word_itr->following(this->char_itr->current());
694 while (pos != icu::BreakIterator::DONE &&
696 int32_t new_pos = this->word_itr->next();
699 if (new_pos == icu::BreakIterator::DONE)
break;
703 this->char_itr->isBoundary(pos);
710 return pos == icu::BreakIterator::DONE ?
END : this->utf16_to_utf8[pos];
718 pos = this->char_itr->previous();
722 pos = this->word_itr->preceding(this->char_itr->current());
726 while (pos != icu::BreakIterator::DONE &&
728 int32_t new_pos = this->word_itr->previous();
731 if (new_pos == icu::BreakIterator::DONE)
break;
735 this->char_itr->isBoundary(pos);
742 return pos == icu::BreakIterator::DONE ?
END : this->utf16_to_utf8[pos];
748 return std::make_unique<IcuStringIterator>();
760 void SetString(std::string_view s)
override
763 this->cur_pos = this->
string.begin();
768 this->cur_pos = this->
string.GetIterAtByte(pos);
769 return this->cur_pos.GetByteOffset();
772 size_t Next(IterType what)
override
774 const auto end = this->
string.end();
776 if (this->cur_pos >= end)
return END;
781 return this->cur_pos.GetByteOffset();
785 while (this->cur_pos != end && !
IsWhitespace(*this->cur_pos)) {
789 while (this->cur_pos != end &&
IsWhitespace(*this->cur_pos)) {
792 return this->cur_pos.GetByteOffset();
801 size_t Prev(IterType what)
override
803 const auto begin = this->
string.begin();
805 if (this->cur_pos == begin)
return END;
810 return this->cur_pos.GetByteOffset();
816 }
while (this->cur_pos != begin &&
IsWhitespace(*this->cur_pos));
818 while (this->cur_pos != begin && !
IsWhitespace(*this->cur_pos)) {
823 return this->cur_pos.GetByteOffset();
833#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
836 std::unique_ptr<StringIterator> i = OSXStringIterator::Create();
837 if (i !=
nullptr)
return i;
839 return std::make_unique<DefaultStringIterator>();
844 return std::make_unique<DefaultStringIterator>();
855std::optional<std::string_view>
GetEnv(
const char *variable)
857 auto val = std::getenv(variable);
858 if (val ==
nullptr || *val ==
'\0')
return std::nullopt;
void PutChar(char c)
Append 8-bit char.
String iterator using ICU as a backend.
size_t Prev(IterType what) override
Move the cursor back by one iteration unit.
std::unique_ptr< icu::BreakIterator > word_itr
ICU iterator for words.
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.
std::unique_ptr< icu::BreakIterator > char_itr
ICU iterator for characters.
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.
bool AnyBytesUnused() const noexcept
Check whether any unused bytes are left between the Builder and Consumer position.
size_type GetBytesWritten() const noexcept
Get number of already written bytes.
Compose data into a fixed size buffer, which is consumed at the same time.
InPlaceBuilder builder
Builder into shared buffer.
StringConsumer consumer
Consumer from shared buffer.
Compose data into a growing std::string.
Parse data from a string / buffer.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
bool PeekCharIf(char c) const
Check whether the next 8-bit char matches 'c'.
static const std::string_view WHITESPACE_NO_NEWLINE
ASCII whitespace characters, excluding new-line.
std::optional< char32_t > TryReadUtf8()
Try to read a UTF-8 character, and then advance reader.
void Skip(size_type len)
Discard some bytes.
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.
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 StrNaturalContainsIgnoreCase(std::string_view str, std::string_view value)
Checks if a string is contained in another string with a locale-aware comparison that is case insensi...
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...
static int ICUStringContains(std::string_view str, std::string_view value, bool case_insensitive)
Search if a string is contained in another string using the current locale.
bool StrNaturalContains(std::string_view str, std::string_view value)
Checks if a string is contained in another string with a locale-aware comparison that is case sensiti...
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
std::optional< std::string_view > GetEnv(const char *variable)
Get the environment variable using std::getenv and when it is an empty string (or nullptr),...
void StrMakeValidInPlace(char *str, StringValidationSettings settings)
Scans the string for invalid characters and replaces them 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.
bool StrEqualsIgnoreCase(std::string_view str1, std::string_view str2)
Compares two string( view)s for equality, while ignoring the case of the characters.
bool StrEndsWithIgnoreCase(std::string_view str, std::string_view suffix)
Check whether the given string ends with the given suffix, 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 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.
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
std::basic_string_view< char, CaseInsensitiveCharTraits > CaseInsensitiveStringView
Case insensitive string view.
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
bool StrStartsWithIgnoreCase(std::string_view str, std::string_view prefix)
Check whether the given string starts with the given prefix, ignoring case.
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
int StrCompareIgnoreCase(std::string_view str1, std::string_view str2)
Compares two string( view)s, while ignoring the case of the characters.
static bool IsGarbageCharacter(char32_t c)
Test if a unicode character is considered garbage to be skipped.
bool StrContainsIgnoreCase(std::string_view str, std::string_view value)
Checks if a string is contained in another string, while ignoring the case of the characters.
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.
Inplace-replacement of textual and binary data.
int MacOSStringCompare(std::string_view s1, std::string_view s2)
Compares two strings using case insensitive natural sort.
int MacOSStringContains(std::string_view str, 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(std::string_view str, 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