OpenTTD Source 20251104-master-g3befbdd52f
string.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
10#include "stdafx.h"
11#include "debug.h"
12#include "core/math_func.hpp"
13#include "error_func.h"
14#include "string_func.h"
15#include "string_base.h"
16#include "core/utf8.hpp"
18
19#include "table/control_codes.h"
20
21#ifdef _WIN32
22# include "os/windows/win32.h"
23#endif
24
25#ifdef WITH_UNISCRIBE
27#endif
28
29#ifdef WITH_ICU_I18N
30/* Required by StrNaturalCompare. */
31# include <unicode/brkiter.h>
32# include <unicode/stsearch.h>
33# include <unicode/ustring.h>
34# include <unicode/utext.h>
35# include "language.h"
36# include "gfx_func.h"
37#endif /* WITH_ICU_I18N */
38
39#if defined(WITH_COCOA)
40# include "os/macosx/string_osx.h"
41#endif
42
43#include "safeguards.h"
44
45
57void strecpy(std::span<char> dst, std::string_view src)
58{
59 /* Ensure source string fits with NUL terminator; dst must be at least 1 character longer than 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");
63#else /* STRGEN || SETTINGSGEN */
64 Debug(misc, 0, "String too long for destination buffer");
65 src = src.substr(0, std::size(dst) - 1U);
66#endif /* STRGEN || SETTINGSGEN */
67 }
68
69 auto it = std::copy(std::begin(src), std::end(src), std::begin(dst));
70 *it = '\0';
71}
72
78std::string FormatArrayAsHex(std::span<const uint8_t> data)
79{
80 std::string str;
81 str.reserve(data.size() * 2 + 1);
82
83 for (auto b : data) {
84 format_append(str, "{:02X}", b);
85 }
86
87 return str;
88}
89
95static bool IsSccEncodedCode(char32_t c)
96{
97 switch (c) {
98 case SCC_RECORD_SEPARATOR:
99 case SCC_ENCODED:
103 return true;
104
105 default:
106 return false;
107 }
108}
109
119template <class Builder>
120static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
121{
122 /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
123 while (consumer.AnyBytesLeft()) {
124 auto c = consumer.TryReadUtf8();
125 if (!c.has_value()) {
126 /* Maybe the next byte is still a valid character? */
127 consumer.Skip(1);
128 continue;
129 }
130 if (*c == 0) break;
131
132 if ((IsPrintable(*c) && (*c < SCC_SPRITE_START || *c > SCC_SPRITE_END)) ||
134 (settings.Test(StringValidationSetting::AllowNewline) && *c == '\n')) {
135 builder.PutUtf8(*c);
136 } else if (settings.Test(StringValidationSetting::AllowNewline) && *c == '\r' && consumer.PeekCharIf('\n')) {
137 /* Skip \r, if followed by \n */
138 /* continue */
139 } else if (settings.Test(StringValidationSetting::ReplaceTabCrNlWithSpace) && (*c == '\r' || *c == '\n' || *c == '\t')) {
140 /* Replace the tab, carriage return or newline with a space. */
141 builder.PutChar(' ');
143 /* Replace the undesirable character with a question mark */
144 builder.PutChar('?');
145 }
146 }
147
148 /* String termination, if needed, is left to the caller of this function. */
149}
150
159{
160 InPlaceReplacement inplace(std::span(str, strlen(str)));
161 StrMakeValid(inplace.builder, inplace.consumer, settings);
162 /* Add NUL terminator, if we ended up with less bytes than before */
163 if (inplace.builder.AnyBytesUnused()) inplace.builder.PutChar('\0');
164}
165
174{
175 if (str.empty()) return;
176
177 InPlaceReplacement inplace(std::span(str.data(), str.size()));
178 StrMakeValid(inplace.builder, inplace.consumer, settings);
179 str.erase(inplace.builder.GetBytesWritten(), std::string::npos);
180}
181
189std::string StrMakeValid(std::string_view str, StringValidationSettings settings)
190{
191 std::string result;
192 StringBuilder builder(result);
193 StringConsumer consumer(str);
194 StrMakeValid(builder, consumer, settings);
195 return result;
196}
197
206bool StrValid(std::span<const char> str)
207{
208 /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
209 StringConsumer consumer(str);
210 while (consumer.AnyBytesLeft()) {
211 auto c = consumer.TryReadUtf8();
212 if (!c.has_value()) return false; // invalid codepoint
213 if (*c == 0) return true; // NUL termination
214 if (!IsPrintable(*c) || (*c >= SCC_SPRITE_START && *c <= SCC_SPRITE_END)) {
215 return false;
216 }
217 }
218
219 return false; // missing NUL termination
220}
221
229void StrTrimInPlace(std::string &str)
230{
231 size_t first_pos = str.find_first_not_of(StringConsumer::WHITESPACE_NO_NEWLINE);
232 if (first_pos == std::string::npos) {
233 str.clear();
234 return;
235 }
236 str.erase(0, first_pos);
237
238 size_t last_pos = str.find_last_not_of(StringConsumer::WHITESPACE_NO_NEWLINE);
239 str.erase(last_pos + 1);
240}
241
242std::string_view StrTrimView(std::string_view str, std::string_view characters_to_trim)
243{
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{};
247 }
248 size_t last_pos = str.find_last_not_of(characters_to_trim);
249 return str.substr(first_pos, last_pos - first_pos + 1);
250}
251
258bool StrStartsWithIgnoreCase(std::string_view str, std::string_view prefix)
259{
260 if (str.size() < prefix.size()) return false;
261 return StrEqualsIgnoreCase(str.substr(0, prefix.size()), prefix);
262}
263
265struct CaseInsensitiveCharTraits : public std::char_traits<char> {
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); }
269
270 static int compare(const char *s1, const char *s2, size_t n)
271 {
272 while (n-- != 0) {
273 if (toupper(*s1) < toupper(*s2)) return -1;
274 if (toupper(*s1) > toupper(*s2)) return 1;
275 ++s1; ++s2;
276 }
277 return 0;
278 }
279
280 static const char *find(const char *s, size_t n, char a)
281 {
282 for (; n > 0; --n, ++s) {
283 if (toupper(*s) == toupper(a)) return s;
284 }
285 return nullptr;
286 }
287};
288
290typedef std::basic_string_view<char, CaseInsensitiveCharTraits> CaseInsensitiveStringView;
291
298bool StrEndsWithIgnoreCase(std::string_view str, std::string_view suffix)
299{
300 if (str.size() < suffix.size()) return false;
301 return StrEqualsIgnoreCase(str.substr(str.size() - suffix.size()), suffix);
302}
303
311int StrCompareIgnoreCase(std::string_view str1, std::string_view str2)
312{
313 CaseInsensitiveStringView ci_str1{ str1.data(), str1.size() };
314 CaseInsensitiveStringView ci_str2{ str2.data(), str2.size() };
315 return ci_str1.compare(ci_str2);
316}
317
324bool StrEqualsIgnoreCase(std::string_view str1, std::string_view str2)
325{
326 if (str1.size() != str2.size()) return false;
327 return StrCompareIgnoreCase(str1, str2) == 0;
328}
329
337bool StrContainsIgnoreCase(std::string_view str, std::string_view value)
338{
339 CaseInsensitiveStringView ci_str{ str.data(), str.size() };
340 CaseInsensitiveStringView ci_value{ value.data(), value.size() };
341 return ci_str.find(ci_value) != ci_str.npos;
342}
343
350size_t Utf8StringLength(std::string_view str)
351{
352 Utf8View view(str);
353 return std::distance(view.begin(), view.end());
354}
355
356bool strtolower(std::string &str, std::string::size_type offs)
357{
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;
362 *ch = new_ch;
363 }
364 return changed;
365}
366
374bool IsValidChar(char32_t key, CharSetFilter afilter)
375{
376 switch (afilter) {
377 case CS_ALPHANUMERAL: return IsPrintable(key);
378 case CS_NUMERAL: return (key >= '0' && key <= '9');
379 case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' ';
380 case CS_NUMERAL_SIGNED: return (key >= '0' && key <= '9') || key == '-';
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();
384 }
385}
386
392static bool IsGarbageCharacter(char32_t c)
393{
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;
399
400 return true;
401}
402
411static std::string_view SkipGarbage(std::string_view str)
412{
413 Utf8View view(str);
414 auto it = view.begin();
415 const auto end = view.end();
416 while (it != end && IsGarbageCharacter(*it)) ++it;
417 return str.substr(it.GetByteOffset());
418}
419
428int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
429{
430 if (ignore_garbage_at_front) {
431 s1 = SkipGarbage(s1);
432 s2 = SkipGarbage(s2);
433 }
434
435#ifdef WITH_ICU_I18N
436 if (_current_collator) {
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;
440 }
441#endif /* WITH_ICU_I18N */
442
443#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
444 int res = OTTDStringCompare(s1, s2);
445 if (res != 0) return res - 2; // Convert to normal C return values.
446#endif
447
448#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
449 int res = MacOSStringCompare(s1, s2);
450 if (res != 0) return res - 2; // Convert to normal C return values.
451#endif
452
453 /* Do a normal comparison if ICU is missing or if we cannot create a collator. */
454 return StrCompareIgnoreCase(s1, s2);
455}
456
457#ifdef WITH_ICU_I18N
458
467static int ICUStringContains(std::string_view str, std::string_view value, bool case_insensitive)
468{
469 if (_current_collator) {
470 std::unique_ptr<icu::RuleBasedCollator> coll(dynamic_cast<icu::RuleBasedCollator *>(_current_collator->clone()));
471 if (coll) {
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);
475
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;
482 }
483 }
484 }
485
486 return -1;
487}
488#endif /* WITH_ICU_I18N */
489
497[[nodiscard]] bool StrNaturalContains(std::string_view str, std::string_view value)
498{
499#ifdef WITH_ICU_I18N
500 int res_u = ICUStringContains(str, value, false);
501 if (res_u >= 0) return res_u > 0;
502#endif /* WITH_ICU_I18N */
503
504#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
505 int res = Win32StringContains(str, value, false);
506 if (res >= 0) return res > 0;
507#endif
508
509#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
510 int res = MacOSStringContains(str, value, false);
511 if (res >= 0) return res > 0;
512#endif
513
514 return str.find(value) != std::string_view::npos;
515}
516
524[[nodiscard]] bool StrNaturalContainsIgnoreCase(std::string_view str, std::string_view value)
525{
526#ifdef WITH_ICU_I18N
527 int res_u = ICUStringContains(str, value, true);
528 if (res_u >= 0) return res_u > 0;
529#endif /* WITH_ICU_I18N */
530
531#if defined(_WIN32) && !defined(STRGEN) && !defined(SETTINGSGEN)
532 int res = Win32StringContains(str, value, true);
533 if (res >= 0) return res > 0;
534#endif
535
536#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
537 int res = MacOSStringContains(str, value, true);
538 if (res >= 0) return res > 0;
539#endif
540
541 CaseInsensitiveStringView ci_str{ str.data(), str.size() };
542 CaseInsensitiveStringView ci_value{ value.data(), value.size() };
543 return ci_str.find(ci_value) != CaseInsensitiveStringView::npos;
544}
545
552static int ConvertHexNibbleToByte(char c)
553{
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';
557 return -1;
558}
559
571bool ConvertHexToBytes(std::string_view hex, std::span<uint8_t> bytes)
572{
573 if (bytes.size() != hex.size() / 2) {
574 return false;
575 }
576
577 /* Hex-string lengths are always divisible by 2. */
578 if (hex.size() % 2 != 0) {
579 return false;
580 }
581
582 for (size_t i = 0; i < hex.size() / 2; i++) {
583 auto hi = ConvertHexNibbleToByte(hex[i * 2]);
584 auto lo = ConvertHexNibbleToByte(hex[i * 2 + 1]);
585
586 if (hi < 0 || lo < 0) {
587 return false;
588 }
589
590 bytes[i] = (hi << 4) | lo;
591 }
592
593 return true;
594}
595
596#ifdef WITH_UNISCRIBE
597
598/* static */ std::unique_ptr<StringIterator> StringIterator::Create()
599{
600 return std::make_unique<UniscribeStringIterator>();
601}
602
603#elif defined(WITH_ICU_I18N)
604
607{
608 std::unique_ptr<icu::BreakIterator> char_itr;
609 std::unique_ptr<icu::BreakIterator> word_itr;
610
611 std::vector<UChar> utf16_str;
612 std::vector<size_t> utf16_to_utf8;
613
614public:
616 {
617 UErrorCode status = U_ZERO_ERROR;
618 auto locale = icu::Locale(_current_language != nullptr ? _current_language->isocode : "en");
619 this->char_itr.reset(icu::BreakIterator::createCharacterInstance(locale, status));
620 this->word_itr.reset(icu::BreakIterator::createWordInstance(locale, status));
621
622 this->utf16_str.push_back('\0');
623 this->utf16_to_utf8.push_back(0);
624 }
625
626 ~IcuStringIterator() override = default;
627
628 void SetString(std::string_view s) override
629 {
630 /* Unfortunately current ICU versions only provide rudimentary support
631 * for word break iterators (especially for CJK languages) in combination
632 * with UTF-8 input. As a work around we have to convert the input to
633 * UTF-16 and create a mapping back to UTF-8 character indices. */
634 this->utf16_str.clear();
635 this->utf16_to_utf8.clear();
636
637 Utf8View view(s);
638 for (auto it = view.begin(), end = view.end(); it != end; ++it) {
639 size_t idx = it.GetByteOffset();
640 char32_t c = *it;
641 if (c < 0x10000) {
642 this->utf16_str.push_back((UChar)c);
643 } else {
644 /* Make a surrogate pair. */
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);
648 }
649 this->utf16_to_utf8.push_back(idx);
650 }
651 this->utf16_str.push_back('\0');
652 this->utf16_to_utf8.push_back(s.size());
653
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();
661 }
662
663 size_t SetCurPosition(size_t pos) override
664 {
665 /* Convert incoming position to an UTF-16 string index. */
666 uint utf16_pos = 0;
667 for (uint i = 0; i < this->utf16_to_utf8.size(); i++) {
668 if (this->utf16_to_utf8[i] == pos) {
669 utf16_pos = i;
670 break;
671 }
672 }
673
674 /* isBoundary has the documented side-effect of setting the current
675 * position to the first valid boundary equal to or greater than
676 * the passed value. */
677 this->char_itr->isBoundary(utf16_pos);
678 return this->utf16_to_utf8[this->char_itr->current()];
679 }
680
681 size_t Next(IterType what) override
682 {
683 int32_t pos;
684 switch (what) {
685 case ITER_CHARACTER:
686 pos = this->char_itr->next();
687 break;
688
689 case ITER_WORD:
690 pos = this->word_itr->following(this->char_itr->current());
691 /* The ICU word iterator considers both the start and the end of a word a valid
692 * break point, but we only want word starts. Move to the next location in
693 * case the new position points to whitespace. */
694 while (pos != icu::BreakIterator::DONE &&
695 IsWhitespace(Utf16DecodeChar((const uint16_t *)&this->utf16_str[pos]))) {
696 int32_t new_pos = this->word_itr->next();
697 /* Don't set it to DONE if it was valid before. Otherwise we'll return END
698 * even though the iterator wasn't at the end of the string before. */
699 if (new_pos == icu::BreakIterator::DONE) break;
700 pos = new_pos;
701 }
702
703 this->char_itr->isBoundary(pos);
704 break;
705
706 default:
707 NOT_REACHED();
708 }
709
710 return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
711 }
712
713 size_t Prev(IterType what) override
714 {
715 int32_t pos;
716 switch (what) {
717 case ITER_CHARACTER:
718 pos = this->char_itr->previous();
719 break;
720
721 case ITER_WORD:
722 pos = this->word_itr->preceding(this->char_itr->current());
723 /* The ICU word iterator considers both the start and the end of a word a valid
724 * break point, but we only want word starts. Move to the previous location in
725 * case the new position points to whitespace. */
726 while (pos != icu::BreakIterator::DONE &&
727 IsWhitespace(Utf16DecodeChar((const uint16_t *)&this->utf16_str[pos]))) {
728 int32_t new_pos = this->word_itr->previous();
729 /* Don't set it to DONE if it was valid before. Otherwise we'll return END
730 * even though the iterator wasn't at the start of the string before. */
731 if (new_pos == icu::BreakIterator::DONE) break;
732 pos = new_pos;
733 }
734
735 this->char_itr->isBoundary(pos);
736 break;
737
738 default:
739 NOT_REACHED();
740 }
741
742 return pos == icu::BreakIterator::DONE ? END : this->utf16_to_utf8[pos];
743 }
744};
745
746/* static */ std::unique_ptr<StringIterator> StringIterator::Create()
747{
748 return std::make_unique<IcuStringIterator>();
749}
750
751#else
752
754class DefaultStringIterator : public StringIterator
755{
756 Utf8View string;
757 Utf8View::iterator cur_pos; //< Current iteration position.
758
759public:
760 void SetString(std::string_view s) override
761 {
762 this->string = s;
763 this->cur_pos = this->string.begin();
764 }
765
766 size_t SetCurPosition(size_t pos) override
767 {
768 this->cur_pos = this->string.GetIterAtByte(pos);
769 return this->cur_pos.GetByteOffset();
770 }
771
772 size_t Next(IterType what) override
773 {
774 const auto end = this->string.end();
775 /* Already at the end? */
776 if (this->cur_pos >= end) return END;
777
778 switch (what) {
779 case ITER_CHARACTER:
780 ++this->cur_pos;
781 return this->cur_pos.GetByteOffset();
782
783 case ITER_WORD:
784 /* Consume current word. */
785 while (this->cur_pos != end && !IsWhitespace(*this->cur_pos)) {
786 ++this->cur_pos;
787 }
788 /* Consume whitespace to the next word. */
789 while (this->cur_pos != end && IsWhitespace(*this->cur_pos)) {
790 ++this->cur_pos;
791 }
792 return this->cur_pos.GetByteOffset();
793
794 default:
795 NOT_REACHED();
796 }
797
798 return END;
799 }
800
801 size_t Prev(IterType what) override
802 {
803 const auto begin = this->string.begin();
804 /* Already at the beginning? */
805 if (this->cur_pos == begin) return END;
806
807 switch (what) {
808 case ITER_CHARACTER:
809 --this->cur_pos;
810 return this->cur_pos.GetByteOffset();
811
812 case ITER_WORD:
813 /* Consume preceding whitespace. */
814 do {
815 --this->cur_pos;
816 } while (this->cur_pos != begin && IsWhitespace(*this->cur_pos));
817 /* Consume preceding word. */
818 while (this->cur_pos != begin && !IsWhitespace(*this->cur_pos)) {
819 --this->cur_pos;
820 }
821 /* Move caret back to the beginning of the word. */
822 if (IsWhitespace(*this->cur_pos)) ++this->cur_pos;
823 return this->cur_pos.GetByteOffset();
824
825 default:
826 NOT_REACHED();
827 }
828
829 return END;
830 }
831};
832
833#if defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN)
834/* static */ std::unique_ptr<StringIterator> StringIterator::Create()
835{
836 std::unique_ptr<StringIterator> i = OSXStringIterator::Create();
837 if (i != nullptr) return i;
838
839 return std::make_unique<DefaultStringIterator>();
840}
841#else
842/* static */ std::unique_ptr<StringIterator> StringIterator::Create()
843{
844 return std::make_unique<DefaultStringIterator>();
845}
846#endif /* defined(WITH_COCOA) && !defined(STRGEN) && !defined(SETTINGSGEN) */
847
848#endif
849
855std::optional<std::string_view> GetEnv(const char *variable)
856{
857 auto val = std::getenv(variable);
858 if (val == nullptr || *val == '\0') return std::nullopt;
859 return val;
860}
void PutChar(char c)
Append 8-bit char.
Enum-as-bit-set wrapper.
String iterator using ICU as a backend.
Definition string.cpp:607
size_t Prev(IterType what) override
Move the cursor back by one iteration unit.
Definition string.cpp:713
std::unique_ptr< icu::BreakIterator > word_itr
ICU iterator for words.
Definition string.cpp:609
size_t Next(IterType what) override
Advance the cursor by one iteration unit.
Definition string.cpp:681
std::vector< size_t > utf16_to_utf8
Mapping from UTF-16 code point position to index in the UTF-8 source string.
Definition string.cpp:612
std::unique_ptr< icu::BreakIterator > char_itr
ICU iterator for characters.
Definition string.cpp:608
void SetString(std::string_view s) override
Set a new iteration string.
Definition string.cpp:628
size_t SetCurPosition(size_t pos) override
Change the current string cursor.
Definition string.cpp:663
std::vector< UChar > utf16_str
UTF-16 copy of the string.
Definition string.cpp:611
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.
Definition string_base.h:14
static const size_t END
Sentinel to indicate end-of-iteration.
Definition string_base.h:23
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.
Definition string.cpp:746
IterType
Type of the iterator.
Definition string_base.h:17
@ ITER_WORD
Iterate over words.
Definition string_base.h:19
@ ITER_CHARACTER
Iterate over characters (or more exactly grapheme clusters).
Definition string_base.h:18
virtual void SetString(std::string_view s)=0
Set a new iteration string.
Bidirectional input iterator over codepoints.
Definition utf8.hpp:43
Constant span of UTF-8 encoded data.
Definition utf8.hpp:30
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.
Definition debug.h:37
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.
Definition strings.cpp:54
std::unique_ptr< icu::Collator > _current_collator
Collator for the language currently in use.
Definition strings.cpp:59
Integer math functions.
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.
Definition string.cpp:571
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...
Definition string.cpp:524
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...
Definition string.cpp:350
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.
Definition string.cpp:467
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...
Definition string.cpp:497
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
Definition string.cpp:374
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),...
Definition string.cpp:855
void StrMakeValidInPlace(char *str, StringValidationSettings settings)
Scans the string for invalid characters and replaces them with a question mark '?' (if not ignored).
Definition string.cpp:158
void strecpy(std::span< char > dst, std::string_view src)
Copies characters from one buffer to another.
Definition string.cpp:57
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:78
bool StrEqualsIgnoreCase(std::string_view str1, std::string_view str2)
Compares two string( view)s for equality, while ignoring the case of the characters.
Definition string.cpp:324
bool StrEndsWithIgnoreCase(std::string_view str, std::string_view suffix)
Check whether the given string ends with the given suffix, ignoring case.
Definition string.cpp:298
bool StrValid(std::span< const char > str)
Checks whether the given string is valid, i.e.
Definition string.cpp:206
static int ConvertHexNibbleToByte(char c)
Convert a single hex-nibble to a byte.
Definition string.cpp:552
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.
Definition string.cpp:411
static bool IsSccEncodedCode(char32_t c)
Test if a character is (only) part of an encoded string.
Definition string.cpp:95
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
Definition string.cpp:428
std::basic_string_view< char, CaseInsensitiveCharTraits > CaseInsensitiveStringView
Case insensitive string view.
Definition string.cpp:290
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
Definition string.cpp:229
bool StrStartsWithIgnoreCase(std::string_view str, std::string_view prefix)
Check whether the given string starts with the given prefix, ignoring case.
Definition string.cpp:258
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Definition string.cpp:120
int StrCompareIgnoreCase(std::string_view str1, std::string_view str2)
Compares two string( view)s, while ignoring the case of the characters.
Definition string.cpp:311
static bool IsGarbageCharacter(char32_t c)
Test if a unicode character is considered garbage to be skipped.
Definition string.cpp:392
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.
Definition string.cpp:337
Functions related to low-level strings.
char32_t Utf16DecodeChar(const uint16_t *c)
Decode an UTF-16 character.
Definition string_func.h:97
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.
Definition string_type.h:24
@ CS_NUMERAL_SPACE
Only numbers and spaces.
Definition string_type.h:27
@ CS_HEXADECIMAL
Only hexadecimal characters.
Definition string_type.h:30
@ CS_NUMERAL
Only numeric ones.
Definition string_type.h:26
@ CS_NUMERAL_SIGNED
Only numbers and '-' for negative values.
Definition string_type.h:28
@ CS_ALPHA
Only alphabetic values.
Definition string_type.h:29
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
Functions related to laying out text on Win32.
Case insensitive implementation of the standard character type traits.
Definition string.cpp:265
char isocode[16]
the ISO code for the language (not country code)
Definition language.h:31
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.
Definition win32.cpp:480
declarations of functions for MS windows systems