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