Debian Codegraph @

core/string/ustring.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* ustring.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "ustring.h"
32
33 STATIC_ASSERT_INCOMPLETE_TYPE(class, Array);
34 STATIC_ASSERT_INCOMPLETE_TYPE(class, Dictionary);
35 STATIC_ASSERT_INCOMPLETE_TYPE(class, Object);
36
37 #include "core/crypto/crypto_core.h"
38 #include "core/io/ip_address.h"
39 #include "core/math/color.h"
40 #include "core/math/math_funcs.h"
41 #include "core/object/object.h"
42 #include "core/os/memory.h"
43 #include "core/os/os.h"
44 #include "core/string/print_string.h"
45 #include "core/string/string_name.h"
46 #include "core/string/translation_server.h"
47 #include "core/string/ucaps.h"
48 #include "core/variant/variant.h"
49 #include "core/version_generated.gen.h"
50
51 #include "thirdparty/grisu2/grisu2.h"
52
53 #ifdef _MSC_VER
54 #define _CRT_SECURE_NO_WARNINGS // to disable build-time warning which suggested to use strcpy_s instead strcpy
55 #endif
56
57 #if defined(MINGW_ENABLED) || defined(_MSC_VER)
58 #define snprintf _snprintf_s
59 #endif
60
61 static const int MAX_DECIMALS = 32;
62
63 static _FORCE_INLINE_ char32_t lower_case(char32_t c) {
64 return (is_ascii_upper_case(c) ? (c + ('a' - 'A')) : c);
65 }
66
67 // Case-insensitive version of are_spans_equal
68 template <typename T1, typename T2>
69 static bool strings_equal_lower(const T1 *p_lhs_begin, const T2 *p_rhs_begin, size_t p_len) {
70 for (size_t i = 0; i < p_len; ++i) {
71 if (_find_lower(p_lhs_begin[i]) != _find_lower(p_rhs_begin[i])) {
72 return false;
73 }
74 }
75 return true;
76 }
77
78 Error String::parse_url(String &r_scheme, String &r_host, int &r_port, String &r_path, String &r_fragment) const {
79 // Splits the URL into scheme, host, port, path, fragment. Strip credentials when present.
80 String base = *this;
81 r_scheme = "";
82 r_host = "";
83 r_port = 0;
84 r_path = "";
85 r_fragment = "";
86
87 int pos = base.find("://");
88 // Scheme
89 if (pos != -1) {
90 bool is_scheme_valid = true;
91 for (int i = 0; i < pos; i++) {
92 if (!is_ascii_alphanumeric_char(base[i]) && base[i] != '+' && base[i] != '-' && base[i] != '.') {
93 is_scheme_valid = false;
94 break;
95 }
96 }
97 if (is_scheme_valid) {
98 r_scheme = base.substr(0, pos + 3).to_lower();
99 base = base.substr(pos + 3);
100 }
101 }
102 pos = base.find_char('#');
103 // Fragment
104 if (pos != -1) {
105 r_fragment = base.substr(pos + 1);
106 base = base.substr(0, pos);
107 }
108 pos = base.find_char('/');
109 // Path
110 if (pos != -1) {
111 r_path = base.substr(pos);
112 base = base.substr(0, pos);
113 }
114 // Host
115 pos = base.find_char('@');
116 if (pos != -1) {
117 // Strip credentials
118 base = base.substr(pos + 1);
119 }
120 if (base.begins_with("[")) {
121 // Literal IPv6
122 pos = base.rfind_char(']');
123 if (pos == -1) {
124 return ERR_INVALID_PARAMETER;
125 }
126 r_host = base.substr(1, pos - 1);
127 base = base.substr(pos + 1);
128 } else {
129 // Anything else
130 if (base.get_slice_count(":") > 2) {
131 return ERR_INVALID_PARAMETER;
132 }
133 pos = base.rfind_char(':');
134 if (pos == -1) {
135 r_host = base;
136 base = "";
137 } else {
138 r_host = base.substr(0, pos);
139 base = base.substr(pos);
140 }
141 }
142 if (r_host.is_empty()) {
143 return ERR_INVALID_PARAMETER;
144 }
145 r_host = r_host.to_lower();
146 // Port
147 if (base.begins_with(":")) {
148 base = base.substr(1);
149 if (!base.is_valid_int()) {
150 return ERR_INVALID_PARAMETER;
151 }
152 r_port = base.to_int();
153 if (r_port < 1 || r_port > 65535) {
154 return ERR_INVALID_PARAMETER;
155 }
156 }
157 return OK;
158 }
159
160 void String::append_latin1(const Span<char> &p_cstr) {
161 if (p_cstr.is_empty()) {
162 return;
163 }
164
165 const int prev_length = length();
166 resize_uninitialized(prev_length + p_cstr.size() + 1); // include 0
167
168 const char *src = p_cstr.ptr();
169 const char *end = src + p_cstr.size();
170 char32_t *dst = ptrw() + prev_length;
171
172 for (; src < end; ++src, ++dst) {
173 // If char is int8_t, a set sign bit will be reinterpreted as 256 - val implicitly.
174 if (unlikely(*src == '\0')) {
175 // NUL in string is allowed by the unicode standard, but unsupported in our implementation right now.
176 print_unicode_error("Unexpected NUL character", true);
177 *dst = _replacement_char;
178 } else {
179 *dst = static_cast<uint8_t>(*src);
180 }
181 }
182 *dst = 0;
183 }
184
185 Error String::append_utf32(const Span<char32_t> &p_cstr) {
186 if (p_cstr.is_empty()) {
187 return OK;
188 }
189
190 Error error = OK;
191
192 const int prev_length = length();
193 resize_uninitialized(prev_length + p_cstr.size() + 1);
194 const char32_t *src = p_cstr.ptr();
195 const char32_t *end = p_cstr.ptr() + p_cstr.size();
196 char32_t *dst = ptrw() + prev_length;
197
198 // Copy the string, and check for UTF-32 problems.
199 for (; src < end; ++src, ++dst) {
200 const char32_t chr = *src;
201 if (unlikely(chr == U'\0')) {
202 // NUL in string is allowed by the unicode standard, but unsupported in our implementation right now.
203 print_unicode_error("Unexpected NUL character", true);
204 *dst = _replacement_char;
205 error = ERR_PARSE_ERROR;
206 } else if (unlikely((chr & 0xfffff800) == 0xd800)) {
207 print_unicode_error(vformat("Unpaired surrogate (%x)", (uint32_t)chr), true);
208 *dst = _replacement_char;
209 error = ERR_PARSE_ERROR;
210 } else if (unlikely(chr > 0x10ffff)) {
211 print_unicode_error(vformat("Invalid unicode codepoint (%x)", (uint32_t)chr), true);
212 *dst = _replacement_char;
213 error = ERR_PARSE_ERROR;
214 } else {
215 *dst = chr;
216 }
217 }
218 *dst = 0;
219 return error;
220 }
221
222 void String::append_utf32_unchecked(const Span<char32_t> &p_span) {
223 const int prev_length = length();
224 resize_uninitialized(prev_length + p_span.size() + 1); // + 1 for \0
225 char32_t *dst = ptrw() + prev_length;
226 memcpy(dst, p_span.ptr(), p_span.size() * sizeof(char32_t));
227 *(dst + p_span.size()) = _null;
228 }
229
230 String String::operator+(const String &p_str) const {
231 String res = *this;
232 res += p_str;
233 return res;
234 }
235
236 String String::operator+(const char *p_str) const {
237 String res = *this;
238 res += p_str;
239 return res;
240 }
241
242 String String::operator+(const wchar_t *p_str) const {
243 String res = *this;
244 res += p_str;
245 return res;
246 }
247
248 String String::operator+(const char32_t *p_str) const {
249 String res = *this;
250 res += p_str;
251 return res;
252 }
253
254 String String::operator+(char32_t p_char) const {
255 String res = *this;
256 res += p_char;
257 return res;
258 }
259
260 String operator+(const char *p_chr, const String &p_str) {
261 String tmp = p_chr;
262 tmp += p_str;
263 return tmp;
264 }
265
266 String operator+(const wchar_t *p_chr, const String &p_str) {
267 #ifdef WINDOWS_ENABLED
268 // wchar_t is 16-bit
269 String tmp = String::utf16((const char16_t *)p_chr);
270 #else
271 // wchar_t is 32-bit
272 String tmp = (const char32_t *)p_chr;
273 #endif
274 tmp += p_str;
275 return tmp;
276 }
277
278 String operator+(char32_t p_chr, const String &p_str) {
279 return (String::chr(p_chr) + p_str);
280 }
281
282 String &String::operator+=(const String &p_str) {
283 if (is_empty()) {
284 *this = p_str;
285 return *this;
286 }
287 append_utf32_unchecked(p_str);
288 return *this;
289 }
290
291 String &String::operator+=(const char *p_str) {
292 append_latin1(p_str);
293 return *this;
294 }
295
296 String &String::operator+=(const wchar_t *p_str) {
297 #ifdef WINDOWS_ENABLED
298 // wchar_t is 16-bit
299 *this += String::utf16((const char16_t *)p_str);
300 #else
301 // wchar_t is 32-bit
302 *this += String((const char32_t *)p_str);
303 #endif
304 return *this;
305 }
306
307 String &String::operator+=(const char32_t *p_str) {
308 append_utf32(Span(p_str, strlen(p_str)));
309 return *this;
310 }
311
312 String &String::operator+=(char32_t p_char) {
313 append_utf32(Span(&p_char, 1));
314 return *this;
315 }
316
317 bool String::operator==(const char *p_str) const {
318 // Compare Latin-1 encoded c-string.
319 return span() == Span(p_str, strlen(p_str)).reinterpret<uint8_t>();
320 }
321
322 bool String::operator==(const wchar_t *p_str) const {
323 #ifdef WINDOWS_ENABLED
324 // wchar_t is 16-bit, parse as UTF-16
325 return *this == String::utf16((const char16_t *)p_str);
326 #else
327 // wchar_t is 32-bit, compare char by char
328 return *this == (const char32_t *)p_str;
329 #endif
330 }
331
332 bool String::operator==(const char32_t *p_str) const {
333 // Compare UTF-32 encoded c-string.
334 return span() == Span(p_str, strlen(p_str));
335 }
336
337 bool String::operator==(const String &p_str) const {
338 return span() == p_str.span();
339 }
340
341 bool String::operator==(const Span<char32_t> &p_str_range) const {
342 return span() == p_str_range;
343 }
344
345 bool operator==(const char *p_chr, const String &p_str) {
346 return p_str == p_chr;
347 }
348
349 bool operator==(const wchar_t *p_chr, const String &p_str) {
350 #ifdef WINDOWS_ENABLED
351 // wchar_t is 16-bit
352 return p_str == String::utf16((const char16_t *)p_chr);
353 #else
354 // wchar_t is 32-bi
355 return p_str == (const char32_t *)p_chr;
356 #endif
357 }
358
359 bool operator!=(const char *p_chr, const String &p_str) {
360 return !(p_str == p_chr);
361 }
362
363 bool operator!=(const wchar_t *p_chr, const String &p_str) {
364 #ifdef WINDOWS_ENABLED
365 // wchar_t is 16-bit
366 return !(p_str == String::utf16((const char16_t *)p_chr));
367 #else
368 // wchar_t is 32-bi
369 return !(p_str == String((const char32_t *)p_chr));
370 #endif
371 }
372
373 bool String::operator!=(const char *p_str) const {
374 return (!(*this == p_str));
375 }
376
377 bool String::operator!=(const wchar_t *p_str) const {
378 return (!(*this == p_str));
379 }
380
381 bool String::operator!=(const char32_t *p_str) const {
382 return (!(*this == p_str));
383 }
384
385 bool String::operator!=(const String &p_str) const {
386 return !((*this == p_str));
387 }
388
389 bool String::operator<=(const String &p_str) const {
390 return !(p_str < *this);
391 }
392
393 bool String::operator>(const String &p_str) const {
394 return p_str < *this;
395 }
396
397 bool String::operator>=(const String &p_str) const {
398 return !(*this < p_str);
399 }
400
401 bool String::operator<(const char *p_str) const {
402 if (is_empty() && p_str[0] == 0) {
403 return false;
404 }
405 if (is_empty()) {
406 return true;
407 }
408 return str_compare(get_data(), p_str) < 0;
409 }
410
411 bool String::operator<(const wchar_t *p_str) const {
412 if (is_empty() && p_str[0] == 0) {
413 return false;
414 }
415 if (is_empty()) {
416 return true;
417 }
418
419 #ifdef WINDOWS_ENABLED
420 // wchar_t is 16-bit
421 return str_compare(get_data(), String::utf16((const char16_t *)p_str).get_data()) < 0;
422 #else
423 // wchar_t is 32-bit
424 return str_compare(get_data(), (const char32_t *)p_str) < 0;
425 #endif
426 }
427
428 bool String::operator<(const char32_t *p_str) const {
429 if (is_empty() && p_str[0] == 0) {
430 return false;
431 }
432 if (is_empty()) {
433 return true;
434 }
435
436 return str_compare(get_data(), p_str) < 0;
437 }
438
439 bool String::operator<(const String &p_str) const {
440 return operator<(p_str.get_data());
441 }
442
443 signed char String::nocasecmp_to(const String &p_str) const {
444 if (is_empty() && p_str.is_empty()) {
445 return 0;
446 }
447 if (is_empty()) {
448 return -1;
449 }
450 if (p_str.is_empty()) {
451 return 1;
452 }
453
454 const char32_t *that_str = p_str.get_data();
455 const char32_t *this_str = get_data();
456
457 while (true) {
458 if (*that_str == 0 && *this_str == 0) { // If both strings are at the end, they are equal.
459 return 0;
460 } else if (*this_str == 0) { // If at the end of this, and not of other, we are less.
461 return -1;
462 } else if (*that_str == 0) { // If at end of other, and not of this, we are greater.
463 return 1;
464 } else if (_find_upper(*this_str) < _find_upper(*that_str)) { // If current character in this is less, we are less.
465 return -1;
466 } else if (_find_upper(*this_str) > _find_upper(*that_str)) { // If current character in this is greater, we are greater.
467 return 1;
468 }
469
470 this_str++;
471 that_str++;
472 }
473 }
474
475 signed char String::casecmp_to(const String &p_str) const {
476 if (is_empty() && p_str.is_empty()) {
477 return 0;
478 }
479 if (is_empty()) {
480 return -1;
481 }
482 if (p_str.is_empty()) {
483 return 1;
484 }
485
486 const char32_t *that_str = p_str.get_data();
487 const char32_t *this_str = get_data();
488
489 while (true) {
490 if (*that_str == 0 && *this_str == 0) { // If both strings are at the end, they are equal.
491 return 0;
492 } else if (*this_str == 0) { // If at the end of this, and not of other, we are less.
493 return -1;
494 } else if (*that_str == 0) { // If at end of other, and not of this, we are greater.
495 return 1;
496 } else if (*this_str < *that_str) { // If current character in this is less, we are less.
497 return -1;
498 } else if (*this_str > *that_str) { // If current character in this is greater, we are greater.
499 return 1;
500 }
501
502 this_str++;
503 that_str++;
504 }
505 }
506
507 static _FORCE_INLINE_ signed char natural_cmp_common(const char32_t *&r_this_str, const char32_t *&r_that_str) {
508 // Keep ptrs to start of numerical sequences.
509 const char32_t *this_substr = r_this_str;
510 const char32_t *that_substr = r_that_str;
511
512 // Compare lengths of both numerical sequences, ignoring leading zeros.
513 while (is_digit(*r_this_str)) {
514 r_this_str++;
515 }
516 while (is_digit(*r_that_str)) {
517 r_that_str++;
518 }
519 while (*this_substr == '0') {
520 this_substr++;
521 }
522 while (*that_substr == '0') {
523 that_substr++;
524 }
525 int this_len = r_this_str - this_substr;
526 int that_len = r_that_str - that_substr;
527
528 if (this_len < that_len) {
529 return -1;
530 } else if (this_len > that_len) {
531 return 1;
532 }
533
534 // If lengths equal, compare lexicographically.
535 while (this_substr != r_this_str && that_substr != r_that_str) {
536 if (*this_substr < *that_substr) {
537 return -1;
538 } else if (*this_substr > *that_substr) {
539 return 1;
540 }
541 this_substr++;
542 that_substr++;
543 }
544
545 return 0;
546 }
547
548 static _FORCE_INLINE_ signed char naturalcasecmp_to_base(const char32_t *p_this_str, const char32_t *p_that_str) {
549 if (p_this_str && p_that_str) {
550 while (*p_this_str == '.' || *p_that_str == '.') {
551 if (*p_this_str++ != '.') {
552 return 1;
553 }
554 if (*p_that_str++ != '.') {
555 return -1;
556 }
557 if (!*p_that_str) {
558 return 1;
559 }
560 if (!*p_this_str) {
561 return -1;
562 }
563 }
564
565 while (*p_this_str) {
566 if (!*p_that_str) {
567 return 1;
568 } else if (is_digit(*p_this_str)) {
569 if (!is_digit(*p_that_str)) {
570 return -1;
571 }
572
573 signed char ret = natural_cmp_common(p_this_str, p_that_str);
574 if (ret) {
575 return ret;
576 }
577 } else if (is_digit(*p_that_str)) {
578 return 1;
579 } else {
580 if (*p_this_str < *p_that_str) { // If current character in this is less, we are less.
581 return -1;
582 } else if (*p_this_str > *p_that_str) { // If current character in this is greater, we are greater.
583 return 1;
584 }
585
586 p_this_str++;
587 p_that_str++;
588 }
589 }
590 if (*p_that_str) {
591 return -1;
592 }
593 }
594
595 return 0;
596 }
597
598 signed char String::naturalcasecmp_to(const String &p_str) const {
599 const char32_t *this_str = get_data();
600 const char32_t *that_str = p_str.get_data();
601
602 return naturalcasecmp_to_base(this_str, that_str);
603 }
604
605 static _FORCE_INLINE_ signed char naturalnocasecmp_to_base(const char32_t *p_this_str, const char32_t *p_that_str) {
606 if (p_this_str && p_that_str) {
607 while (*p_this_str == '.' || *p_that_str == '.') {
608 if (*p_this_str++ != '.') {
609 return 1;
610 }
611 if (*p_that_str++ != '.') {
612 return -1;
613 }
614 if (!*p_that_str) {
615 return 1;
616 }
617 if (!*p_this_str) {
618 return -1;
619 }
620 }
621
622 while (*p_this_str) {
623 if (!*p_that_str) {
624 return 1;
625 } else if (is_digit(*p_this_str)) {
626 if (!is_digit(*p_that_str)) {
627 return -1;
628 }
629
630 signed char ret = natural_cmp_common(p_this_str, p_that_str);
631 if (ret) {
632 return ret;
633 }
634 } else if (is_digit(*p_that_str)) {
635 return 1;
636 } else {
637 if (_find_upper(*p_this_str) < _find_upper(*p_that_str)) { // If current character in this is less, we are less.
638 return -1;
639 } else if (_find_upper(*p_this_str) > _find_upper(*p_that_str)) { // If current character in this is greater, we are greater.
640 return 1;
641 }
642
643 p_this_str++;
644 p_that_str++;
645 }
646 }
647 if (*p_that_str) {
648 return -1;
649 }
650 }
651
652 return 0;
653 }
654
655 signed char String::naturalnocasecmp_to(const String &p_str) const {
656 const char32_t *this_str = get_data();
657 const char32_t *that_str = p_str.get_data();
658
659 return naturalnocasecmp_to_base(this_str, that_str);
660 }
661
662 static _FORCE_INLINE_ signed char file_cmp_common(const char32_t *&r_this_str, const char32_t *&r_that_str) {
663 // Compare leading `_` sequences.
664 while ((*r_this_str == '_' && *r_that_str) || (*r_this_str && *r_that_str == '_')) {
665 // Sort `_` lower than everything except `.`
666 if (*r_this_str != '_') {
667 return *r_this_str == '.' ? -1 : 1;
668 } else if (*r_that_str != '_') {
669 return *r_that_str == '.' ? 1 : -1;
670 }
671 r_this_str++;
672 r_that_str++;
673 }
674
675 return 0;
676 }
677
678 signed char String::filecasecmp_to(const String &p_str) const {
679 const char32_t *this_str = get_data();
680 const char32_t *that_str = p_str.get_data();
681
682 signed char ret = file_cmp_common(this_str, that_str);
683 if (ret) {
684 return ret;
685 }
686
687 return naturalcasecmp_to_base(this_str, that_str);
688 }
689
690 signed char String::filenocasecmp_to(const String &p_str) const {
691 const char32_t *this_str = get_data();
692 const char32_t *that_str = p_str.get_data();
693
694 signed char ret = file_cmp_common(this_str, that_str);
695 if (ret) {
696 return ret;
697 }
698
699 return naturalnocasecmp_to_base(this_str, that_str);
700 }
701
702 String String::_separate_compound_words() const {
703 if (length() == 0) {
704 return *this;
705 }
706
707 const char32_t *cstr = get_data();
708 int start_index = 0;
709 String new_string;
710
711 bool is_prev_upper = is_unicode_upper_case(cstr[0]);
712 bool is_prev_lower = is_unicode_lower_case(cstr[0]);
713 bool is_prev_digit = is_digit(cstr[0]);
714
715 for (int i = 1; i < length(); i++) {
716 const bool is_curr_upper = is_unicode_upper_case(cstr[i]);
717 const bool is_curr_lower = is_unicode_lower_case(cstr[i]);
718 const bool is_curr_digit = is_digit(cstr[i]);
719
720 bool is_next_lower = false;
721 if (i + 1 < length()) {
722 is_next_lower = is_unicode_lower_case(cstr[i + 1]);
723 }
724
725 const bool cond_a = is_prev_lower && is_curr_upper; // aA
726 const bool cond_b = (is_prev_upper || is_prev_digit) && is_curr_upper && is_next_lower; // AAa, 2Aa
727 const bool cond_c = is_prev_digit && is_curr_lower && is_next_lower; // 2aa
728 const bool cond_d = (is_prev_upper || is_prev_lower) && is_curr_digit; // A2, a2
729
730 if (cond_a || cond_b || cond_c || cond_d) {
731 new_string += substr(start_index, i - start_index) + " ";
732 start_index = i;
733 }
734
735 is_prev_upper = is_curr_upper;
736 is_prev_lower = is_curr_lower;
737 is_prev_digit = is_curr_digit;
738 }
739
740 new_string += substr(start_index, size() - start_index);
741
742 for (int i = 0; i < new_string.size(); i++) {
743 const bool whitespace = is_whitespace(new_string[i]);
744 const bool underscore = is_underscore(new_string[i]);
745 const bool hyphen = is_hyphen(new_string[i]);
746
747 if (whitespace || underscore || hyphen) {
748 new_string[i] = ' ';
749 }
750 }
751
752 return new_string.to_lower();
753 }
754
755 String String::capitalize() const {
756 String words = _separate_compound_words().strip_edges();
757 String ret;
758 for (int i = 0; i < words.get_slice_count(" "); i++) {
759 String slice = words.get_slicec(' ', i);
760 if (slice.length() > 0) {
761 slice[0] = _find_upper(slice[0]);
762 if (i > 0) {
763 ret += " ";
764 }
765 ret += slice;
766 }
767 }
768 return ret;
769 }
770
771 String String::to_camel_case() const {
772 String words = _separate_compound_words().strip_edges();
773 String ret;
774 for (int i = 0; i < words.get_slice_count(" "); i++) {
775 String slice = words.get_slicec(' ', i);
776 if (slice.length() > 0) {
777 if (i == 0) {
778 slice[0] = _find_lower(slice[0]);
779 } else {
780 slice[0] = _find_upper(slice[0]);
781 }
782 ret += slice;
783 }
784 }
785 return ret;
786 }
787
788 String String::to_pascal_case() const {
789 String words = _separate_compound_words().strip_edges();
790 String ret;
791 for (int i = 0; i < words.get_slice_count(" "); i++) {
792 String slice = words.get_slicec(' ', i);
793 if (slice.length() > 0) {
794 slice[0] = _find_upper(slice[0]);
795 ret += slice;
796 }
797 }
798 return ret;
799 }
800
801 String String::to_snake_case() const {
802 return _separate_compound_words().replace_char(' ', '_');
803 }
804
805 String String::to_kebab_case() const {
806 return _separate_compound_words().replace_char(' ', '-');
807 }
808
809 String String::get_with_code_lines() const {
810 const Vector<String> lines = split("\n");
811 String ret;
812 for (int i = 0; i < lines.size(); i++) {
813 if (i > 0) {
814 ret += "\n";
815 }
816 ret += vformat("%4d | %s", i + 1, lines[i]);
817 }
818 return ret;
819 }
820
821 int String::get_slice_count(const String &p_splitter) const {
822 if (is_empty()) {
823 return 0;
824 }
825 if (p_splitter.is_empty()) {
826 return 0;
827 }
828
829 int pos = 0;
830 int slices = 1;
831
832 while ((pos = find(p_splitter, pos)) >= 0) {
833 slices++;
834 pos += p_splitter.length();
835 }
836
837 return slices;
838 }
839
840 int String::get_slice_count(const char *p_splitter) const {
841 if (is_empty()) {
842 return 0;
843 }
844 if (p_splitter == nullptr || *p_splitter == '\0') {
845 return 0;
846 }
847
848 int pos = 0;
849 int slices = 1;
850 int splitter_length = strlen(p_splitter);
851
852 while ((pos = find(p_splitter, pos)) >= 0) {
853 slices++;
854 pos += splitter_length;
855 }
856
857 return slices;
858 }
859
860 String String::get_slice(const String &p_splitter, int p_slice) const {
861 if (is_empty() || p_splitter.is_empty()) {
862 return "";
863 }
864
865 int pos = 0;
866 int prev_pos = 0;
867 //int slices=1;
868 if (p_slice < 0) {
869 return "";
870 }
871 if (find(p_splitter) == -1) {
872 return *this;
873 }
874
875 int i = 0;
876 while (true) {
877 pos = find(p_splitter, pos);
878 if (pos == -1) {
879 pos = length(); //reached end
880 }
881
882 int from = prev_pos;
883 //int to=pos;
884
885 if (p_slice == i) {
886 return substr(from, pos - from);
887 }
888
889 if (pos == length()) { //reached end and no find
890 break;
891 }
892 pos += p_splitter.length();
893 prev_pos = pos;
894 i++;
895 }
896
897 return ""; //no find!
898 }
899
900 String String::get_slice(const char *p_splitter, int p_slice) const {
901 if (is_empty() || p_splitter == nullptr || *p_splitter == '\0') {
902 return "";
903 }
904
905 int pos = 0;
906 int prev_pos = 0;
907 //int slices=1;
908 if (p_slice < 0) {
909 return "";
910 }
911 if (find(p_splitter) == -1) {
912 return *this;
913 }
914
915 int i = 0;
916 const int splitter_length = strlen(p_splitter);
917 while (true) {
918 pos = find(p_splitter, pos);
919 if (pos == -1) {
920 pos = length(); //reached end
921 }
922
923 int from = prev_pos;
924 //int to=pos;
925
926 if (p_slice == i) {
927 return substr(from, pos - from);
928 }
929
930 if (pos == length()) { //reached end and no find
931 break;
932 }
933 pos += splitter_length;
934 prev_pos = pos;
935 i++;
936 }
937
938 return ""; //no find!
939 }
940
941 String String::get_slicec(char32_t p_splitter, int p_slice) const {
942 if (is_empty()) {
943 return String();
944 }
945
946 if (p_slice < 0) {
947 return String();
948 }
949
950 const char32_t *c = ptr();
951 int i = 0;
952 int prev = 0;
953 int count = 0;
954 while (true) {
955 if (c[i] == 0 || c[i] == p_splitter) {
956 if (p_slice == count) {
957 return substr(prev, i - prev);
958 } else if (c[i] == 0) {
959 return String();
960 } else {
961 count++;
962 prev = i + 1;
963 }
964 }
965
966 i++;
967 }
968 }
969
970 Vector<String> String::split_spaces(int p_maxsplit) const {
971 Vector<String> ret;
972 int from = 0;
973 int i = 0;
974 int len = length();
975 if (len == 0) {
976 return ret;
977 }
978
979 bool inside = false;
980
981 while (true) {
982 bool empty = operator[](i) < 33;
983
984 if (i == 0) {
985 inside = !empty;
986 }
987
988 if (!empty && !inside) {
989 inside = true;
990 from = i;
991 }
992
993 if (empty && inside) {
994 if (p_maxsplit > 0 && p_maxsplit == ret.size()) {
995 // Put rest of the string and leave cycle.
996 ret.push_back(substr(from));
997 break;
998 }
999 ret.push_back(substr(from, i - from));
1000 inside = false;
1001 }
1002
1003 if (i == len) {
1004 break;
1005 }
1006 i++;
1007 }
1008
1009 return ret;
1010 }
1011
1012 Vector<String> String::split(const String &p_splitter, bool p_allow_empty, int p_maxsplit) const {
1013 Vector<String> ret;
1014
1015 if (is_empty()) {
1016 if (p_allow_empty) {
1017 ret.push_back("");
1018 }
1019 return ret;
1020 }
1021
1022 int from = 0;
1023 int len = length();
1024
1025 while (true) {
1026 int end;
1027 if (p_splitter.is_empty()) {
1028 end = from + 1;
1029 } else {
1030 end = find(p_splitter, from);
1031 if (end < 0) {
1032 end = len;
1033 }
1034 }
1035 if (p_allow_empty || (end > from)) {
1036 if (p_maxsplit <= 0) {
1037 ret.push_back(substr(from, end - from));
1038 } else {
1039 // Put rest of the string and leave cycle.
1040 if (p_maxsplit == ret.size()) {
1041 ret.push_back(substr(from, len));
1042 break;
1043 }
1044
1045 // Otherwise, push items until positive limit is reached.
1046 ret.push_back(substr(from, end - from));
1047 }
1048 }
1049
1050 if (end == len) {
1051 break;
1052 }
1053
1054 from = end + p_splitter.length();
1055 }
1056
1057 return ret;
1058 }
1059
1060 Vector<String> String::split(const char *p_splitter, bool p_allow_empty, int p_maxsplit) const {
1061 Vector<String> ret;
1062
1063 if (is_empty()) {
1064 if (p_allow_empty) {
1065 ret.push_back("");
1066 }
1067 return ret;
1068 }
1069
1070 int from = 0;
1071 int len = length();
1072 const int splitter_length = strlen(p_splitter);
1073
1074 while (true) {
1075 int end;
1076 if (p_splitter == nullptr || *p_splitter == '\0') {
1077 end = from + 1;
1078 } else {
1079 end = find(p_splitter, from);
1080 if (end < 0) {
1081 end = len;
1082 }
1083 }
1084 if (p_allow_empty || (end > from)) {
1085 if (p_maxsplit <= 0) {
1086 ret.push_back(substr(from, end - from));
1087 } else {
1088 // Put rest of the string and leave cycle.
1089 if (p_maxsplit == ret.size()) {
1090 ret.push_back(substr(from, len));
1091 break;
1092 }
1093
1094 // Otherwise, push items until positive limit is reached.
1095 ret.push_back(substr(from, end - from));
1096 }
1097 }
1098
1099 if (end == len) {
1100 break;
1101 }
1102
1103 from = end + splitter_length;
1104 }
1105
1106 return ret;
1107 }
1108
1109 Vector<String> String::rsplit(const String &p_splitter, bool p_allow_empty, int p_maxsplit) const {
1110 Vector<String> ret;
1111 const int len = length();
1112 int remaining_len = len;
1113
1114 while (true) {
1115 if (remaining_len < p_splitter.length() || (p_maxsplit > 0 && p_maxsplit == ret.size())) {
1116 // no room for another splitter or hit max splits, push what's left and we're done
1117 if (p_allow_empty || remaining_len > 0) {
1118 ret.push_back(substr(0, remaining_len));
1119 }
1120 break;
1121 }
1122
1123 int left_edge;
1124 if (p_splitter.is_empty()) {
1125 left_edge = remaining_len - 1;
1126 if (left_edge == 0) {
1127 left_edge--; // Skip to the < 0 condition.
1128 }
1129 } else {
1130 left_edge = rfind(p_splitter, remaining_len - p_splitter.length());
1131 }
1132
1133 if (left_edge < 0) {
1134 // no more splitters, we're done
1135 ret.push_back(substr(0, remaining_len));
1136 break;
1137 }
1138
1139 int substr_start = left_edge + p_splitter.length();
1140 if (p_allow_empty || substr_start < remaining_len) {
1141 ret.push_back(substr(substr_start, remaining_len - substr_start));
1142 }
1143
1144 remaining_len = left_edge;
1145 }
1146
1147 ret.reverse();
1148 return ret;
1149 }
1150
1151 Vector<String> String::rsplit(const char *p_splitter, bool p_allow_empty, int p_maxsplit) const {
1152 Vector<String> ret;
1153 const int len = length();
1154 const int splitter_length = strlen(p_splitter);
1155 int remaining_len = len;
1156
1157 while (true) {
1158 if (remaining_len < splitter_length || (p_maxsplit > 0 && p_maxsplit == ret.size())) {
1159 // no room for another splitter or hit max splits, push what's left and we're done
1160 if (p_allow_empty || remaining_len > 0) {
1161 ret.push_back(substr(0, remaining_len));
1162 }
1163 break;
1164 }
1165
1166 int left_edge;
1167 if (p_splitter == nullptr || *p_splitter == '\0') {
1168 left_edge = remaining_len - 1;
1169 if (left_edge == 0) {
1170 left_edge--; // Skip to the < 0 condition.
1171 }
1172 } else {
1173 left_edge = rfind(p_splitter, remaining_len - splitter_length);
1174 }
1175
1176 if (left_edge < 0) {
1177 // no more splitters, we're done
1178 ret.push_back(substr(0, remaining_len));
1179 break;
1180 }
1181
1182 int substr_start = left_edge + splitter_length;
1183 if (p_allow_empty || substr_start < remaining_len) {
1184 ret.push_back(substr(substr_start, remaining_len - substr_start));
1185 }
1186
1187 remaining_len = left_edge;
1188 }
1189
1190 ret.reverse();
1191 return ret;
1192 }
1193
1194 Vector<double> String::split_floats(const String &p_splitter, bool p_allow_empty) const {
1195 Vector<double> ret;
1196 int from = 0;
1197 int len = length();
1198 if (len == 0) {
1199 return ret;
1200 }
1201
1202 String buffer = *this;
1203 while (true) {
1204 int end = find(p_splitter, from);
1205 if (end < 0) {
1206 end = len;
1207 }
1208 if (p_allow_empty || (end > from)) {
1209 buffer[end] = 0;
1210 ret.push_back(String::to_float(&buffer.get_data()[from]));
1211 buffer[end] = _cowdata.get(end);
1212 }
1213
1214 if (end == len) {
1215 break;
1216 }
1217
1218 from = end + p_splitter.length();
1219 }
1220
1221 return ret;
1222 }
1223
1224 Vector<float> String::split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
1225 Vector<float> ret;
1226 int from = 0;
1227 int len = length();
1228 if (len == 0) {
1229 return ret;
1230 }
1231
1232 String buffer = *this;
1233 while (true) {
1234 int idx = 0;
1235 int end = findmk(p_splitters, from, &idx);
1236 int spl_len = 1;
1237 if (end < 0) {
1238 end = len;
1239 } else {
1240 spl_len = p_splitters[idx].length();
1241 }
1242
1243 if (p_allow_empty || (end > from)) {
1244 buffer[end] = 0;
1245 ret.push_back(String::to_float(&buffer.get_data()[from]));
1246 buffer[end] = _cowdata.get(end);
1247 }
1248
1249 if (end == len) {
1250 break;
1251 }
1252
1253 from = end + spl_len;
1254 }
1255
1256 return ret;
1257 }
1258
1259 Vector<int> String::split_ints(const String &p_splitter, bool p_allow_empty) const {
1260 Vector<int> ret;
1261 int from = 0;
1262 int len = length();
1263 if (len == 0) {
1264 return ret;
1265 }
1266
1267 while (true) {
1268 int end = find(p_splitter, from);
1269 if (end < 0) {
1270 end = len;
1271 }
1272 if (p_allow_empty || (end > from)) {
1273 ret.push_back(String::to_int(&get_data()[from], end - from));
1274 }
1275
1276 if (end == len) {
1277 break;
1278 }
1279
1280 from = end + p_splitter.length();
1281 }
1282
1283 return ret;
1284 }
1285
1286 Vector<int> String::split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
1287 Vector<int> ret;
1288 int from = 0;
1289 int len = length();
1290 if (len == 0) {
1291 return ret;
1292 }
1293
1294 while (true) {
1295 int idx = 0;
1296 int end = findmk(p_splitters, from, &idx);
1297 int spl_len = 1;
1298 if (end < 0) {
1299 end = len;
1300 } else {
1301 spl_len = p_splitters[idx].length();
1302 }
1303
1304 if (p_allow_empty || (end > from)) {
1305 ret.push_back(String::to_int(&get_data()[from], end - from));
1306 }
1307
1308 if (end == len) {
1309 break;
1310 }
1311
1312 from = end + spl_len;
1313 }
1314
1315 return ret;
1316 }
1317
1318 String String::join(const Vector<String> &parts) const {
1319 if (parts.is_empty()) {
1320 return String();
1321 } else if (parts.size() == 1) {
1322 return parts[0];
1323 }
1324
1325 const int this_length = length();
1326
1327 int new_size = (parts.size() - 1) * this_length;
1328 for (const String &part : parts) {
1329 new_size += part.length();
1330 }
1331 new_size += 1;
1332
1333 String ret;
1334 ret.resize_uninitialized(new_size);
1335 char32_t *ret_ptrw = ret.ptrw();
1336 const char32_t *this_ptr = ptr();
1337
1338 bool first = true;
1339 for (const String &part : parts) {
1340 if (first) {
1341 first = false;
1342 } else if (this_length) {
1343 memcpy(ret_ptrw, this_ptr, this_length * sizeof(char32_t));
1344 ret_ptrw += this_length;
1345 }
1346
1347 const int part_length = part.length();
1348 if (part_length) {
1349 memcpy(ret_ptrw, part.ptr(), part_length * sizeof(char32_t));
1350 ret_ptrw += part_length;
1351 }
1352 }
1353
1354 *ret_ptrw = 0;
1355
1356 return ret;
1357 }
1358
1359 char32_t String::char_uppercase(char32_t p_char) {
1360 return _find_upper(p_char);
1361 }
1362
1363 char32_t String::char_lowercase(char32_t p_char) {
1364 return _find_lower(p_char);
1365 }
1366
1367 String String::to_upper() const {
1368 if (is_empty()) {
1369 return *this;
1370 }
1371
1372 String upper;
1373 upper.resize_uninitialized(size());
1374 const char32_t *old_ptr = ptr();
1375 char32_t *upper_ptrw = upper.ptrw();
1376
1377 while (*old_ptr) {
1378 *upper_ptrw++ = _find_upper(*old_ptr++);
1379 }
1380
1381 *upper_ptrw = 0;
1382
1383 return upper;
1384 }
1385
1386 String String::to_lower() const {
1387 if (is_empty()) {
1388 return *this;
1389 }
1390
1391 String lower;
1392 lower.resize_uninitialized(size());
1393 const char32_t *old_ptr = ptr();
1394 char32_t *lower_ptrw = lower.ptrw();
1395
1396 while (*old_ptr) {
1397 *lower_ptrw++ = _find_lower(*old_ptr++);
1398 }
1399
1400 *lower_ptrw = 0;
1401
1402 return lower;
1403 }
1404
1405 String String::num(double p_num, int p_decimals) {
1406 if (Math::is_nan(p_num)) {
1407 return "nan";
1408 }
1409
1410 if (Math::is_inf(p_num)) {
1411 if (std::signbit(p_num)) {
1412 return "-inf";
1413 } else {
1414 return "inf";
1415 }
1416 }
1417
1418 if (p_decimals < 0) {
1419 p_decimals = 14;
1420 const double abs_num = Math::abs(p_num);
1421 if (abs_num > 10) {
1422 // We want to align the digits to the above reasonable default, so we only
1423 // need to subtract log10 for numbers with a positive power of ten.
1424 p_decimals -= (int)std::floor(std::log10(abs_num));
1425 }
1426 }
1427 if (p_decimals > MAX_DECIMALS) {
1428 p_decimals = MAX_DECIMALS;
1429 }
1430
1431 char fmt[7];
1432 fmt[0] = '%';
1433 fmt[1] = '.';
1434
1435 if (p_decimals < 0) {
1436 fmt[1] = 'l';
1437 fmt[2] = 'f';
1438 fmt[3] = 0;
1439 } else if (p_decimals < 10) {
1440 fmt[2] = '0' + p_decimals;
1441 fmt[3] = 'l';
1442 fmt[4] = 'f';
1443 fmt[5] = 0;
1444 } else {
1445 fmt[2] = '0' + (p_decimals / 10);
1446 fmt[3] = '0' + (p_decimals % 10);
1447 fmt[4] = 'l';
1448 fmt[5] = 'f';
1449 fmt[6] = 0;
1450 }
1451 // if we want to convert a double with as much decimal places as
1452 // DBL_MAX or DBL_MIN then we would theoretically need a buffer of at least
1453 // DBL_MAX_10_EXP + 2 for DBL_MAX and DBL_MAX_10_EXP + 4 for DBL_MIN.
1454 // BUT those values where still giving me exceptions, so I tested from
1455 // DBL_MAX_10_EXP + 10 incrementing one by one and DBL_MAX_10_EXP + 17 (325)
1456 // was the first buffer size not to throw an exception
1457 char buf[325];
1458
1459 #if defined(__GNUC__) || defined(_MSC_VER)
1460 // PLEASE NOTE that, albeit vcrt online reference states that snprintf
1461 // should safely truncate the output to the given buffer size, we have
1462 // found a case where this is not true, so we should create a buffer
1463 // as big as needed
1464 snprintf(buf, 325, fmt, p_num);
1465 #else
1466 sprintf(buf, fmt, p_num);
1467 #endif
1468
1469 buf[324] = 0;
1470 // Destroy trailing zeroes, except one after period.
1471 {
1472 bool period = false;
1473 int z = 0;
1474 while (buf[z]) {
1475 if (buf[z] == '.') {
1476 period = true;
1477 }
1478 z++;
1479 }
1480
1481 if (period) {
1482 z--;
1483 while (z > 0) {
1484 if (buf[z] == '0') {
1485 buf[z] = 0;
1486 } else if (buf[z] == '.') {
1487 buf[z + 1] = '0';
1488 break;
1489 } else {
1490 break;
1491 }
1492
1493 z--;
1494 }
1495 }
1496 }
1497
1498 return buf;
1499 }
1500
1501 String String::num_int64(int64_t p_num, int base, bool capitalize_hex) {
1502 ERR_FAIL_COND_V_MSG(base < 2 || base > 36, "", "Cannot convert to base " + itos(base) + ", since the value is " + (base < 2 ? "less than 2." : "greater than 36."));
1503
1504 bool sign = p_num < 0;
1505
1506 int64_t n = p_num;
1507
1508 int chars = 0;
1509 do {
1510 n /= base;
1511 chars++;
1512 } while (n);
1513
1514 if (sign) {
1515 chars++;
1516 }
1517 String s;
1518 s.resize_uninitialized(chars + 1);
1519 char32_t *c = s.ptrw();
1520 c[chars] = 0;
1521 n = p_num;
1522 do {
1523 int mod = Math::abs(n % base);
1524 if (mod >= 10) {
1525 char a = (capitalize_hex ? 'A' : 'a');
1526 c[--chars] = a + (mod - 10);
1527 } else {
1528 c[--chars] = '0' + mod;
1529 }
1530
1531 n /= base;
1532 } while (n);
1533
1534 if (sign) {
1535 c[0] = '-';
1536 }
1537
1538 return s;
1539 }
1540
1541 String String::num_uint64(uint64_t p_num, int base, bool capitalize_hex) {
1542 ERR_FAIL_COND_V_MSG(base < 2 || base > 36, "", "Cannot convert to base " + itos(base) + ", since the value is " + (base < 2 ? "less than 2." : "greater than 36."));
1543
1544 uint64_t n = p_num;
1545
1546 int chars = 0;
1547 do {
1548 n /= base;
1549 chars++;
1550 } while (n);
1551
1552 String s;
1553 s.resize_uninitialized(chars + 1);
1554 char32_t *c = s.ptrw();
1555 c[chars] = 0;
1556 n = p_num;
1557 do {
1558 int mod = n % base;
1559 if (mod >= 10) {
1560 char a = (capitalize_hex ? 'A' : 'a');
1561 c[--chars] = a + (mod - 10);
1562 } else {
1563 c[--chars] = '0' + mod;
1564 }
1565
1566 n /= base;
1567 } while (n);
1568
1569 return s;
1570 }
1571
1572 String String::num_real(double p_num, bool p_trailing) {
1573 if (Math::is_nan(p_num) || Math::is_inf(p_num)) {
1574 return num(p_num, 0);
1575 }
1576
1577 if (p_num == (double)(int64_t)p_num) {
1578 if (p_trailing) {
1579 return num_int64((int64_t)p_num) + ".0";
1580 } else {
1581 return num_int64((int64_t)p_num);
1582 }
1583 }
1584
1585 int decimals = 14;
1586 // We want to align the digits to the above sane default, so we only need
1587 // to subtract log10 for numbers with a positive power of ten magnitude.
1588 const double abs_num = Math::abs(p_num);
1589 if (abs_num > 10) {
1590 decimals -= (int)std::floor(std::log10(abs_num));
1591 }
1592
1593 return num(p_num, decimals);
1594 }
1595
1596 String String::num_real(float p_num, bool p_trailing) {
1597 if (Math::is_nan(p_num) || Math::is_inf(p_num)) {
1598 return num(p_num, 0);
1599 }
1600
1601 if (p_num == (float)(int64_t)p_num) {
1602 if (p_trailing) {
1603 return num_int64((int64_t)p_num) + ".0";
1604 } else {
1605 return num_int64((int64_t)p_num);
1606 }
1607 }
1608 int decimals = 6;
1609 // We want to align the digits to the above sane default, so we only need
1610 // to subtract log10 for numbers with a positive power of ten magnitude.
1611 const float abs_num = Math::abs(p_num);
1612 if (abs_num > 10) {
1613 decimals -= (int)std::floor(std::log10(abs_num));
1614 }
1615 return num(p_num, decimals);
1616 }
1617
1618 String String::num_scientific(double p_num) {
1619 if (Math::is_nan(p_num) || Math::is_inf(p_num)) {
1620 return num(p_num, 0);
1621 }
1622 char buffer[256];
1623 char *last = grisu2::to_chars(buffer, p_num);
1624 return String::ascii(Span(buffer, last - buffer));
1625 }
1626
1627 String String::num_scientific(float p_num) {
1628 if (Math::is_nan(p_num) || Math::is_inf(p_num)) {
1629 return num(p_num, 0);
1630 }
1631 char buffer[256];
1632 char *last = grisu2::to_chars(buffer, p_num);
1633 return String::ascii(Span(buffer, last - buffer));
1634 }
1635
1636 String String::md5(const uint8_t *p_md5) {
1637 return String::hex_encode_buffer(p_md5, 16);
1638 }
1639
1640 String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
1641 static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1642
1643 String ret;
1644 ret.resize_uninitialized(p_len * 2 + 1);
1645 char32_t *ret_ptrw = ret.ptrw();
1646
1647 for (int i = 0; i < p_len; i++) {
1648 *ret_ptrw++ = hex[p_buffer[i] >> 4];
1649 *ret_ptrw++ = hex[p_buffer[i] & 0xF];
1650 }
1651
1652 *ret_ptrw = 0;
1653
1654 return ret;
1655 }
1656
1657 Vector<uint8_t> String::hex_decode() const {
1658 ERR_FAIL_COND_V_MSG(length() % 2 != 0, Vector<uint8_t>(), "Hexadecimal string of uneven length.");
1659
1660 #define HEX_TO_BYTE(m_output, m_index) \
1661 uint8_t m_output; \
1662 c = operator[](m_index); \
1663 if (is_digit(c)) { \
1664 m_output = c - '0'; \
1665 } else if (c >= 'a' && c <= 'f') { \
1666 m_output = c - 'a' + 10; \
1667 } else if (c >= 'A' && c <= 'F') { \
1668 m_output = c - 'A' + 10; \
1669 } else { \
1670 ERR_FAIL_V_MSG(Vector<uint8_t>(), "Invalid hexadecimal character \"" + chr(c) + "\" at index " + m_index + "."); \
1671 }
1672
1673 Vector<uint8_t> out;
1674 int len = length() / 2;
1675 out.resize_uninitialized(len);
1676 uint8_t *out_ptrw = out.ptrw();
1677 for (int i = 0; i < len; i++) {
1678 char32_t c;
1679 HEX_TO_BYTE(first, i * 2);
1680 HEX_TO_BYTE(second, i * 2 + 1);
1681 out_ptrw[i] = first * 16 + second;
1682 }
1683 return out;
1684 #undef HEX_TO_BYTE
1685 }
1686
1687 void String::print_unicode_error(const String &p_message, bool p_critical) const {
1688 if (p_critical) {
1689 print_error(vformat(U"Unicode parsing error, some characters were replaced with � (U+FFFD): %s", p_message));
1690 } else {
1691 print_error(vformat("Unicode parsing error: %s", p_message));
1692 }
1693 }
1694
1695 CharString String::ascii(bool p_allow_extended) const {
1696 if (!length()) {
1697 return CharString();
1698 }
1699
1700 CharString cs;
1701 cs.resize_uninitialized(size());
1702 char *cs_ptrw = cs.ptrw();
1703 const char32_t *this_ptr = ptr();
1704
1705 for (int i = 0; i < size(); i++) {
1706 char32_t c = this_ptr[i];
1707 if ((c <= 0x7f) || (c <= 0xff && p_allow_extended)) {
1708 cs_ptrw[i] = char(c);
1709 } else {
1710 print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as ASCII/Latin-1", (uint32_t)c));
1711 cs_ptrw[i] = 0x20; // ASCII doesn't have a replacement character like unicode, 0x1a is sometimes used but is kinda arcane.
1712 }
1713 }
1714
1715 return cs;
1716 }
1717
1718 Error String::append_ascii(const Span<char> &p_range) {
1719 if (p_range.is_empty()) {
1720 return OK;
1721 }
1722
1723 const int prev_length = length();
1724 resize_uninitialized(prev_length + p_range.size() + 1); // Include \0
1725
1726 const char *src = p_range.ptr();
1727 const char *end = src + p_range.size();
1728 char32_t *dst = ptrw() + prev_length;
1729 bool decode_failed = false;
1730
1731 for (; src < end; ++src, ++dst) {
1732 // If char is int8_t, a set sign bit will be reinterpreted as 256 - val implicitly.
1733 const uint8_t chr = *src;
1734 if (unlikely(chr == '\0')) {
1735 // NUL in string is allowed by the unicode standard, but unsupported in our implementation right now.
1736 print_unicode_error("Unexpected NUL character", true);
1737 *dst = _replacement_char;
1738 } else if (unlikely(chr > 127)) {
1739 print_unicode_error(vformat("Invalid ASCII codepoint (%x)", (uint32_t)chr), true);
1740 decode_failed = true;
1741 *dst = _replacement_char;
1742 } else {
1743 *dst = chr;
1744 }
1745 }
1746 *dst = _null;
1747 return decode_failed ? ERR_INVALID_DATA : OK;
1748 }
1749
1750 Error String::append_utf8(const char *p_utf8, int p_len) {
1751 if (!p_utf8) {
1752 return ERR_INVALID_DATA;
1753 }
1754
1755 /* HANDLE BOM (Byte Order Mark) */
1756 if (p_len < 0 || p_len >= 3) {
1757 bool has_bom = uint8_t(p_utf8[0]) == 0xef && uint8_t(p_utf8[1]) == 0xbb && uint8_t(p_utf8[2]) == 0xbf;
1758 if (has_bom) {
1759 //8-bit encoding, byte order has no meaning in UTF-8, just skip it
1760 if (p_len >= 0) {
1761 p_len -= 3;
1762 }
1763 p_utf8 += 3;
1764 }
1765 }
1766
1767 if (p_len < 0) {
1768 p_len = strlen(p_utf8);
1769 }
1770
1771 const int prev_length = length();
1772 // If all utf8 characters maps to ASCII, then the max size will be p_len, and we add +1 for the null termination.
1773 resize_uninitialized(prev_length + p_len + 1);
1774 char32_t *dst = ptrw() + prev_length;
1775
1776 Error result = Error::OK;
1777
1778 const uint8_t *ptrtmp = (uint8_t *)p_utf8;
1779 const uint8_t *ptr_limit = (uint8_t *)p_utf8 + p_len;
1780
1781 while (ptrtmp < ptr_limit && *ptrtmp) {
1782 uint8_t c = *ptrtmp;
1783 uint32_t unicode = _replacement_char;
1784 uint32_t size = 1;
1785
1786 if ((c & 0b10000000) == 0) {
1787 unicode = c;
1788 if (unicode > 0x7F) {
1789 unicode = _replacement_char;
1790 print_unicode_error(vformat("Invalid unicode codepoint (%d)", unicode), true);
1791 result = Error::ERR_INVALID_DATA;
1792 }
1793 } else if ((c & 0b11100000) == 0b11000000) {
1794 if (ptrtmp + 1 >= ptr_limit) {
1795 print_unicode_error(vformat("Missing %x UTF-8 continuation byte", c), true);
1796 result = Error::ERR_INVALID_DATA;
1797 } else {
1798 uint8_t c2 = *(ptrtmp + 1);
1799
1800 if ((c2 & 0b11000000) == 0b10000000) {
1801 unicode = (uint32_t)((c & 0b00011111) << 6) | (uint32_t)(c2 & 0b00111111);
1802
1803 if (unicode < 0x80) {
1804 unicode = _replacement_char;
1805 print_unicode_error(vformat("Overlong encoding (%x %x)", c, c2));
1806 result = Error::ERR_INVALID_DATA;
1807 } else if (unicode > 0x7FF) {
1808 unicode = _replacement_char;
1809 print_unicode_error(vformat("Invalid unicode codepoint (%d)", unicode), true);
1810 result = Error::ERR_INVALID_DATA;
1811 } else {
1812 size = 2;
1813 }
1814 } else {
1815 print_unicode_error(vformat("Byte %x is not a correct continuation byte after %x", c2, c));
1816 result = Error::ERR_INVALID_DATA;
1817 }
1818 }
1819 } else if ((c & 0b11110000) == 0b11100000) {
1820 uint32_t range_min = (c == 0xE0) ? 0xA0 : 0x80;
1821 uint32_t range_max = (c == 0xED) ? 0x9F : 0xBF;
1822 uint8_t c2 = (ptrtmp + 1) < ptr_limit ? *(ptrtmp + 1) : 0;
1823 uint8_t c3 = (ptrtmp + 2) < ptr_limit ? *(ptrtmp + 2) : 0;
1824 bool c2_valid = c2 && (c2 >= range_min) && (c2 <= range_max);
1825 bool c3_valid = c3 && ((c3 & 0b11000000) == 0b10000000);
1826
1827 if (c2_valid && c3_valid) {
1828 unicode = (uint32_t)((c & 0b00001111) << 12) | (uint32_t)((c2 & 0b00111111) << 6) | (uint32_t)(c3 & 0b00111111);
1829
1830 if (unicode < 0x800) {
1831 unicode = _replacement_char;
1832 print_unicode_error(vformat("Overlong encoding (%x %x %x)", c, c2, c3));
1833 result = Error::ERR_INVALID_DATA;
1834 } else if (unicode > 0xFFFF) {
1835 unicode = _replacement_char;
1836 print_unicode_error(vformat("Invalid unicode codepoint (%d)", unicode), true);
1837 result = Error::ERR_INVALID_DATA;
1838 } else {
1839 size = 3;
1840 }
1841 } else {
1842 if (c2 == 0) {
1843 print_unicode_error(vformat("Missing %x UTF-8 continuation byte", c), true);
1844 } else if (c2_valid == false) {
1845 print_unicode_error(vformat("Byte %x is not a correct continuation byte after %x", c2, c));
1846 } else if (c3 == 0) {
1847 print_unicode_error(vformat("Missing %x %x UTF-8 continuation byte", c, c2), true);
1848 } else {
1849 print_unicode_error(vformat("Byte %x is not a correct continuation byte after %x %x", c3, c, c2));
1850 // The unicode specification, in paragraphe 3.9 "Unicode Encoding Forms" Conformance
1851 // state : "Only when a sequence of two or three bytes is a truncated version of a sequence which is
1852 // otherwise well-formed to that point, is more than one byte replaced with a single U+FFFD"
1853 // So here we replace the first 2 bytes with one single replacement_char.
1854 size = 2;
1855 }
1856
1857 result = Error::ERR_INVALID_DATA;
1858 }
1859 } else if ((c & 0b11111000) == 0b11110000) {
1860 uint32_t range_min = (c == 0xF0) ? 0x90 : 0x80;
1861 uint32_t range_max = (c == 0xF4) ? 0x8F : 0xBF;
1862
1863 uint8_t c2 = ((ptrtmp + 1) < ptr_limit) ? *(ptrtmp + 1) : 0;
1864 uint8_t c3 = ((ptrtmp + 2) < ptr_limit) ? *(ptrtmp + 2) : 0;
1865 uint8_t c4 = ((ptrtmp + 3) < ptr_limit) ? *(ptrtmp + 3) : 0;
1866
1867 bool c2_valid = c2 && (c2 >= range_min) && (c2 <= range_max);
1868 bool c3_valid = c3 && ((c3 & 0b11000000) == 0b10000000);
1869 bool c4_valid = c4 && ((c4 & 0b11000000) == 0b10000000);
1870
1871 if (c2_valid && c3_valid && c4_valid) {
1872 unicode = (uint32_t)((c & 0b00000111) << 18) | (uint32_t)((c2 & 0b00111111) << 12) | (uint32_t)((c3 & 0b00111111) << 6) | (uint32_t)(c4 & 0b00111111);
1873
1874 if (unicode < 0x10000) {
1875 unicode = _replacement_char;
1876 print_unicode_error(vformat("Overlong encoding (%x %x %x %x)", c, c2, c3, c4));
1877 result = Error::ERR_INVALID_DATA;
1878 } else if (unicode > 0x10FFFF) {
1879 unicode = _replacement_char;
1880 print_unicode_error(vformat("Invalid unicode codepoint (%d)", unicode), true);
1881 result = Error::ERR_INVALID_DATA;
1882 } else {
1883 size = 4;
1884 }
1885 } else {
1886 if (c2 == 0) {
1887 print_unicode_error(vformat("Missing %x UTF-8 continuation byte", c), true);
1888 } else if (c2_valid == false) {
1889 print_unicode_error(vformat("Byte %x is not a correct continuation byte after %x", c2, c));
1890 } else if (c3 == 0) {
1891 print_unicode_error(vformat("Missing %x %x UTF-8 continuation byte", c, c2), true);
1892 } else if (c3_valid == false) {
1893 print_unicode_error(vformat("Byte %x is not a correct continuation byte after %x %x", c3, c, c2));
1894 size = 2;
1895 } else if (c4 == 0) {
1896 print_unicode_error(vformat("Missing %x %x %x UTF-8 continuation byte", c, c2, c3), true);
1897 } else {
1898 print_unicode_error(vformat("Byte %x is not a correct continuation byte after %x %x %x", c4, c, c2, c3));
1899 size = 3;
1900 }
1901
1902 result = Error::ERR_INVALID_DATA;
1903 }
1904 } else {
1905 print_unicode_error(vformat("Invalid UTF-8 leading byte (%x)", c), true);
1906 result = Error::ERR_INVALID_DATA;
1907 }
1908
1909 (*dst++) = unicode;
1910 ptrtmp += size;
1911 }
1912
1913 (*dst++) = 0;
1914 resize_uninitialized(dst - ptr());
1915
1916 return result;
1917 }
1918
1919 CharString String::utf8(Vector<uint8_t> *r_ch_length_map) const {
1920 int l = length();
1921 if (!l) {
1922 return CharString();
1923 }
1924
1925 uint8_t *map_ptr = nullptr;
1926 if (r_ch_length_map) {
1927 r_ch_length_map->resize_uninitialized(l);
1928 map_ptr = r_ch_length_map->ptrw();
1929 }
1930
1931 const char32_t *d = &operator[](0);
1932 int fl = 0;
1933 for (int i = 0; i < l; i++) {
1934 uint32_t c = d[i];
1935 int ch_w = 1;
1936 if (c <= 0x7f) { // 7 bits.
1937 ch_w = 1;
1938 } else if (c <= 0x7ff) { // 11 bits
1939 ch_w = 2;
1940 } else if (c <= 0xffff) { // 16 bits
1941 ch_w = 3;
1942 } else if (c <= 0x001fffff) { // 21 bits
1943 ch_w = 4;
1944 } else if (c <= 0x03ffffff) { // 26 bits
1945 ch_w = 5;
1946 print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
1947 } else if (c <= 0x7fffffff) { // 31 bits
1948 ch_w = 6;
1949 print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
1950 } else {
1951 ch_w = 1;
1952 print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-8", c), true);
1953 }
1954 fl += ch_w;
1955 if (map_ptr) {
1956 map_ptr[i] = ch_w;
1957 }
1958 }
1959
1960 CharString utf8s;
1961 if (fl == 0) {
1962 return utf8s;
1963 }
1964
1965 utf8s.resize_uninitialized(fl + 1);
1966 uint8_t *cdst = (uint8_t *)utf8s.get_data();
1967
1968 #define APPEND_CHAR(m_c) *(cdst++) = m_c
1969
1970 for (int i = 0; i < l; i++) {
1971 uint32_t c = d[i];
1972
1973 if (c <= 0x7f) { // 7 bits.
1974 APPEND_CHAR(c);
1975 } else if (c <= 0x7ff) { // 11 bits
1976 APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits.
1977 APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
1978 } else if (c <= 0xffff) { // 16 bits
1979 APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits.
1980 APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits.
1981 APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
1982 } else if (c <= 0x001fffff) { // 21 bits
1983 APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits.
1984 APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits.
1985 APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
1986 APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
1987 } else if (c <= 0x03ffffff) { // 26 bits
1988 APPEND_CHAR(uint32_t(0xf8 | ((c >> 24) & 0x03))); // Top 2 bits.
1989 APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Upper middle 6 bits.
1990 APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // middle 6 bits.
1991 APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
1992 APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
1993 } else if (c <= 0x7fffffff) { // 31 bits
1994 APPEND_CHAR(uint32_t(0xfc | ((c >> 30) & 0x01))); // Top 1 bit.
1995 APPEND_CHAR(uint32_t(0x80 | ((c >> 24) & 0x3f))); // Upper upper middle 6 bits.
1996 APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Lower upper middle 6 bits.
1997 APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper lower middle 6 bits.
1998 APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower lower middle 6 bits.
1999 APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
2000 } else {
2001 // the string is a valid UTF32, so it should never happen ...
2002 print_unicode_error(vformat("Non scalar value (%x)", c), true);
2003 APPEND_CHAR(uint32_t(0xe0 | ((_replacement_char >> 12) & 0x0f))); // Top 4 bits.
2004 APPEND_CHAR(uint32_t(0x80 | ((_replacement_char >> 6) & 0x3f))); // Middle 6 bits.
2005 APPEND_CHAR(uint32_t(0x80 | (_replacement_char & 0x3f))); // Bottom 6 bits.
2006 }
2007 }
2008 #undef APPEND_CHAR
2009 *cdst = 0; //trailing zero
2010
2011 return utf8s;
2012 }
2013
2014 Error String::append_utf16(const char16_t *p_utf16, int p_len, bool p_default_little_endian) {
2015 if (!p_utf16) {
2016 return ERR_INVALID_DATA;
2017 }
2018
2019 String aux;
2020
2021 int cstr_size = 0;
2022 int str_size = 0;
2023
2024 #ifdef BIG_ENDIAN_ENABLED
2025 bool byteswap = p_default_little_endian;
2026 #else
2027 bool byteswap = !p_default_little_endian;
2028 #endif
2029 /* HANDLE BOM (Byte Order Mark) */
2030 if (p_len < 0 || p_len >= 1) {
2031 bool has_bom = false;
2032 if (uint16_t(p_utf16[0]) == 0xfeff) { // correct BOM, read as is
2033 has_bom = true;
2034 byteswap = false;
2035 } else if (uint16_t(p_utf16[0]) == 0xfffe) { // backwards BOM, swap bytes
2036 has_bom = true;
2037 byteswap = true;
2038 }
2039 if (has_bom) {
2040 if (p_len >= 0) {
2041 p_len -= 1;
2042 }
2043 p_utf16 += 1;
2044 }
2045 }
2046
2047 bool decode_error = false;
2048 {
2049 const char16_t *ptrtmp = p_utf16;
2050 const char16_t *ptrtmp_limit = p_len >= 0 ? &p_utf16[p_len] : nullptr;
2051 uint32_t c_prev = 0;
2052 bool skip = false;
2053 while (ptrtmp != ptrtmp_limit && *ptrtmp) {
2054 uint32_t c = (byteswap) ? BSWAP16(*ptrtmp) : *ptrtmp;
2055
2056 if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
2057 if (skip) {
2058 print_unicode_error(vformat("Unpaired lead surrogate (%x [trail?] %x)", c_prev, c));
2059 decode_error = true;
2060 }
2061 skip = true;
2062 } else if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
2063 if (skip) {
2064 str_size--;
2065 } else {
2066 print_unicode_error(vformat("Unpaired trail surrogate (%x [lead?] %x)", c_prev, c));
2067 decode_error = true;
2068 }
2069 skip = false;
2070 } else {
2071 skip = false;
2072 }
2073
2074 c_prev = c;
2075 str_size++;
2076 cstr_size++;
2077 ptrtmp++;
2078 }
2079
2080 if (skip) {
2081 print_unicode_error(vformat("Unpaired lead surrogate (%x [eol])", c_prev));
2082 decode_error = true;
2083 }
2084 }
2085
2086 if (str_size == 0) {
2087 clear();
2088 return OK; // empty string
2089 }
2090
2091 const int prev_length = length();
2092 resize_uninitialized(prev_length + str_size + 1);
2093 char32_t *dst = ptrw() + prev_length;
2094 dst[str_size] = 0;
2095
2096 bool skip = false;
2097 uint32_t c_prev = 0;
2098 while (cstr_size) {
2099 uint32_t c = (byteswap) ? BSWAP16(*p_utf16) : *p_utf16;
2100
2101 if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
2102 if (skip) {
2103 *(dst++) = c_prev; // unpaired, store as is
2104 }
2105 skip = true;
2106 } else if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
2107 if (skip) {
2108 *(dst++) = (c_prev << 10UL) + c - ((0xd800 << 10UL) + 0xdc00 - 0x10000); // decode pair
2109 } else {
2110 *(dst++) = c; // unpaired, store as is
2111 }
2112 skip = false;
2113 } else {
2114 *(dst++) = c;
2115 skip = false;
2116 }
2117
2118 cstr_size--;
2119 p_utf16++;
2120 c_prev = c;
2121 }
2122
2123 if (skip) {
2124 *(dst++) = c_prev;
2125 }
2126
2127 if (decode_error) {
2128 return ERR_PARSE_ERROR;
2129 } else {
2130 return OK;
2131 }
2132 }
2133
2134 Char16String String::utf16() const {
2135 int l = length();
2136 if (!l) {
2137 return Char16String();
2138 }
2139
2140 const char32_t *d = &operator[](0);
2141 int fl = 0;
2142 for (int i = 0; i < l; i++) {
2143 uint32_t c = d[i];
2144 if (c <= 0xffff) { // 16 bits.
2145 fl += 1;
2146 if ((c & 0xfffff800) == 0xd800) {
2147 print_unicode_error(vformat("Unpaired surrogate (%x)", c));
2148 }
2149 } else if (c <= 0x10ffff) { // 32 bits.
2150 fl += 2;
2151 } else {
2152 print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-16", c), true);
2153 fl += 1;
2154 }
2155 }
2156
2157 Char16String utf16s;
2158 if (fl == 0) {
2159 return utf16s;
2160 }
2161
2162 utf16s.resize_uninitialized(fl + 1);
2163 uint16_t *cdst = (uint16_t *)utf16s.get_data();
2164
2165 #define APPEND_CHAR(m_c) *(cdst++) = m_c
2166
2167 for (int i = 0; i < l; i++) {
2168 uint32_t c = d[i];
2169
2170 if (c <= 0xffff) { // 16 bits.
2171 APPEND_CHAR(c);
2172 } else if (c <= 0x10ffff) { // 32 bits.
2173 APPEND_CHAR(uint32_t((c >> 10) + 0xd7c0)); // lead surrogate.
2174 APPEND_CHAR(uint32_t((c & 0x3ff) | 0xdc00)); // trail surrogate.
2175 } else {
2176 // the string is a valid UTF32, so it should never happen ...
2177 APPEND_CHAR(uint32_t((_replacement_char >> 10) + 0xd7c0));
2178 APPEND_CHAR(uint32_t((_replacement_char & 0x3ff) | 0xdc00));
2179 }
2180 }
2181 #undef APPEND_CHAR
2182 *cdst = 0; //trailing zero
2183
2184 return utf16s;
2185 }
2186
2187 int64_t String::hex_to_int() const {
2188 int len = length();
2189 if (len == 0) {
2190 return 0;
2191 }
2192
2193 const char32_t *s = ptr();
2194
2195 int64_t sign = s[0] == '-' ? -1 : 1;
2196
2197 if (sign < 0) {
2198 s++;
2199 }
2200
2201 if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'x') {
2202 s += 2;
2203 }
2204
2205 int64_t hex = 0;
2206
2207 while (*s) {
2208 char32_t c = lower_case(*s);
2209 int64_t n;
2210 if (is_digit(c)) {
2211 n = c - '0';
2212 } else if (c >= 'a' && c <= 'f') {
2213 n = (c - 'a') + 10;
2214 } else {
2215 ERR_FAIL_V_MSG(0, vformat(R"(Invalid hexadecimal notation character "%c" (U+%04X) in string "%s".)", *s, static_cast<int32_t>(*s), *this));
2216 }
2217 // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
2218 bool overflow = ((hex > INT64_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT64_MAX >> 4) + 1))) || (sign == -1 && hex == (INT64_MAX >> 4) + 1 && c > '0');
2219 ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
2220 hex *= 16;
2221 hex += n;
2222 s++;
2223 }
2224
2225 return hex * sign;
2226 }
2227
2228 int64_t String::bin_to_int() const {
2229 int len = length();
2230 if (len == 0) {
2231 return 0;
2232 }
2233
2234 const char32_t *s = ptr();
2235
2236 int64_t sign = s[0] == '-' ? -1 : 1;
2237
2238 if (sign < 0) {
2239 s++;
2240 }
2241
2242 if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'b') {
2243 s += 2;
2244 }
2245
2246 int64_t binary = 0;
2247
2248 while (*s) {
2249 char32_t c = lower_case(*s);
2250 int64_t n;
2251 if (c == '0' || c == '1') {
2252 n = c - '0';
2253 } else {
2254 return 0;
2255 }
2256 // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
2257 bool overflow = ((binary > INT64_MAX / 2) && (sign == 1 || (sign == -1 && binary != (INT64_MAX >> 1) + 1))) || (sign == -1 && binary == (INT64_MAX >> 1) + 1 && c > '0');
2258 ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
2259 binary *= 2;
2260 binary += n;
2261 s++;
2262 }
2263
2264 return binary * sign;
2265 }
2266
2267 template <typename C, typename T>
2268 _ALWAYS_INLINE_ int64_t _to_int(const T &p_in, int to) {
2269 // Accumulate the total number in an unsigned integer as the range is:
2270 // +9223372036854775807 to -9223372036854775808 and the smallest negative
2271 // number does not fit inside an int64_t. So we accumulate the positive
2272 // number in an unsigned, and then at the very end convert to its signed
2273 // form.
2274 uint64_t integer = 0;
2275 uint8_t digits = 0;
2276 bool positive = true;
2277
2278 for (int i = 0; i < to; i++) {
2279 C c = p_in[i];
2280 if (is_digit(c)) {
2281 // No need to do expensive checks unless we're approaching INT64_MAX / INT64_MIN.
2282 if (unlikely(digits > 18)) {
2283 bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((positive && c > '7') || (!positive && c > '8')));
2284 ERR_FAIL_COND_V_MSG(overflow, positive ? INT64_MAX : INT64_MIN, "Cannot represent " + String(p_in) + " as a 64-bit signed integer, since the value is " + (positive ? "too large." : "too small."));
2285 }
2286
2287 integer *= 10;
2288 integer += c - '0';
2289 ++digits;
2290
2291 } else if (integer == 0 && c == '-') {
2292 positive = !positive;
2293 }
2294 }
2295
2296 if (positive) {
2297 return int64_t(integer);
2298 } else {
2299 return int64_t(integer * uint64_t(-1));
2300 }
2301 }
2302
2303 int64_t String::to_int() const {
2304 if (length() == 0) {
2305 return 0;
2306 }
2307
2308 int to = (find_char('.') >= 0) ? find_char('.') : length();
2309
2310 return _to_int<char32_t>(*this, to);
2311 }
2312
2313 int64_t String::to_int(const char *p_str, int p_len) {
2314 int to = 0;
2315 if (p_len >= 0) {
2316 to = p_len;
2317 } else {
2318 while (p_str[to] != 0 && p_str[to] != '.') {
2319 to++;
2320 }
2321 }
2322
2323 return _to_int<char>(p_str, to);
2324 }
2325
2326 int64_t String::to_int(const wchar_t *p_str, int p_len) {
2327 int to = 0;
2328 if (p_len >= 0) {
2329 to = p_len;
2330 } else {
2331 while (p_str[to] != 0 && p_str[to] != '.') {
2332 to++;
2333 }
2334 }
2335
2336 return _to_int<wchar_t>(p_str, to);
2337 }
2338
2339 bool String::is_numeric() const {
2340 if (length() == 0) {
2341 return false;
2342 }
2343
2344 int s = 0;
2345 if (operator[](0) == '-') {
2346 ++s;
2347 }
2348 bool dot = false;
2349 for (int i = s; i < length(); i++) {
2350 char32_t c = operator[](i);
2351 if (c == '.') {
2352 if (dot) {
2353 return false;
2354 }
2355 dot = true;
2356 } else if (!is_digit(c)) {
2357 return false;
2358 }
2359 }
2360
2361 return true; // TODO: Use the parser below for this instead
2362 }
2363
2364 template <typename C>
2365 static double built_in_strtod(
2366 /* A decimal ASCII floating-point number,
2367 * optionally preceded by white space. Must
2368 * have form "-I.FE-X", where I is the integer
2369 * part of the mantissa, F is the fractional
2370 * part of the mantissa, and X is the
2371 * exponent. Either of the signs may be "+",
2372 * "-", or omitted. Either I or F may be
2373 * omitted, or both. The decimal point isn't
2374 * necessary unless F is present. The "E" may
2375 * actually be an "e". E and X may both be
2376 * omitted (but not just one). */
2377 const C *string,
2378 /* If non-nullptr, store terminating Cacter's
2379 * address here. */
2380 C **endPtr = nullptr) {
2381 /* Largest possible base 10 exponent. Any
2382 * exponent larger than this will already
2383 * produce underflow or overflow, so there's
2384 * no need to worry about additional digits. */
2385 static const int maxExponent = 511;
2386 /* Table giving binary powers of 10. Entry
2387 * is 10^2^i. Used to convert decimal
2388 * exponents into floating-point numbers. */
2389 static const double powersOf10[] = {
2390 10.,
2391 100.,
2392 1.0e4,
2393 1.0e8,
2394 1.0e16,
2395 1.0e32,
2396 1.0e64,
2397 1.0e128,
2398 1.0e256
2399 };
2400
2401 bool sign, expSign = false;
2402 double fraction, dblExp;
2403 const double *d;
2404 const C *p;
2405 int c;
2406 /* Exponent read from "EX" field. */
2407 int exp = 0;
2408 /* Exponent that derives from the fractional
2409 * part. Under normal circumstances, it is
2410 * the negative of the number of digits in F.
2411 * However, if I is very long, the last digits
2412 * of I get dropped (otherwise a long I with a
2413 * large negative exponent could cause an
2414 * unnecessary overflow on I alone). In this
2415 * case, fracExp is incremented one for each
2416 * dropped digit. */
2417 int fracExp = 0;
2418 /* Number of digits in mantissa. */
2419 int mantSize;
2420 /* Number of mantissa digits BEFORE decimal point. */
2421 int decPt;
2422 /* Temporarily holds location of exponent in string. */
2423 const C *pExp;
2424
2425 /*
2426 * Strip off leading blanks and check for a sign.
2427 */
2428
2429 p = string;
2430 while (*p == ' ' || *p == '\t' || *p == '\n') {
2431 p += 1;
2432 }
2433 if (*p == '-') {
2434 sign = true;
2435 p += 1;
2436 } else {
2437 if (*p == '+') {
2438 p += 1;
2439 }
2440 sign = false;
2441 }
2442
2443 /*
2444 * Count the number of digits in the mantissa (including the decimal
2445 * point), and also locate the decimal point.
2446 */
2447
2448 decPt = -1;
2449 for (mantSize = 0;; mantSize += 1) {
2450 c = *p;
2451 if (!is_digit(c)) {
2452 if ((c != '.') || (decPt >= 0)) {
2453 break;
2454 }
2455 decPt = mantSize;
2456 }
2457 p += 1;
2458 }
2459
2460 /*
2461 * Now suck up the digits in the mantissa. Use two integers to collect 9
2462 * digits each (this is faster than using floating-point). If the mantissa
2463 * has more than 18 digits, ignore the extras, since they can't affect the
2464 * value anyway.
2465 */
2466
2467 pExp = p;
2468 p -= mantSize;
2469 if (decPt < 0) {
2470 decPt = mantSize;
2471 } else {
2472 mantSize -= 1; /* One of the digits was the point. */
2473 }
2474 if (mantSize > 18) {
2475 fracExp = decPt - 18;
2476 mantSize = 18;
2477 } else {
2478 fracExp = decPt - mantSize;
2479 }
2480 if (mantSize == 0) {
2481 fraction = 0.0;
2482 p = string;
2483 goto done;
2484 } else {
2485 int frac1, frac2;
2486
2487 frac1 = 0;
2488 for (; mantSize > 9; mantSize -= 1) {
2489 c = *p;
2490 p += 1;
2491 if (c == '.') {
2492 c = *p;
2493 p += 1;
2494 }
2495 frac1 = 10 * frac1 + (c - '0');
2496 }
2497 frac2 = 0;
2498 for (; mantSize > 0; mantSize -= 1) {
2499 c = *p;
2500 p += 1;
2501 if (c == '.') {
2502 c = *p;
2503 p += 1;
2504 }
2505 frac2 = 10 * frac2 + (c - '0');
2506 }
2507 fraction = (1.0e9 * frac1) + frac2;
2508 }
2509
2510 /*
2511 * Skim off the exponent.
2512 */
2513
2514 p = pExp;
2515 if ((*p == 'E') || (*p == 'e')) {
2516 p += 1;
2517 if (*p == '-') {
2518 expSign = true;
2519 p += 1;
2520 } else {
2521 if (*p == '+') {
2522 p += 1;
2523 }
2524 expSign = false;
2525 }
2526 if (!is_digit(char32_t(*p))) {
2527 p = pExp;
2528 goto done;
2529 }
2530 while (is_digit(char32_t(*p))) {
2531 exp = exp * 10 + (*p - '0');
2532 p += 1;
2533 }
2534 }
2535 if (expSign) {
2536 exp = fracExp - exp;
2537 } else {
2538 exp = fracExp + exp;
2539 }
2540
2541 /*
2542 * Generate a floating-point number that represents the exponent. Do this
2543 * by processing the exponent one bit at a time to combine many powers of
2544 * 2 of 10. Then combine the exponent with the fraction.
2545 */
2546
2547 if (exp < 0) {
2548 expSign = true;
2549 exp = -exp;
2550 } else {
2551 expSign = false;
2552 }
2553
2554 if (exp > maxExponent) {
2555 exp = maxExponent;
2556 WARN_PRINT("Exponent too high");
2557 }
2558 dblExp = 1.0;
2559 for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
2560 if (exp & 01) {
2561 dblExp *= *d;
2562 }
2563 }
2564 if (expSign) {
2565 fraction /= dblExp;
2566 } else {
2567 fraction *= dblExp;
2568 }
2569
2570 done:
2571 if (endPtr != nullptr) {
2572 *endPtr = (C *)p;
2573 }
2574
2575 if (sign) {
2576 return -fraction;
2577 }
2578 return fraction;
2579 }
2580
2581 #define READING_SIGN 0
2582 #define READING_INT 1
2583 #define READING_DEC 2
2584 #define READING_EXP 3
2585 #define READING_DONE 4
2586
2587 double String::to_float(const char *p_str) {
2588 return built_in_strtod<char>(p_str);
2589 }
2590
2591 double String::to_float(const char32_t *p_str, const char32_t **r_end) {
2592 return built_in_strtod<char32_t>(p_str, (char32_t **)r_end);
2593 }
2594
2595 double String::to_float(const wchar_t *p_str, const wchar_t **r_end) {
2596 return built_in_strtod<wchar_t>(p_str, (wchar_t **)r_end);
2597 }
2598
2599 uint32_t String::num_characters(int64_t p_int) {
2600 int r = 1;
2601 if (p_int < 0) {
2602 r += 1;
2603 if (p_int == INT64_MIN) {
2604 p_int = INT64_MAX;
2605 } else {
2606 p_int = -p_int;
2607 }
2608 }
2609 while (p_int >= 10) {
2610 p_int /= 10;
2611 r++;
2612 }
2613 return r;
2614 }
2615
2616 int64_t String::to_int(const char32_t *p_str, int p_len, bool p_clamp) {
2617 if (p_len == 0 || !p_str[0]) {
2618 return 0;
2619 }
2620 ///@todo make more exact so saving and loading does not lose precision
2621
2622 int64_t integer = 0;
2623 int64_t sign = 1;
2624 int reading = READING_SIGN;
2625
2626 const char32_t *str = p_str;
2627 const char32_t *limit = &p_str[p_len];
2628
2629 while (*str && reading != READING_DONE && str != limit) {
2630 char32_t c = *(str++);
2631 switch (reading) {
2632 case READING_SIGN: {
2633 if (is_digit(c)) {
2634 reading = READING_INT;
2635 // let it fallthrough
2636 } else if (c == '-') {
2637 sign = -1;
2638 reading = READING_INT;
2639 break;
2640 } else if (c == '+') {
2641 sign = 1;
2642 reading = READING_INT;
2643 break;
2644 } else {
2645 break;
2646 }
2647 [[fallthrough]];
2648 }
2649 case READING_INT: {
2650 if (is_digit(c)) {
2651 if (integer > INT64_MAX / 10) {
2652 String number("");
2653 str = p_str;
2654 while (*str && str != limit) {
2655 number += *(str++);
2656 }
2657 if (p_clamp) {
2658 if (sign == 1) {
2659 return INT64_MAX;
2660 } else {
2661 return INT64_MIN;
2662 }
2663 } else {
2664 ERR_FAIL_V_MSG(sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + number + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));
2665 }
2666 }
2667 integer *= 10;
2668 integer += c - '0';
2669 } else {
2670 reading = READING_DONE;
2671 }
2672
2673 } break;
2674 }
2675 }
2676
2677 return sign * integer;
2678 }
2679
2680 double String::to_float() const {
2681 if (is_empty()) {
2682 return 0;
2683 }
2684 return built_in_strtod<char32_t>(get_data());
2685 }
2686
2687 uint32_t String::hash(const char *p_cstr) {
2688 // static_cast: avoid negative values on platforms where char is signed.
2689 uint32_t hashv = 5381;
2690 uint32_t c = static_cast<uint8_t>(*p_cstr++);
2691
2692 while (c) {
2693 hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
2694 c = static_cast<uint8_t>(*p_cstr++);
2695 }
2696
2697 return hashv;
2698 }
2699
2700 uint32_t String::hash(const char *p_cstr, int p_len) {
2701 uint32_t hashv = 5381;
2702 for (int i = 0; i < p_len; i++) {
2703 // static_cast: avoid negative values on platforms where char is signed.
2704 hashv = ((hashv << 5) + hashv) + static_cast<uint8_t>(p_cstr[i]); /* hash * 33 + c */
2705 }
2706
2707 return hashv;
2708 }
2709
2710 uint32_t String::hash(const wchar_t *p_cstr, int p_len) {
2711 // Avoid negative values on platforms where wchar_t is signed. Account for different sizes.
2712 using wide_unsigned = std::conditional<sizeof(wchar_t) == 2, uint16_t, uint32_t>::type;
2713
2714 uint32_t hashv = 5381;
2715 for (int i = 0; i < p_len; i++) {
2716 hashv = ((hashv << 5) + hashv) + static_cast<wide_unsigned>(p_cstr[i]); /* hash * 33 + c */
2717 }
2718
2719 return hashv;
2720 }
2721
2722 uint32_t String::hash(const wchar_t *p_cstr) {
2723 // Avoid negative values on platforms where wchar_t is signed. Account for different sizes.
2724 using wide_unsigned = std::conditional<sizeof(wchar_t) == 2, uint16_t, uint32_t>::type;
2725
2726 uint32_t hashv = 5381;
2727 uint32_t c = static_cast<wide_unsigned>(*p_cstr++);
2728
2729 while (c) {
2730 hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
2731 c = static_cast<wide_unsigned>(*p_cstr++);
2732 }
2733
2734 return hashv;
2735 }
2736
2737 uint32_t String::hash(const char32_t *p_cstr, int p_len) {
2738 uint32_t hashv = 5381;
2739 for (int i = 0; i < p_len; i++) {
2740 hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
2741 }
2742
2743 return hashv;
2744 }
2745
2746 uint32_t String::hash(const char32_t *p_cstr) {
2747 uint32_t hashv = 5381;
2748 uint32_t c = *p_cstr++;
2749
2750 while (c) {
2751 hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
2752 c = *p_cstr++;
2753 }
2754
2755 return hashv;
2756 }
2757
2758 uint32_t String::hash() const {
2759 /* simple djb2 hashing */
2760
2761 const char32_t *chr = get_data();
2762 uint32_t hashv = 5381;
2763 uint32_t c = *chr++;
2764
2765 while (c) {
2766 hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
2767 c = *chr++;
2768 }
2769
2770 return hashv;
2771 }
2772
2773 uint64_t String::hash64() const {
2774 /* simple djb2 hashing */
2775
2776 const char32_t *chr = get_data();
2777 uint64_t hashv = 5381;
2778 uint64_t c = *chr++;
2779
2780 while (c) {
2781 hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
2782 c = *chr++;
2783 }
2784
2785 return hashv;
2786 }
2787
2788 String String::md5_text() const {
2789 CharString cs = utf8();
2790 unsigned char hash[16];
2791 CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
2792 return String::hex_encode_buffer(hash, 16);
2793 }
2794
2795 String String::sha1_text() const {
2796 CharString cs = utf8();
2797 unsigned char hash[20];
2798 CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
2799 return String::hex_encode_buffer(hash, 20);
2800 }
2801
2802 String String::sha256_text() const {
2803 CharString cs = utf8();
2804 unsigned char hash[32];
2805 CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
2806 return String::hex_encode_buffer(hash, 32);
2807 }
2808
2809 Vector<uint8_t> String::md5_buffer() const {
2810 CharString cs = utf8();
2811 unsigned char hash[16];
2812 CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
2813
2814 Vector<uint8_t> ret;
2815 ret.resize_uninitialized(16);
2816 uint8_t *ret_ptrw = ret.ptrw();
2817 for (int i = 0; i < 16; i++) {
2818 ret_ptrw[i] = hash[i];
2819 }
2820 return ret;
2821 }
2822
2823 Vector<uint8_t> String::sha1_buffer() const {
2824 CharString cs = utf8();
2825 unsigned char hash[20];
2826 CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
2827
2828 Vector<uint8_t> ret;
2829 ret.resize_uninitialized(20);
2830 uint8_t *ret_ptrw = ret.ptrw();
2831 for (int i = 0; i < 20; i++) {
2832 ret_ptrw[i] = hash[i];
2833 }
2834
2835 return ret;
2836 }
2837
2838 Vector<uint8_t> String::sha256_buffer() const {
2839 CharString cs = utf8();
2840 unsigned char hash[32];
2841 CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
2842
2843 Vector<uint8_t> ret;
2844 ret.resize_uninitialized(32);
2845 uint8_t *ret_ptrw = ret.ptrw();
2846 for (int i = 0; i < 32; i++) {
2847 ret_ptrw[i] = hash[i];
2848 }
2849 return ret;
2850 }
2851
2852 String String::insert(int p_at_pos, const String &p_string) const {
2853 if (p_string.is_empty() || p_at_pos < 0) {
2854 return *this;
2855 }
2856
2857 if (p_at_pos > length()) {
2858 p_at_pos = length();
2859 }
2860
2861 String ret;
2862 ret.resize_uninitialized(length() + p_string.length() + 1);
2863 char32_t *ret_ptrw = ret.ptrw();
2864 const char32_t *this_ptr = ptr();
2865
2866 if (p_at_pos > 0) {
2867 memcpy(ret_ptrw, this_ptr, p_at_pos * sizeof(char32_t));
2868 ret_ptrw += p_at_pos;
2869 }
2870
2871 memcpy(ret_ptrw, p_string.ptr(), p_string.length() * sizeof(char32_t));
2872 ret_ptrw += p_string.length();
2873
2874 if (p_at_pos < length()) {
2875 memcpy(ret_ptrw, this_ptr + p_at_pos, (length() - p_at_pos) * sizeof(char32_t));
2876 ret_ptrw += length() - p_at_pos;
2877 }
2878
2879 *ret_ptrw = 0;
2880
2881 return ret;
2882 }
2883
2884 String String::erase(int p_pos, int p_chars) const {
2885 ERR_FAIL_COND_V_MSG(p_pos < 0, "", vformat("Invalid starting position for `String.erase()`: %d. Starting position must be positive or zero.", p_pos));
2886 ERR_FAIL_COND_V_MSG(p_chars < 0, "", vformat("Invalid character count for `String.erase()`: %d. Character count must be positive or zero.", p_chars));
2887 return left(p_pos) + substr(p_pos + p_chars);
2888 }
2889
2890 template <class T>
2891 static bool _contains_char(char32_t p_c, const T *p_chars, int p_chars_len) {
2892 for (int i = 0; i < p_chars_len; ++i) {
2893 if (p_c == (char32_t)p_chars[i]) {
2894 return true;
2895 }
2896 }
2897
2898 return false;
2899 }
2900
2901 String String::remove_char(char32_t p_char) const {
2902 if (p_char == 0) {
2903 return *this;
2904 }
2905
2906 int len = length();
2907 if (len == 0) {
2908 return *this;
2909 }
2910
2911 int index = 0;
2912 const char32_t *old_ptr = ptr();
2913 for (; index < len; ++index) {
2914 if (old_ptr[index] == p_char) {
2915 break;
2916 }
2917 }
2918
2919 // If no occurrence of `char` was found, return this.
2920 if (index == len) {
2921 return *this;
2922 }
2923
2924 // If we found at least one occurrence of `char`, create new string, allocating enough space for the current length minus one.
2925 String new_string;
2926 new_string.resize_uninitialized(len);
2927 char32_t *new_ptr = new_string.ptrw();
2928
2929 // Copy part of input before `char`.
2930 memcpy(new_ptr, old_ptr, index * sizeof(char32_t));
2931
2932 int new_size = index;
2933
2934 // Copy rest, skipping `char`.
2935 for (++index; index < len; ++index) {
2936 const char32_t old_char = old_ptr[index];
2937 if (old_char != p_char) {
2938 new_ptr[new_size] = old_char;
2939 ++new_size;
2940 }
2941 }
2942
2943 new_ptr[new_size] = _null;
2944
2945 // Shrink new string to fit.
2946 new_string.resize_uninitialized(new_size + 1);
2947
2948 return new_string;
2949 }
2950
2951 template <class T>
2952 static String _remove_chars_common(const String &p_this, const T *p_chars, int p_chars_len) {
2953 // Delegate if p_chars has a single element.
2954 if (p_chars_len == 1) {
2955 return p_this.remove_char(*p_chars);
2956 } else if (p_chars_len == 0) {
2957 return p_this;
2958 }
2959
2960 int len = p_this.length();
2961
2962 if (len == 0) {
2963 return p_this;
2964 }
2965
2966 int index = 0;
2967 const char32_t *old_ptr = p_this.ptr();
2968 for (; index < len; ++index) {
2969 if (_contains_char(old_ptr[index], p_chars, p_chars_len)) {
2970 break;
2971 }
2972 }
2973
2974 // If no occurrence of `chars` was found, return this.
2975 if (index == len) {
2976 return p_this;
2977 }
2978
2979 // If we found at least one occurrence of `chars`, create new string, allocating enough space for the current length minus one.
2980 String new_string;
2981 new_string.resize_uninitialized(len);
2982 char32_t *new_ptr = new_string.ptrw();
2983
2984 // Copy part of input before `char`.
2985 memcpy(new_ptr, old_ptr, index * sizeof(char32_t));
2986
2987 int new_size = index;
2988
2989 // Copy rest, skipping `chars`.
2990 for (++index; index < len; ++index) {
2991 const char32_t old_char = old_ptr[index];
2992 if (!_contains_char(old_char, p_chars, p_chars_len)) {
2993 new_ptr[new_size] = old_char;
2994 ++new_size;
2995 }
2996 }
2997
2998 new_ptr[new_size] = 0;
2999
3000 // Shrink new string to fit.
3001 new_string.resize_uninitialized(new_size + 1);
3002
3003 return new_string;
3004 }
3005
3006 String String::remove_chars(const String &p_chars) const {
3007 return _remove_chars_common(*this, p_chars.ptr(), p_chars.length());
3008 }
3009
3010 String String::remove_chars(const char *p_chars) const {
3011 return _remove_chars_common(*this, p_chars, strlen(p_chars));
3012 }
3013
3014 String String::substr(int p_from, int p_chars) const {
3015 if (p_chars == -1) {
3016 p_chars = length() - p_from;
3017 }
3018
3019 if (is_empty() || p_from < 0 || p_from >= length() || p_chars <= 0) {
3020 return "";
3021 }
3022
3023 if ((p_from + p_chars) > length()) {
3024 p_chars = length() - p_from;
3025 }
3026
3027 if (p_from == 0 && p_chars >= length()) {
3028 return String(*this);
3029 }
3030
3031 String s;
3032 s.append_utf32_unchecked(Span(ptr() + p_from, p_chars));
3033 return s;
3034 }
3035
3036 int String::find(const String &p_str, int p_from) const {
3037 const int str_len = p_str.length();
3038 const int len = length();
3039
3040 if (p_from < 0) {
3041 p_from = len - str_len + p_from + 1;
3042 }
3043 if (p_from < 0 || p_from > len - str_len || p_str.is_empty()) {
3044 return -1; // Still out of bounds
3045 }
3046
3047 if (p_str.length() == 1) {
3048 // Optimize with single-char implementation.
3049 return span().find(p_str[0], p_from);
3050 }
3051
3052 return span().find_sequence(p_str.span(), p_from);
3053 }
3054
3055 int String::find(const char *p_str, int p_from) const {
3056 const int str_len = strlen(p_str);
3057 const int len = length();
3058
3059 if (p_from < 0) {
3060 p_from = len - str_len + p_from + 1;
3061 }
3062 if (p_from < 0 || p_from > len - str_len || str_len == 0) {
3063 return -1; // Still out of bounds
3064 }
3065
3066 if (str_len == 1) {
3067 return find_char(*p_str, p_from); // Optimize with single-char find.
3068 }
3069
3070 return span().find_sequence(Span((const unsigned char *)p_str, str_len), p_from);
3071 }
3072
3073 int String::find_char(char32_t p_char, int p_from) const {
3074 if (p_from < 0) {
3075 p_from = length() + p_from;
3076 }
3077 if (p_from < 0 || p_from >= length()) {
3078 return -1;
3079 }
3080 return span().find(p_char, p_from);
3081 }
3082
3083 int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
3084 if (p_from < 0) {
3085 return -1;
3086 }
3087 if (p_keys.is_empty()) {
3088 return -1;
3089 }
3090
3091 //int str_len=p_str.length();
3092 const String *keys = &p_keys[0];
3093 int key_count = p_keys.size();
3094 int len = length();
3095
3096 if (len == 0) {
3097 return -1; // won't find anything!
3098 }
3099
3100 const char32_t *src = get_data();
3101
3102 for (int i = p_from; i < len; i++) {
3103 for (int k = 0; k < key_count; k++) {
3104 const int str_len = keys[k].length();
3105
3106 if (i + str_len > len) {
3107 continue; // Can't find this key here.
3108 }
3109
3110 const char32_t *str = keys[k].get_data();
3111 if (are_spans_equal(src + i, str, str_len)) {
3112 if (r_key) {
3113 *r_key = k;
3114 }
3115 return i;
3116 }
3117 }
3118 }
3119
3120 return -1;
3121 }
3122
3123 int String::findn(const String &p_str, int p_from) const {
3124 const int str_len = p_str.length();
3125 const int len = length();
3126
3127 if (p_from < 0) {
3128 p_from = len - str_len + p_from + 1;
3129 }
3130 if (p_from < 0 || p_from > len - str_len || p_str.is_empty()) {
3131 return -1; // Still out of bounds
3132 }
3133
3134 const char32_t *src = get_data();
3135 const char32_t *str = p_str.get_data();
3136
3137 for (int i = p_from; i <= (len - str_len); i++) {
3138 if (strings_equal_lower(src + i, str, str_len)) {
3139 return i;
3140 }
3141 }
3142
3143 return -1;
3144 }
3145
3146 int String::findn(const char *p_str, int p_from) const {
3147 const int str_len = strlen(p_str);
3148 const int len = length();
3149
3150 if (p_from < 0) {
3151 p_from = len - str_len + p_from + 1;
3152 }
3153 if (p_from < 0 || p_from > len - str_len || str_len == 0) {
3154 return -1; // Still out of bounds
3155 }
3156
3157 const char32_t *src = get_data();
3158
3159 for (int i = p_from; i <= (len - str_len); i++) {
3160 if (strings_equal_lower(src + i, p_str, str_len)) {
3161 return i;
3162 }
3163 }
3164
3165 return -1;
3166 }
3167
3168 int String::rfind(const String &p_str, int p_from) const {
3169 const int str_len = p_str.length();
3170 const int len = length();
3171
3172 if (p_from < 0) {
3173 p_from = len - str_len + p_from + 1;
3174 }
3175 if (p_from < 0 || p_from > len - str_len || p_str.is_empty()) {
3176 return -1; // Still out of bounds
3177 }
3178
3179 if (p_str.length() == 1) {
3180 // Optimize with single-char implementation.
3181 return span().rfind(p_str[0], p_from);
3182 }
3183
3184 return span().rfind_sequence(p_str.span(), p_from);
3185 }
3186
3187 int String::rfind(const char *p_str, int p_from) const {
3188 const int str_len = strlen(p_str);
3189 const int len = length();
3190
3191 if (p_from < 0) {
3192 p_from = len - str_len + p_from + 1;
3193 }
3194 if (p_from < 0 || p_from > len - str_len || str_len == 0) {
3195 return -1; // Still out of bounds
3196 }
3197
3198 if (str_len == 1) {
3199 // Optimize with single-char implementation.
3200 return span().rfind(p_str[0], p_from);
3201 }
3202
3203 return span().rfind_sequence(Span((const unsigned char *)p_str, str_len), p_from);
3204 }
3205
3206 int String::rfind_char(char32_t p_char, int p_from) const {
3207 if (p_from < 0) {
3208 p_from = length() + p_from;
3209 }
3210 if (p_from < 0 || p_from >= length()) {
3211 return -1;
3212 }
3213 return span().rfind(p_char, p_from);
3214 }
3215
3216 int String::rfindn(const String &p_str, int p_from) const {
3217 const int str_len = p_str.length();
3218 const int len = length();
3219
3220 if (p_from < 0) {
3221 p_from = len - str_len + p_from + 1;
3222 }
3223 if (p_from < 0 || p_from > len - str_len || p_str.is_empty()) {
3224 return -1; // Still out of bounds
3225 }
3226
3227 const char32_t *src = get_data();
3228 const char32_t *str = p_str.get_data();
3229
3230 for (int i = p_from; i >= 0; i--) {
3231 if (strings_equal_lower(src + i, str, str_len)) {
3232 return i;
3233 }
3234 }
3235
3236 return -1;
3237 }
3238
3239 int String::rfindn(const char *p_str, int p_from) const {
3240 const int str_len = strlen(p_str);
3241 const int len = length();
3242
3243 if (p_from < 0) {
3244 p_from = len - str_len + p_from + 1;
3245 }
3246 if (p_from < 0 || p_from > len - str_len || str_len == 0) {
3247 return -1; // Still out of bounds
3248 }
3249
3250 const char32_t *src = get_data();
3251
3252 for (int i = p_from; i >= 0; i--) {
3253 if (strings_equal_lower(src + i, p_str, str_len)) {
3254 return i;
3255 }
3256 }
3257
3258 return -1;
3259 }
3260
3261 bool String::ends_with(const String &p_string) const {
3262 const int l = p_string.length();
3263 if (l > length()) {
3264 return false;
3265 }
3266 if (l == 0) {
3267 return true;
3268 }
3269
3270 return memcmp(ptr() + (length() - l), p_string.ptr(), l * sizeof(char32_t)) == 0;
3271 }
3272
3273 bool String::ends_with(const char *p_string) const {
3274 if (!p_string) {
3275 return false;
3276 }
3277
3278 int l = strlen(p_string);
3279 if (l > length()) {
3280 return false;
3281 }
3282
3283 if (l == 0) {
3284 return true;
3285 }
3286
3287 const char32_t *s = &operator[](length() - l);
3288
3289 for (int i = 0; i < l; i++) {
3290 if (static_cast<char32_t>(p_string[i]) != s[i]) {
3291 return false;
3292 }
3293 }
3294
3295 return true;
3296 }
3297
3298 bool String::begins_with(const String &p_string) const {
3299 const int l = p_string.length();
3300 if (l > length()) {
3301 return false;
3302 }
3303 if (l == 0) {
3304 return true;
3305 }
3306
3307 return memcmp(ptr(), p_string.ptr(), l * sizeof(char32_t)) == 0;
3308 }
3309
3310 bool String::begins_with(const char *p_string) const {
3311 if (!p_string) {
3312 return false;
3313 }
3314
3315 int l = length();
3316 if (l == 0) {
3317 return *p_string == 0;
3318 }
3319
3320 const char32_t *str = &operator[](0);
3321 int i = 0;
3322
3323 while (*p_string && i < l) {
3324 if ((char32_t)*p_string != str[i]) {
3325 return false;
3326 }
3327 i++;
3328 p_string++;
3329 }
3330
3331 return *p_string == 0;
3332 }
3333
3334 bool String::is_enclosed_in(const String &p_string) const {
3335 return begins_with(p_string) && ends_with(p_string);
3336 }
3337
3338 bool String::is_subsequence_of(const String &p_string) const {
3339 return _base_is_subsequence_of(p_string, false);
3340 }
3341
3342 bool String::is_subsequence_ofn(const String &p_string) const {
3343 return _base_is_subsequence_of(p_string, true);
3344 }
3345
3346 bool String::is_quoted() const {
3347 return is_enclosed_in("\"") || is_enclosed_in("'");
3348 }
3349
3350 bool String::is_lowercase() const {
3351 for (const char32_t *str = &operator[](0); *str; str++) {
3352 if (is_unicode_upper_case(*str)) {
3353 return false;
3354 }
3355 }
3356 return true;
3357 }
3358
3359 int String::_count(const String &p_string, int p_from, int p_to, bool p_case_insensitive) const {
3360 if (p_string.is_empty()) {
3361 return 0;
3362 }
3363 int len = length();
3364 int slen = p_string.length();
3365 if (len < slen) {
3366 return 0;
3367 }
3368 String str;
3369 if (p_from >= 0 && p_to >= 0) {
3370 if (p_to == 0) {
3371 p_to = len;
3372 } else if (p_from >= p_to) {
3373 return 0;
3374 }
3375 if (p_from == 0 && p_to == len) {
3376 str = *this;
3377 } else {
3378 str = substr(p_from, p_to - p_from);
3379 }
3380 } else {
3381 return 0;
3382 }
3383 int c = 0;
3384 int idx = 0;
3385 while ((idx = p_case_insensitive ? str.findn(p_string, idx) : str.find(p_string, idx)) != -1) {
3386 // Skip the occurrence itself.
3387 idx += slen;
3388 ++c;
3389 }
3390 return c;
3391 }
3392
3393 int String::_count(const char *p_string, int p_from, int p_to, bool p_case_insensitive) const {
3394 int substring_length = strlen(p_string);
3395 if (substring_length == 0) {
3396 return 0;
3397 }
3398 const int source_length = length();
3399
3400 if (source_length < substring_length) {
3401 return 0;
3402 }
3403 String str;
3404 int search_limit = p_to;
3405 if (p_from >= 0 && p_to >= 0) {
3406 if (p_to == 0) {
3407 search_limit = source_length;
3408 } else if (p_from >= p_to) {
3409 return 0;
3410 }
3411 if (p_from == 0 && search_limit == source_length) {
3412 str = *this;
3413 } else {
3414 str = substr(p_from, search_limit - p_from);
3415 }
3416 } else {
3417 return 0;
3418 }
3419 int c = 0;
3420 int idx = 0;
3421 while ((idx = p_case_insensitive ? str.findn(p_string, idx) : str.find(p_string, idx)) != -1) {
3422 // Skip the occurrence itself.
3423 idx += substring_length;
3424 ++c;
3425 }
3426 return c;
3427 }
3428
3429 int String::count(const String &p_string, int p_from, int p_to) const {
3430 return _count(p_string, p_from, p_to, false);
3431 }
3432
3433 int String::count(const char *p_string, int p_from, int p_to) const {
3434 return _count(p_string, p_from, p_to, false);
3435 }
3436
3437 int String::countn(const String &p_string, int p_from, int p_to) const {
3438 return _count(p_string, p_from, p_to, true);
3439 }
3440
3441 int String::countn(const char *p_string, int p_from, int p_to) const {
3442 return _count(p_string, p_from, p_to, true);
3443 }
3444
3445 bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const {
3446 int len = length();
3447 if (len == 0) {
3448 // Technically an empty string is subsequence of any string
3449 return true;
3450 }
3451
3452 if (len > p_string.length()) {
3453 return false;
3454 }
3455
3456 const char32_t *src = &operator[](0);
3457 const char32_t *tgt = &p_string[0];
3458
3459 for (; *src && *tgt; tgt++) {
3460 bool match = false;
3461 if (case_insensitive) {
3462 char32_t srcc = _find_lower(*src);
3463 char32_t tgtc = _find_lower(*tgt);
3464 match = srcc == tgtc;
3465 } else {
3466 match = *src == *tgt;
3467 }
3468 if (match) {
3469 src++;
3470 if (!*src) {
3471 return true;
3472 }
3473 }
3474 }
3475
3476 return false;
3477 }
3478
3479 Vector<String> String::bigrams() const {
3480 int n_pairs = length() - 1;
3481 Vector<String> b;
3482 if (n_pairs <= 0) {
3483 return b;
3484 }
3485 b.resize_initialized(n_pairs);
3486 String *b_ptrw = b.ptrw();
3487 for (int i = 0; i < n_pairs; i++) {
3488 b_ptrw[i] = substr(i, 2);
3489 }
3490 return b;
3491 }
3492
3493 // Similarity according to Sorensen-Dice coefficient
3494 float String::similarity(const String &p_string) const {
3495 if (operator==(p_string)) {
3496 // Equal strings are totally similar
3497 return 1.0f;
3498 }
3499 if (length() < 2 || p_string.length() < 2) {
3500 // No way to calculate similarity without a single bigram
3501 return 0.0f;
3502 }
3503
3504 const int src_size = length() - 1;
3505 const int tgt_size = p_string.length() - 1;
3506
3507 const int sum = src_size + tgt_size;
3508 int inter = 0;
3509 for (int i = 0; i < src_size; i++) {
3510 const char32_t i0 = get(i);
3511 const char32_t i1 = get(i + 1);
3512
3513 for (int j = 0; j < tgt_size; j++) {
3514 if (i0 == p_string.get(j) && i1 == p_string.get(j + 1)) {
3515 inter++;
3516 break;
3517 }
3518 }
3519 }
3520
3521 return (2.0f * inter) / sum;
3522 }
3523
3524 static bool _wildcard_match(const char32_t *p_pattern, const char32_t *p_string, bool p_case_sensitive) {
3525 switch (*p_pattern) {
3526 case '\0':
3527 return !*p_string;
3528 case '*':
3529 return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive));
3530 case '?':
3531 return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
3532 default:
3533
3534 return (p_case_sensitive ? (*p_string == *p_pattern) : (_find_upper(*p_string) == _find_upper(*p_pattern))) && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
3535 }
3536 }
3537
3538 bool String::match(const String &p_wildcard) const {
3539 if (!p_wildcard.length() || !length()) {
3540 return false;
3541 }
3542
3543 return _wildcard_match(p_wildcard.get_data(), get_data(), true);
3544 }
3545
3546 bool String::matchn(const String &p_wildcard) const {
3547 if (!p_wildcard.length() || !length()) {
3548 return false;
3549 }
3550 return _wildcard_match(p_wildcard.get_data(), get_data(), false);
3551 }
3552
3553 String String::format(const Variant &values, const String &placeholder) const {
3554 String new_string = *this;
3555
3556 if (values.get_type() == Variant::ARRAY) {
3557 Array values_arr = values;
3558
3559 for (int i = 0; i < values_arr.size(); i++) {
3560 if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
3561 Array value_arr = values_arr[i];
3562
3563 if (value_arr.size() == 2) {
3564 String key = value_arr[0];
3565 String val = value_arr[1];
3566
3567 new_string = new_string.replace(placeholder.replace("_", key), val);
3568 } else {
3569 ERR_PRINT(vformat("Invalid format: the inner Array at index %d needs to contain only 2 elements, as a key-value pair.", i).ascii().get_data());
3570 }
3571 } else { //Array structure ["RobotGuy","Logis","rookie"]
3572 String val = values_arr[i];
3573
3574 if (placeholder.contains_char('_')) {
3575 new_string = new_string.replace(placeholder.replace("_", String::num_int64(i)), val);
3576 } else {
3577 new_string = new_string.replace_first(placeholder, val);
3578 }
3579 }
3580 }
3581 } else if (values.get_type() == Variant::DICTIONARY) {
3582 Dictionary d = values;
3583
3584 for (const KeyValue<Variant, Variant> &kv : d) {
3585 new_string = new_string.replace(placeholder.replace("_", kv.key), kv.value);
3586 }
3587 } else if (values.get_type() == Variant::OBJECT) {
3588 Object *obj = values.get_validated_object();
3589 ERR_FAIL_NULL_V(obj, new_string);
3590
3591 List<PropertyInfo> props;
3592 obj->get_property_list(&props);
3593
3594 for (const PropertyInfo &E : props) {
3595 new_string = new_string.replace(placeholder.replace("_", E.name), obj->get(E.name));
3596 }
3597 } else {
3598 ERR_PRINT(String("Invalid type: use Array, Dictionary or Object.").ascii().get_data());
3599 }
3600
3601 return new_string;
3602 }
3603
3604 static String _replace_common(const String &p_this, const String &p_key, const String &p_with, bool p_case_insensitive) {
3605 if (p_key.is_empty() || p_this.is_empty()) {
3606 return p_this;
3607 }
3608
3609 const size_t key_length = p_key.length();
3610
3611 int search_from = 0;
3612 int result = 0;
3613
3614 LocalVector<int> found;
3615
3616 while ((result = (p_case_insensitive ? p_this.findn(p_key, search_from) : p_this.find(p_key, search_from))) >= 0) {
3617 found.push_back(result);
3618 ERR_FAIL_COND_V_MSG((result + key_length) > INT32_MAX, p_this, "Key length too long");
3619 search_from = result + key_length;
3620 }
3621
3622 if (found.is_empty()) {
3623 return p_this;
3624 }
3625
3626 String new_string;
3627
3628 const int with_length = p_with.length();
3629 const int old_length = p_this.length();
3630
3631 new_string.resize_uninitialized(old_length + int(found.size()) * (with_length - key_length) + 1);
3632
3633 char32_t *new_ptrw = new_string.ptrw();
3634 const char32_t *old_ptr = p_this.ptr();
3635 const char32_t *with_ptr = p_with.ptr();
3636
3637 int last_pos = 0;
3638
3639 for (const int &pos : found) {
3640 if (last_pos != pos) {
3641 memcpy(new_ptrw, old_ptr + last_pos, (pos - last_pos) * sizeof(char32_t));
3642 new_ptrw += (pos - last_pos);
3643 }
3644 if (with_length) {
3645 memcpy(new_ptrw, with_ptr, with_length * sizeof(char32_t));
3646 new_ptrw += with_length;
3647 }
3648 last_pos = pos + key_length;
3649 }
3650
3651 if (last_pos != old_length) {
3652 memcpy(new_ptrw, old_ptr + last_pos, (old_length - last_pos) * sizeof(char32_t));
3653 new_ptrw += old_length - last_pos;
3654 }
3655
3656 *new_ptrw = 0;
3657
3658 return new_string;
3659 }
3660
3661 static String _replace_common(const String &p_this, char const *p_key, char const *p_with, bool p_case_insensitive) {
3662 size_t key_length = strlen(p_key);
3663
3664 if (key_length == 0 || p_this.is_empty()) {
3665 return p_this;
3666 }
3667
3668 int search_from = 0;
3669 int result = 0;
3670
3671 LocalVector<int> found;
3672
3673 while ((result = (p_case_insensitive ? p_this.findn(p_key, search_from) : p_this.find(p_key, search_from))) >= 0) {
3674 found.push_back(result);
3675 ERR_FAIL_COND_V_MSG((result + key_length) > INT32_MAX, p_this, "Key length too long");
3676 search_from = result + key_length;
3677 }
3678
3679 if (found.is_empty()) {
3680 return p_this;
3681 }
3682
3683 String new_string;
3684
3685 // Create string to speed up copying as we can't do `memcopy` between `char32_t` and `char`.
3686 const String with_string(p_with);
3687 const int with_length = with_string.length();
3688 const int old_length = p_this.length();
3689
3690 new_string.resize_uninitialized(old_length + int(found.size()) * (with_length - key_length) + 1);
3691
3692 char32_t *new_ptrw = new_string.ptrw();
3693 const char32_t *old_ptr = p_this.ptr();
3694 const char32_t *with_ptr = with_string.ptr();
3695
3696 int last_pos = 0;
3697
3698 for (const int &pos : found) {
3699 if (last_pos != pos) {
3700 memcpy(new_ptrw, old_ptr + last_pos, (pos - last_pos) * sizeof(char32_t));
3701 new_ptrw += (pos - last_pos);
3702 }
3703 if (with_length) {
3704 memcpy(new_ptrw, with_ptr, with_length * sizeof(char32_t));
3705 new_ptrw += with_length;
3706 }
3707 last_pos = pos + key_length;
3708 }
3709
3710 if (last_pos != old_length) {
3711 memcpy(new_ptrw, old_ptr + last_pos, (old_length - last_pos) * sizeof(char32_t));
3712 new_ptrw += old_length - last_pos;
3713 }
3714
3715 *new_ptrw = 0;
3716
3717 return new_string;
3718 }
3719
3720 String String::replace(const String &p_key, const String &p_with) const {
3721 return _replace_common(*this, p_key, p_with, false);
3722 }
3723
3724 String String::replace(const char *p_key, const char *p_with) const {
3725 return _replace_common(*this, p_key, p_with, false);
3726 }
3727
3728 String String::replace_first(const String &p_key, const String &p_with) const {
3729 int pos = find(p_key);
3730 if (pos >= 0) {
3731 const int old_length = length();
3732 const int key_length = p_key.length();
3733 const int with_length = p_with.length();
3734
3735 String new_string;
3736 new_string.resize_uninitialized(old_length + (with_length - key_length) + 1);
3737
3738 char32_t *new_ptrw = new_string.ptrw();
3739 const char32_t *old_ptr = ptr();
3740 const char32_t *with_ptr = p_with.ptr();
3741
3742 if (pos > 0) {
3743 memcpy(new_ptrw, old_ptr, pos * sizeof(char32_t));
3744 new_ptrw += pos;
3745 }
3746
3747 if (with_length) {
3748 memcpy(new_ptrw, with_ptr, with_length * sizeof(char32_t));
3749 new_ptrw += with_length;
3750 }
3751 pos += key_length;
3752
3753 if (pos != old_length) {
3754 memcpy(new_ptrw, old_ptr + pos, (old_length - pos) * sizeof(char32_t));
3755 new_ptrw += (old_length - pos);
3756 }
3757
3758 *new_ptrw = 0;
3759
3760 return new_string;
3761 }
3762
3763 return *this;
3764 }
3765
3766 String String::replace_first(const char *p_key, const char *p_with) const {
3767 int pos = find(p_key);
3768 if (pos >= 0) {
3769 const int old_length = length();
3770 const int key_length = strlen(p_key);
3771 const int with_length = strlen(p_with);
3772
3773 String new_string;
3774 new_string.resize_uninitialized(old_length + (with_length - key_length) + 1);
3775
3776 char32_t *new_ptrw = new_string.ptrw();
3777 const char32_t *old_ptr = ptr();
3778
3779 if (pos > 0) {
3780 memcpy(new_ptrw, old_ptr, pos * sizeof(char32_t));
3781 new_ptrw += pos;
3782 }
3783
3784 for (int i = 0; i < with_length; ++i) {
3785 *new_ptrw++ = p_with[i];
3786 }
3787 pos += key_length;
3788
3789 if (pos != old_length) {
3790 memcpy(new_ptrw, old_ptr + pos, (old_length - pos) * sizeof(char32_t));
3791 new_ptrw += (old_length - pos);
3792 }
3793
3794 *new_ptrw = 0;
3795
3796 return new_string;
3797 }
3798
3799 return *this;
3800 }
3801
3802 String String::replace_char(char32_t p_key, char32_t p_with) const {
3803 ERR_FAIL_COND_V_MSG(p_with == 0, *this, "`with` must not be the NUL character.");
3804
3805 if (p_key == 0) {
3806 return *this;
3807 }
3808
3809 int len = length();
3810 if (len == 0) {
3811 return *this;
3812 }
3813
3814 int index = 0;
3815 const char32_t *old_ptr = ptr();
3816 for (; index < len; ++index) {
3817 if (old_ptr[index] == p_key) {
3818 break;
3819 }
3820 }
3821
3822 // If no occurrence of `key` was found, return this.
3823 if (index == len) {
3824 return *this;
3825 }
3826
3827 // If we found at least one occurrence of `key`, create new string.
3828 String new_string;
3829 new_string.resize_uninitialized(len + 1);
3830 char32_t *new_ptr = new_string.ptrw();
3831
3832 // Copy part of input before `key`.
3833 memcpy(new_ptr, old_ptr, index * sizeof(char32_t));
3834
3835 new_ptr[index] = p_with;
3836
3837 // Copy or replace rest of input.
3838 for (++index; index < len; ++index) {
3839 if (old_ptr[index] == p_key) {
3840 new_ptr[index] = p_with;
3841 } else {
3842 new_ptr[index] = old_ptr[index];
3843 }
3844 }
3845
3846 new_ptr[index] = _null;
3847
3848 return new_string;
3849 }
3850
3851 template <class T>
3852 static String _replace_chars_common(const String &p_this, const T *p_keys, int p_keys_len, char32_t p_with) {
3853 ERR_FAIL_COND_V_MSG(p_with == 0, p_this, "`with` must not be the NUL character.");
3854
3855 // Delegate if p_keys is a single element.
3856 if (p_keys_len == 1) {
3857 return p_this.replace_char(*p_keys, p_with);
3858 } else if (p_keys_len == 0) {
3859 return p_this;
3860 }
3861
3862 int len = p_this.length();
3863 if (len == 0) {
3864 return p_this;
3865 }
3866
3867 int index = 0;
3868 const char32_t *old_ptr = p_this.ptr();
3869 for (; index < len; ++index) {
3870 if (_contains_char(old_ptr[index], p_keys, p_keys_len)) {
3871 break;
3872 }
3873 }
3874
3875 // If no occurrence of `keys` was found, return this.
3876 if (index == len) {
3877 return p_this;
3878 }
3879
3880 // If we found at least one occurrence of `keys`, create new string.
3881 String new_string;
3882 new_string.resize_uninitialized(len + 1);
3883 char32_t *new_ptr = new_string.ptrw();
3884
3885 // Copy part of input before `key`.
3886 memcpy(new_ptr, old_ptr, index * sizeof(char32_t));
3887
3888 new_ptr[index] = p_with;
3889
3890 // Copy or replace rest of input.
3891 for (++index; index < len; ++index) {
3892 const char32_t old_char = old_ptr[index];
3893 if (_contains_char(old_char, p_keys, p_keys_len)) {
3894 new_ptr[index] = p_with;
3895 } else {
3896 new_ptr[index] = old_char;
3897 }
3898 }
3899
3900 new_ptr[index] = 0;
3901
3902 return new_string;
3903 }
3904
3905 String String::replace_chars(const String &p_keys, char32_t p_with) const {
3906 return _replace_chars_common(*this, p_keys.ptr(), p_keys.length(), p_with);
3907 }
3908
3909 String String::replace_chars(const char *p_keys, char32_t p_with) const {
3910 return _replace_chars_common(*this, p_keys, strlen(p_keys), p_with);
3911 }
3912
3913 String String::replacen(const String &p_key, const String &p_with) const {
3914 return _replace_common(*this, p_key, p_with, true);
3915 }
3916
3917 String String::replacen(const char *p_key, const char *p_with) const {
3918 return _replace_common(*this, p_key, p_with, true);
3919 }
3920
3921 String String::repeat(int p_count) const {
3922 ERR_FAIL_COND_V_MSG(p_count < 0, "", "Parameter count should be a positive number.");
3923
3924 if (p_count == 0) {
3925 return "";
3926 }
3927
3928 if (p_count == 1) {
3929 return *this;
3930 }
3931
3932 int len = length();
3933 String new_string = *this;
3934 new_string.resize_uninitialized(p_count * len + 1);
3935
3936 char32_t *dst = new_string.ptrw();
3937 int offset = 1;
3938 int stride = 1;
3939 while (offset < p_count) {
3940 memcpy(dst + offset * len, dst, stride * len * sizeof(char32_t));
3941 offset += stride;
3942 stride = MIN(stride * 2, p_count - offset);
3943 }
3944 dst[p_count * len] = _null;
3945 return new_string;
3946 }
3947
3948 String String::reverse() const {
3949 int len = length();
3950 if (len <= 1) {
3951 return *this;
3952 }
3953 String new_string;
3954 new_string.resize_uninitialized(len + 1);
3955
3956 const char32_t *src = ptr();
3957 char32_t *dst = new_string.ptrw();
3958 for (int i = 0; i < len; i++) {
3959 dst[i] = src[len - i - 1];
3960 }
3961 dst[len] = _null;
3962 return new_string;
3963 }
3964
3965 String String::left(int p_len) const {
3966 if (p_len < 0) {
3967 p_len = length() + p_len;
3968 }
3969
3970 if (p_len <= 0) {
3971 return "";
3972 }
3973
3974 if (p_len >= length()) {
3975 return *this;
3976 }
3977
3978 String s;
3979 s.append_utf32_unchecked(Span(ptr(), p_len));
3980 return s;
3981 }
3982
3983 String String::right(int p_len) const {
3984 if (p_len < 0) {
3985 p_len = length() + p_len;
3986 }
3987
3988 if (p_len <= 0) {
3989 return "";
3990 }
3991
3992 if (p_len >= length()) {
3993 return *this;
3994 }
3995
3996 String s;
3997 s.append_utf32_unchecked(Span(ptr() + length() - p_len, p_len));
3998 return s;
3999 }
4000
4001 char32_t String::unicode_at(int p_idx) const {
4002 ERR_FAIL_INDEX_V(p_idx, length(), 0);
4003 return operator[](p_idx);
4004 }
4005
4006 String String::indent(const String &p_prefix) const {
4007 String new_string;
4008 int line_start = 0;
4009
4010 for (int i = 0; i < length(); i++) {
4011 const char32_t c = operator[](i);
4012 if (c == '\n') {
4013 if (i == line_start) {
4014 new_string += c; // Leave empty lines empty.
4015 } else {
4016 new_string += p_prefix + substr(line_start, i - line_start + 1);
4017 }
4018 line_start = i + 1;
4019 }
4020 }
4021 if (line_start != length()) {
4022 new_string += p_prefix + substr(line_start);
4023 }
4024 return new_string;
4025 }
4026
4027 String String::dedent() const {
4028 String new_string;
4029 String indent;
4030 bool has_indent = false;
4031 bool has_text = false;
4032 int line_start = 0;
4033 int indent_stop = -1;
4034
4035 for (int i = 0; i < length(); i++) {
4036 char32_t c = operator[](i);
4037 if (c == '\n') {
4038 if (has_text) {
4039 new_string += substr(indent_stop, i - indent_stop);
4040 }
4041 new_string += "\n";
4042 has_text = false;
4043 line_start = i + 1;
4044 indent_stop = -1;
4045 } else if (!has_text) {
4046 if (c > 32) {
4047 has_text = true;
4048 if (!has_indent) {
4049 has_indent = true;
4050 indent = substr(line_start, i - line_start);
4051 indent_stop = i;
4052 }
4053 }
4054 if (has_indent && indent_stop < 0) {
4055 int j = i - line_start;
4056 if (j >= indent.length() || c != indent[j]) {
4057 indent_stop = i;
4058 }
4059 }
4060 }
4061 }
4062
4063 if (has_text) {
4064 new_string += substr(indent_stop, length() - indent_stop);
4065 }
4066
4067 return new_string;
4068 }
4069
4070 String String::strip_edges(bool left, bool right) const {
4071 int len = length();
4072 int beg = 0, end = len;
4073
4074 if (left) {
4075 for (int i = 0; i < len; i++) {
4076 if (operator[](i) <= 32) {
4077 beg++;
4078 } else {
4079 break;
4080 }
4081 }
4082 }
4083
4084 if (right) {
4085 for (int i = len - 1; i >= 0; i--) {
4086 if (operator[](i) <= 32) {
4087 end--;
4088 } else {
4089 break;
4090 }
4091 }
4092 }
4093
4094 if (beg == 0 && end == len) {
4095 return *this;
4096 }
4097
4098 return substr(beg, end - beg);
4099 }
4100
4101 String String::strip_escapes() const {
4102 String new_string;
4103 for (int i = 0; i < length(); i++) {
4104 // Escape characters on first page of the ASCII table, before 32 (Space).
4105 if (operator[](i) < 32) {
4106 continue;
4107 }
4108 new_string += operator[](i);
4109 }
4110
4111 return new_string;
4112 }
4113
4114 String String::lstrip(const String &p_chars) const {
4115 int len = length();
4116 int beg;
4117
4118 for (beg = 0; beg < len; beg++) {
4119 if (p_chars.find_char(get(beg)) == -1) {
4120 break;
4121 }
4122 }
4123
4124 if (beg == 0) {
4125 return *this;
4126 }
4127
4128 return substr(beg, len - beg);
4129 }
4130
4131 String String::rstrip(const String &p_chars) const {
4132 int len = length();
4133 int end;
4134
4135 for (end = len - 1; end >= 0; end--) {
4136 if (p_chars.find_char(get(end)) == -1) {
4137 break;
4138 }
4139 }
4140
4141 if (end == len - 1) {
4142 return *this;
4143 }
4144
4145 return substr(0, end + 1);
4146 }
4147
4148 bool String::is_network_share_path() const {
4149 return begins_with("//") || begins_with("\\\\");
4150 }
4151
4152 String String::simplify_path() const {
4153 String s = *this;
4154 String drive;
4155
4156 // Check if we have a special path (like res://) or a protocol identifier.
4157 int p = s.find("://");
4158 bool found = false;
4159 if (p > 0) {
4160 bool only_chars = true;
4161 for (int i = 0; i < p; i++) {
4162 if (!is_ascii_alphanumeric_char(s[i])) {
4163 only_chars = false;
4164 break;
4165 }
4166 }
4167 if (only_chars) {
4168 found = true;
4169 drive = s.substr(0, p + 3);
4170 s = s.substr(p + 3);
4171 }
4172 }
4173 if (!found) {
4174 if (is_network_share_path()) {
4175 // Network path, beginning with // or \\.
4176 drive = s.substr(0, 2);
4177 s = s.substr(2);
4178 } else if (s.begins_with("/") || s.begins_with("\\")) {
4179 // Absolute path.
4180 drive = s.substr(0, 1);
4181 s = s.substr(1);
4182 } else {
4183 // Windows-style drive path, like C:/ or C:\.
4184 p = s.find(":/");
4185 if (p == -1) {
4186 p = s.find(":\\");
4187 }
4188 if (p != -1 && p < s.find_char('/')) {
4189 drive = s.substr(0, p + 2);
4190 s = s.substr(p + 2);
4191 }
4192 }
4193 }
4194
4195 s = s.replace_char('\\', '/');
4196 while (true) { // in case of using 2 or more slash
4197 String compare = s.replace("//", "/");
4198 if (s == compare) {
4199 break;
4200 } else {
4201 s = compare;
4202 }
4203 }
4204 Vector<String> dirs = s.split("/", false);
4205 bool absolute_path = is_absolute_path();
4206
4207 absolute_path = absolute_path && !begins_with("res://"); // FIXME: Some code (GLTF importer) rely on accessing files up from `res://`, this probably should be disabled in the future.
4208
4209 for (int i = 0; i < dirs.size(); i++) {
4210 String d = dirs[i];
4211 if (d == ".") {
4212 dirs.remove_at(i);
4213 i--;
4214 } else if (d == "..") {
4215 if (i != 0 && dirs[i - 1] != "..") {
4216 dirs.remove_at(i);
4217 dirs.remove_at(i - 1);
4218 i -= 2;
4219 } else if (absolute_path && i == 0) {
4220 dirs.remove_at(i);
4221 i--;
4222 }
4223 }
4224 }
4225
4226 s = "";
4227
4228 for (int i = 0; i < dirs.size(); i++) {
4229 if (i > 0) {
4230 s += "/";
4231 }
4232 s += dirs[i];
4233 }
4234
4235 return drive + s;
4236 }
4237
4238 static int _humanize_digits(int p_num) {
4239 if (p_num < 100) {
4240 return 2;
4241 } else if (p_num < 1024) {
4242 return 1;
4243 } else {
4244 return 0;
4245 }
4246 }
4247
4248 String String::humanize_size(uint64_t p_size) {
4249 int magnitude = 0;
4250 uint64_t _div = 1;
4251 while (p_size > _div * 1024 && magnitude < 6) {
4252 _div *= 1024;
4253 magnitude++;
4254 }
4255
4256 if (magnitude == 0) {
4257 return String::num_uint64(p_size) + " " + RTR("B");
4258 } else {
4259 String suffix;
4260 switch (magnitude) {
4261 case 1:
4262 suffix = RTR("KiB");
4263 break;
4264 case 2:
4265 suffix = RTR("MiB");
4266 break;
4267 case 3:
4268 suffix = RTR("GiB");
4269 break;
4270 case 4:
4271 suffix = RTR("TiB");
4272 break;
4273 case 5:
4274 suffix = RTR("PiB");
4275 break;
4276 case 6:
4277 suffix = RTR("EiB");
4278 break;
4279 }
4280
4281 const double divisor = _div;
4282 const int digits = _humanize_digits(p_size / _div);
4283 return String::num(p_size / divisor).pad_decimals(digits) + " " + suffix;
4284 }
4285 }
4286
4287 bool String::is_absolute_path() const {
4288 if (length() > 1) {
4289 return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
4290 } else if ((length()) == 1) {
4291 return (operator[](0) == '/' || operator[](0) == '\\');
4292 } else {
4293 return false;
4294 }
4295 }
4296
4297 String String::validate_ascii_identifier() const {
4298 if (is_empty()) {
4299 return "_"; // Empty string is not a valid identifier.
4300 }
4301
4302 String result;
4303 if (is_digit(operator[](0))) {
4304 result = "_" + *this;
4305 } else {
4306 result = *this;
4307 }
4308
4309 int len = result.length();
4310 char32_t *buffer = result.ptrw();
4311 for (int i = 0; i < len; i++) {
4312 if (!is_ascii_identifier_char(buffer[i])) {
4313 buffer[i] = '_';
4314 }
4315 }
4316
4317 return result;
4318 }
4319
4320 String String::validate_unicode_identifier() const {
4321 if (is_empty()) {
4322 return "_"; // Empty string is not a valid identifier.
4323 }
4324
4325 String result;
4326 if (is_unicode_identifier_start(operator[](0))) {
4327 result = *this;
4328 } else {
4329 result = "_" + *this;
4330 }
4331
4332 int len = result.length();
4333 char32_t *buffer = result.ptrw();
4334 for (int i = 0; i < len; i++) {
4335 if (!is_unicode_identifier_continue(buffer[i])) {
4336 buffer[i] = '_';
4337 }
4338 }
4339
4340 return result;
4341 }
4342
4343 bool String::is_valid_ascii_identifier() const {
4344 int len = length();
4345
4346 if (len == 0) {
4347 return false;
4348 }
4349
4350 if (is_digit(operator[](0))) {
4351 return false;
4352 }
4353
4354 const char32_t *str = &operator[](0);
4355
4356 for (int i = 0; i < len; i++) {
4357 if (!is_ascii_identifier_char(str[i])) {
4358 return false;
4359 }
4360 }
4361
4362 return true;
4363 }
4364
4365 bool String::is_valid_unicode_identifier() const {
4366 const char32_t *str = ptr();
4367 int len = length();
4368
4369 if (len == 0) {
4370 return false; // Empty string.
4371 }
4372
4373 if (!is_unicode_identifier_start(str[0])) {
4374 return false;
4375 }
4376
4377 for (int i = 1; i < len; i++) {
4378 if (!is_unicode_identifier_continue(str[i])) {
4379 return false;
4380 }
4381 }
4382 return true;
4383 }
4384
4385 bool String::is_valid_string() const {
4386 int l = length();
4387 const char32_t *src = get_data();
4388 bool valid = true;
4389 for (int i = 0; i < l; i++) {
4390 valid = valid && (src[i] < 0xd800 || (src[i] > 0xdfff && src[i] <= 0x10ffff));
4391 }
4392 return valid;
4393 }
4394
4395 String String::uri_encode() const {
4396 const CharString temp = utf8();
4397 String res;
4398
4399 for (int i = 0; i < temp.length(); ++i) {
4400 uint8_t ord = uint8_t(temp[i]);
4401 if (ord == '.' || ord == '-' || ord == '~' || is_ascii_identifier_char(ord)) {
4402 res += ord;
4403 } else {
4404 char p[4] = { '%', 0, 0, 0 };
4405 p[1] = hex_char_table_upper[ord >> 4];
4406 p[2] = hex_char_table_upper[ord & 0xF];
4407 res += p;
4408 }
4409 }
4410 return res;
4411 }
4412
4413 String String::uri_decode() const {
4414 CharString src = utf8();
4415 CharString res;
4416 for (int i = 0; i < src.length(); ++i) {
4417 if (src[i] == '%' && i + 2 < src.length()) {
4418 char ord1 = src[i + 1];
4419 if (is_digit(ord1) || is_ascii_upper_case(ord1)) {
4420 char ord2 = src[i + 2];
4421 if (is_digit(ord2) || is_ascii_upper_case(ord2)) {
4422 char bytes[3] = { (char)ord1, (char)ord2, 0 };
4423 res += (char)strtol(bytes, nullptr, 16);
4424 i += 2;
4425 }
4426 } else {
4427 res += src[i];
4428 }
4429 } else if (src[i] == '+') {
4430 res += ' ';
4431 } else {
4432 res += src[i];
4433 }
4434 }
4435 return String::utf8(res);
4436 }
4437
4438 String String::uri_file_decode() const {
4439 CharString src = utf8();
4440 CharString res;
4441 for (int i = 0; i < src.length(); ++i) {
4442 if (src[i] == '%' && i + 2 < src.length()) {
4443 char ord1 = src[i + 1];
4444 if (is_digit(ord1) || is_ascii_upper_case(ord1)) {
4445 char ord2 = src[i + 2];
4446 if (is_digit(ord2) || is_ascii_upper_case(ord2)) {
4447 char bytes[3] = { (char)ord1, (char)ord2, 0 };
4448 res += (char)strtol(bytes, nullptr, 16);
4449 i += 2;
4450 }
4451 } else {
4452 res += src[i];
4453 }
4454 } else {
4455 res += src[i];
4456 }
4457 }
4458 return String::utf8(res);
4459 }
4460
4461 String String::c_unescape() const {
4462 String escaped = *this;
4463 escaped = escaped.replace("\\a", "\a");
4464 escaped = escaped.replace("\\b", "\b");
4465 escaped = escaped.replace("\\f", "\f");
4466 escaped = escaped.replace("\\n", "\n");
4467 escaped = escaped.replace("\\r", "\r");
4468 escaped = escaped.replace("\\t", "\t");
4469 escaped = escaped.replace("\\v", "\v");
4470 escaped = escaped.replace("\\'", "\'");
4471 escaped = escaped.replace("\\\"", "\"");
4472 escaped = escaped.replace("\\\\", "\\");
4473
4474 return escaped;
4475 }
4476
4477 String String::c_escape() const {
4478 String escaped = *this;
4479 escaped = escaped.replace("\\", "\\\\");
4480 escaped = escaped.replace("\a", "\\a");
4481 escaped = escaped.replace("\b", "\\b");
4482 escaped = escaped.replace("\f", "\\f");
4483 escaped = escaped.replace("\n", "\\n");
4484 escaped = escaped.replace("\r", "\\r");
4485 escaped = escaped.replace("\t", "\\t");
4486 escaped = escaped.replace("\v", "\\v");
4487 escaped = escaped.replace("\'", "\\'");
4488 escaped = escaped.replace("\"", "\\\"");
4489
4490 return escaped;
4491 }
4492
4493 String String::c_escape_multiline() const {
4494 String escaped = *this;
4495 escaped = escaped.replace("\\", "\\\\");
4496 escaped = escaped.replace("\"", "\\\"");
4497
4498 return escaped;
4499 }
4500
4501 String String::json_escape() const {
4502 String escaped = *this;
4503 escaped = escaped.replace("\\", "\\\\");
4504 escaped = escaped.replace("\b", "\\b");
4505 escaped = escaped.replace("\f", "\\f");
4506 escaped = escaped.replace("\n", "\\n");
4507 escaped = escaped.replace("\r", "\\r");
4508 escaped = escaped.replace("\t", "\\t");
4509 escaped = escaped.replace("\v", "\\v");
4510 escaped = escaped.replace("\"", "\\\"");
4511
4512 return escaped;
4513 }
4514
4515 String String::xml_escape(bool p_escape_quotes) const {
4516 String str = *this;
4517 str = str.replace("&", "&amp;");
4518 str = str.replace("<", "&lt;");
4519 str = str.replace(">", "&gt;");
4520 if (p_escape_quotes) {
4521 str = str.replace("'", "&apos;");
4522 str = str.replace("\"", "&quot;");
4523 }
4524 /*
4525 for (int i=1;i<32;i++) {
4526 char chr[2]={i,0};
4527 str=str.replace(chr,"&#"+String::num(i)+";");
4528 }*/
4529 return str;
4530 }
4531
4532 static _FORCE_INLINE_ int _xml_unescape(const char32_t *p_src, int p_src_len, char32_t *p_dst) {
4533 int len = 0;
4534 while (p_src_len) {
4535 if (*p_src == '&') {
4536 int eat = 0;
4537
4538 if (p_src_len >= 4 && p_src[1] == '#') {
4539 char32_t c = 0;
4540 bool overflow = false;
4541 if (p_src[2] == 'x') {
4542 // Hex entity &#x<num>;
4543 for (int i = 3; i < p_src_len; i++) {
4544 eat = i + 1;
4545 char32_t ct = p_src[i];
4546 if (ct == ';') {
4547 break;
4548 } else if (is_digit(ct)) {
4549 ct = ct - '0';
4550 } else if (ct >= 'a' && ct <= 'f') {
4551 ct = (ct - 'a') + 10;
4552 } else if (ct >= 'A' && ct <= 'F') {
4553 ct = (ct - 'A') + 10;
4554 } else {
4555 break;
4556 }
4557 if (c > (UINT32_MAX >> 4)) {
4558 overflow = true;
4559 break;
4560 }
4561 c <<= 4;
4562 c |= ct;
4563 }
4564 } else {
4565 // Decimal entity &#<num>;
4566 for (int i = 2; i < p_src_len; i++) {
4567 eat = i + 1;
4568 char32_t ct = p_src[i];
4569 if (ct == ';' || !is_digit(ct)) {
4570 break;
4571 }
4572 }
4573 if (p_src[eat - 1] == ';') {
4574 int64_t val = String::to_int(p_src + 2, eat - 3);
4575 if (val > 0 && val <= UINT32_MAX) {
4576 c = (char32_t)val;
4577 } else {
4578 overflow = true;
4579 }
4580 }
4581 }
4582
4583 // Value must be non-zero, in the range of char32_t,
4584 // actually end with ';'. If invalid, leave the entity as-is
4585 if (c == '\0' || overflow || p_src[eat - 1] != ';') {
4586 eat = 1;
4587 c = *p_src;
4588 }
4589 if (p_dst) {
4590 *p_dst = c;
4591 }
4592
4593 } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') {
4594 if (p_dst) {
4595 *p_dst = '>';
4596 }
4597 eat = 4;
4598 } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') {
4599 if (p_dst) {
4600 *p_dst = '<';
4601 }
4602 eat = 4;
4603 } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') {
4604 if (p_dst) {
4605 *p_dst = '&';
4606 }
4607 eat = 5;
4608 } else if (p_src_len >= 6 && p_src[1] == 'q' && p_src[2] == 'u' && p_src[3] == 'o' && p_src[4] == 't' && p_src[5] == ';') {
4609 if (p_dst) {
4610 *p_dst = '"';
4611 }
4612 eat = 6;
4613 } else if (p_src_len >= 6 && p_src[1] == 'a' && p_src[2] == 'p' && p_src[3] == 'o' && p_src[4] == 's' && p_src[5] == ';') {
4614 if (p_dst) {
4615 *p_dst = '\'';
4616 }
4617 eat = 6;
4618 } else {
4619 if (p_dst) {
4620 *p_dst = *p_src;
4621 }
4622 eat = 1;
4623 }
4624
4625 if (p_dst) {
4626 p_dst++;
4627 }
4628
4629 len++;
4630 p_src += eat;
4631 p_src_len -= eat;
4632 } else {
4633 if (p_dst) {
4634 *p_dst = *p_src;
4635 p_dst++;
4636 }
4637 len++;
4638 p_src++;
4639 p_src_len--;
4640 }
4641 }
4642
4643 return len;
4644 }
4645
4646 String String::xml_unescape() const {
4647 String str;
4648 int l = length();
4649 int len = _xml_unescape(get_data(), l, nullptr);
4650 if (len == 0) {
4651 return String();
4652 }
4653 str.resize_uninitialized(len + 1);
4654 char32_t *str_ptrw = str.ptrw();
4655 _xml_unescape(get_data(), l, str_ptrw);
4656 str_ptrw[len] = 0;
4657 return str;
4658 }
4659
4660 String String::pad_decimals(int p_digits) const {
4661 String s = *this;
4662 int c = s.find_char('.');
4663
4664 if (c == -1) {
4665 if (p_digits <= 0) {
4666 return s;
4667 }
4668 s += ".";
4669 c = s.length() - 1;
4670 } else {
4671 if (p_digits <= 0) {
4672 return s.substr(0, c);
4673 }
4674 }
4675
4676 if (s.length() - (c + 1) > p_digits) {
4677 return s.substr(0, c + p_digits + 1);
4678 } else {
4679 int zeros_to_add = p_digits - s.length() + (c + 1);
4680 return s + String("0").repeat(zeros_to_add);
4681 }
4682 }
4683
4684 String String::pad_zeros(int p_digits) const {
4685 String s = *this;
4686 int end = s.find_char('.');
4687
4688 if (end == -1) {
4689 end = s.length();
4690 }
4691
4692 if (end == 0) {
4693 return s;
4694 }
4695
4696 int begin = 0;
4697
4698 while (begin < end && !is_digit(s[begin])) {
4699 begin++;
4700 }
4701
4702 int zeros_to_add = p_digits - (end - begin);
4703
4704 if (zeros_to_add <= 0) {
4705 return s;
4706 } else {
4707 return s.insert(begin, String("0").repeat(zeros_to_add));
4708 }
4709 }
4710
4711 String String::trim_prefix(const String &p_prefix) const {
4712 String s = *this;
4713 if (s.begins_with(p_prefix)) {
4714 return s.substr(p_prefix.length());
4715 }
4716 return s;
4717 }
4718
4719 String String::trim_prefix(const char *p_prefix) const {
4720 String s = *this;
4721 if (s.begins_with(p_prefix)) {
4722 int prefix_length = strlen(p_prefix);
4723 return s.substr(prefix_length);
4724 }
4725 return s;
4726 }
4727
4728 String String::trim_suffix(const String &p_suffix) const {
4729 String s = *this;
4730 if (s.ends_with(p_suffix)) {
4731 return s.substr(0, s.length() - p_suffix.length());
4732 }
4733 return s;
4734 }
4735
4736 String String::trim_suffix(const char *p_suffix) const {
4737 String s = *this;
4738 if (s.ends_with(p_suffix)) {
4739 return s.substr(0, s.length() - strlen(p_suffix));
4740 }
4741 return s;
4742 }
4743
4744 bool String::is_valid_int() const {
4745 int len = length();
4746
4747 if (len == 0) {
4748 return false;
4749 }
4750
4751 int from = 0;
4752 if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
4753 from++;
4754 }
4755
4756 for (int i = from; i < len; i++) {
4757 if (!is_digit(operator[](i))) {
4758 return false; // no start with number plz
4759 }
4760 }
4761
4762 return true;
4763 }
4764
4765 bool String::is_valid_hex_number(bool p_with_prefix) const {
4766 int len = length();
4767
4768 if (len == 0) {
4769 return false;
4770 }
4771
4772 int from = 0;
4773 if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
4774 from++;
4775 }
4776
4777 if (p_with_prefix) {
4778 if (len < 3) {
4779 return false;
4780 }
4781 if (operator[](from) != '0' || operator[](from + 1) != 'x') {
4782 return false;
4783 }
4784 from += 2;
4785 }
4786
4787 if (from == len) {
4788 return false;
4789 }
4790
4791 for (int i = from; i < len; i++) {
4792 char32_t c = operator[](i);
4793 if (is_hex_digit(c)) {
4794 continue;
4795 }
4796 return false;
4797 }
4798
4799 return true;
4800 }
4801
4802 bool String::is_valid_float() const {
4803 int len = length();
4804
4805 if (len == 0) {
4806 return false;
4807 }
4808
4809 int from = 0;
4810 if (operator[](0) == '+' || operator[](0) == '-') {
4811 from++;
4812 }
4813
4814 bool exponent_found = false;
4815 bool period_found = false;
4816 bool sign_found = false;
4817 bool exponent_values_found = false;
4818 bool numbers_found = false;
4819
4820 for (int i = from; i < len; i++) {
4821 const char32_t c = operator[](i);
4822 if (is_digit(c)) {
4823 if (exponent_found) {
4824 exponent_values_found = true;
4825 } else {
4826 numbers_found = true;
4827 }
4828 } else if (numbers_found && !exponent_found && (c == 'e' || c == 'E')) {
4829 exponent_found = true;
4830 } else if (!period_found && !exponent_found && c == '.') {
4831 period_found = true;
4832 } else if ((c == '-' || c == '+') && exponent_found && !exponent_values_found && !sign_found) {
4833 sign_found = true;
4834 } else {
4835 return false; // no start with number plz
4836 }
4837 }
4838
4839 return numbers_found;
4840 }
4841
4842 String String::path_to_file(const String &p_path) const {
4843 // Don't get base dir for src, this is expected to be a dir already.
4844 String src = replace_char('\\', '/');
4845 String dst = p_path.replace_char('\\', '/').get_base_dir();
4846 String rel = src.path_to(dst);
4847 if (rel == dst) { // failed
4848 return p_path;
4849 } else {
4850 return rel + p_path.get_file();
4851 }
4852 }
4853
4854 String String::path_to(const String &p_path) const {
4855 String src = replace_char('\\', '/');
4856 String dst = p_path.replace_char('\\', '/');
4857 if (!src.ends_with("/")) {
4858 src += "/";
4859 }
4860 if (!dst.ends_with("/")) {
4861 dst += "/";
4862 }
4863
4864 if (src.begins_with("res://") && dst.begins_with("res://")) {
4865 src = src.replace("res://", "/");
4866 dst = dst.replace("res://", "/");
4867
4868 } else if (src.begins_with("user://") && dst.begins_with("user://")) {
4869 src = src.replace("user://", "/");
4870 dst = dst.replace("user://", "/");
4871
4872 } else if (src.begins_with("/") && dst.begins_with("/")) {
4873 //nothing
4874 } else {
4875 //dos style
4876 String src_begin = src.get_slicec('/', 0);
4877 String dst_begin = dst.get_slicec('/', 0);
4878
4879 if (src_begin != dst_begin) {
4880 return p_path; //impossible to do this
4881 }
4882
4883 src = src.substr(src_begin.length());
4884 dst = dst.substr(dst_begin.length());
4885 }
4886
4887 //remove leading and trailing slash and split
4888 Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/");
4889 Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/");
4890
4891 //find common parent
4892 int common_parent = 0;
4893
4894 while (true) {
4895 if (src_dirs.size() == common_parent) {
4896 break;
4897 }
4898 if (dst_dirs.size() == common_parent) {
4899 break;
4900 }
4901 if (src_dirs[common_parent] != dst_dirs[common_parent]) {
4902 break;
4903 }
4904 common_parent++;
4905 }
4906
4907 common_parent--;
4908
4909 int dirs_to_backtrack = (src_dirs.size() - 1) - common_parent;
4910 String dir = String("../").repeat(dirs_to_backtrack);
4911
4912 for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
4913 dir += dst_dirs[i] + "/";
4914 }
4915
4916 if (dir.length() == 0) {
4917 dir = "./";
4918 }
4919 return dir;
4920 }
4921
4922 bool String::is_valid_html_color() const {
4923 return Color::html_is_valid(*this);
4924 }
4925
4926 // Changes made to the set of invalid filename characters must also be reflected in the String documentation for is_valid_filename.
4927 static const char *invalid_filename_characters[] = { ":", "/", "\\", "?", "*", "\"", "|", "%", "<", ">" };
4928
4929 bool String::is_valid_filename() const {
4930 String stripped = strip_edges();
4931 if (*this != stripped) {
4932 return false;
4933 }
4934
4935 if (stripped.is_empty()) {
4936 return false;
4937 }
4938
4939 for (const char *ch : invalid_filename_characters) {
4940 if (contains(ch)) {
4941 return false;
4942 }
4943 }
4944 return true;
4945 }
4946
4947 String String::validate_filename() const {
4948 String name = strip_edges();
4949 for (const char *ch : invalid_filename_characters) {
4950 name = name.replace(ch, "_");
4951 }
4952 return name;
4953 }
4954
4955 bool String::is_valid_ip_address() const {
4956 return IPAddress::is_valid_ip_address(*this);
4957 }
4958
4959 bool String::is_resource_file() const {
4960 return begins_with("res://") && find("::") == -1;
4961 }
4962
4963 bool String::is_relative_path() const {
4964 return !is_absolute_path();
4965 }
4966
4967 String String::get_base_dir() const {
4968 int end = 0;
4969
4970 // URL scheme style base.
4971 int basepos = find("://");
4972 if (basepos != -1) {
4973 end = basepos + 3;
4974 }
4975
4976 // Windows top level directory base.
4977 if (end == 0) {
4978 basepos = find(":/");
4979 if (basepos == -1) {
4980 basepos = find(":\\");
4981 }
4982 if (basepos != -1) {
4983 end = basepos + 2;
4984 }
4985 }
4986
4987 // Windows UNC network share path.
4988 if (end == 0) {
4989 if (is_network_share_path()) {
4990 basepos = find_char('/', 2);
4991 if (basepos == -1) {
4992 basepos = find_char('\\', 2);
4993 }
4994 int servpos = find_char('/', basepos + 1);
4995 if (servpos == -1) {
4996 servpos = find_char('\\', basepos + 1);
4997 }
4998 if (servpos != -1) {
4999 end = servpos + 1;
5000 }
5001 }
5002 }
5003
5004 // Unix root directory base.
5005 if (end == 0) {
5006 if (begins_with("/")) {
5007 end = 1;
5008 }
5009 }
5010
5011 String rs;
5012 String base;
5013 if (end != 0) {
5014 rs = substr(end, length());
5015 base = substr(0, end);
5016 } else {
5017 rs = *this;
5018 }
5019
5020 int sep = MAX(rs.rfind_char('/'), rs.rfind_char('\\'));
5021 if (sep == -1) {
5022 return base;
5023 }
5024
5025 return base + rs.substr(0, sep);
5026 }
5027
5028 String String::get_file() const {
5029 int sep = MAX(rfind_char('/'), rfind_char('\\'));
5030 if (sep == -1) {
5031 return *this;
5032 }
5033
5034 return substr(sep + 1, length());
5035 }
5036
5037 String String::get_extension() const {
5038 int pos = rfind_char('.');
5039 if (pos < 0 || pos < MAX(rfind_char('/'), rfind_char('\\'))) {
5040 return "";
5041 }
5042
5043 return substr(pos + 1, length());
5044 }
5045
5046 String String::path_join(const String &p_file) const {
5047 if (is_empty()) {
5048 return p_file;
5049 }
5050 if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/')) {
5051 return *this + p_file;
5052 }
5053 return *this + "/" + p_file;
5054 }
5055
5056 String String::property_name_encode() const {
5057 // Escape and quote strings with extended ASCII or further Unicode characters
5058 // as well as '"', '=' or ' ' (32)
5059 const char32_t *cstr = get_data();
5060 for (int i = 0; cstr[i]; i++) {
5061 if (cstr[i] == '=' || cstr[i] == '"' || cstr[i] == ';' || cstr[i] == '[' || cstr[i] == ']' || cstr[i] < 33 || cstr[i] > 126) {
5062 return "\"" + c_escape_multiline() + "\"";
5063 }
5064 }
5065 // Keep as is
5066 return *this;
5067 }
5068
5069 // Changes made to the set of invalid characters must also be reflected in the String documentation.
5070
5071 static const char32_t invalid_node_name_characters[] = { '.', ':', '@', '/', '\"', UNIQUE_NODE_PREFIX[0], 0 };
5072
5073 String String::get_invalid_node_name_characters(bool p_allow_internal) {
5074 // Do not use this function for critical validation.
5075 String r;
5076 const char32_t *c = invalid_node_name_characters;
5077 while (*c) {
5078 if (p_allow_internal && *c == '@') {
5079 c++;
5080 continue;
5081 }
5082
5083 if (c != invalid_node_name_characters) {
5084 r += " ";
5085 }
5086 r += String::chr(*c);
5087 c++;
5088 }
5089 return r;
5090 }
5091
5092 String String::validate_node_name() const {
5093 // This is a critical validation in node addition, so it must be optimized.
5094 const char32_t *cn = ptr();
5095 if (cn == nullptr) {
5096 return String();
5097 }
5098 bool valid = true;
5099 uint32_t idx = 0;
5100 while (cn[idx]) {
5101 const char32_t *c = invalid_node_name_characters;
5102 while (*c) {
5103 if (cn[idx] == *c) {
5104 valid = false;
5105 break;
5106 }
5107 c++;
5108 }
5109 if (!valid) {
5110 break;
5111 }
5112 idx++;
5113 }
5114
5115 if (valid) {
5116 return *this;
5117 }
5118
5119 String validated = *this;
5120 char32_t *nn = validated.ptrw();
5121 while (nn[idx]) {
5122 const char32_t *c = invalid_node_name_characters;
5123 while (*c) {
5124 if (nn[idx] == *c) {
5125 nn[idx] = '_';
5126 break;
5127 }
5128 c++;
5129 }
5130 idx++;
5131 }
5132
5133 return validated;
5134 }
5135
5136 String String::get_basename() const {
5137 int pos = rfind_char('.');
5138 if (pos < 0 || pos < MAX(rfind_char('/'), rfind_char('\\'))) {
5139 return *this;
5140 }
5141
5142 return substr(0, pos);
5143 }
5144
5145 String itos(int64_t p_val) {
5146 return String::num_int64(p_val);
5147 }
5148
5149 String uitos(uint64_t p_val) {
5150 return String::num_uint64(p_val);
5151 }
5152
5153 String rtos(double p_val) {
5154 return String::num(p_val);
5155 }
5156
5157 String rtoss(double p_val) {
5158 return String::num_scientific(p_val);
5159 }
5160
5161 // Right-pad with a character.
5162 String String::rpad(int min_length, const String &character) const {
5163 String s = *this;
5164 int padding = min_length - s.length();
5165 if (padding > 0) {
5166 s += character.repeat(padding);
5167 }
5168 return s;
5169 }
5170
5171 // Left-pad with a character.
5172 String String::lpad(int min_length, const String &character) const {
5173 String s = *this;
5174 int padding = min_length - s.length();
5175 if (padding > 0) {
5176 s = character.repeat(padding) + s;
5177 }
5178 return s;
5179 }
5180
5181 // sprintf is implemented in GDScript via:
5182 // "fish %s pie" % "frog"
5183 // "fish %s %d pie" % ["frog", 12]
5184 // In case of an error, the string returned is the error description and "error" is true.
5185 String String::sprintf(const Span<Variant> &values, bool *error) const {
5186 static const String ZERO("0");
5187 static const String SPACE(" ");
5188 static const String MINUS("-");
5189 static const String PLUS("+");
5190
5191 String formatted;
5192 char32_t *self = (char32_t *)get_data();
5193 bool in_format = false;
5194 uint64_t value_index = 0;
5195 int min_chars = 0;
5196 int min_decimals = 0;
5197 bool in_decimals = false;
5198 bool pad_with_zeros = false;
5199 bool left_justified = false;
5200 bool show_sign = false;
5201 bool as_unsigned = false;
5202
5203 if (error) {
5204 *error = true;
5205 }
5206
5207 for (; *self; self++) {
5208 const char32_t c = *self;
5209
5210 if (in_format) { // We have % - let's see what else we get.
5211 switch (c) {
5212 case '%': { // Replace %% with %
5213 formatted += c;
5214 in_format = false;
5215 break;
5216 }
5217 case 'd': // Integer (signed)
5218 case 'o': // Octal
5219 case 'x': // Hexadecimal (lowercase)
5220 case 'X': { // Hexadecimal (uppercase)
5221 if (value_index >= values.size()) {
5222 return "not enough arguments for format string";
5223 }
5224
5225 if (!values[value_index].is_num()) {
5226 return "a number is required";
5227 }
5228
5229 int64_t value = values[value_index];
5230 int base = 16;
5231 bool capitalize = false;
5232 switch (c) {
5233 case 'd':
5234 base = 10;
5235 break;
5236 case 'o':
5237 base = 8;
5238 break;
5239 case 'x':
5240 break;
5241 case 'X':
5242 capitalize = true;
5243 break;
5244 }
5245 // Get basic number.
5246 String str;
5247 if (!as_unsigned) {
5248 if (value == INT64_MIN) { // INT64_MIN can't be represented as positive value.
5249 str = String::num_int64(value, base, capitalize).trim_prefix("-");
5250 } else {
5251 str = String::num_int64(Math::abs(value), base, capitalize);
5252 }
5253 } else {
5254 uint64_t uvalue = *((uint64_t *)&value);
5255 // In unsigned hex, if the value fits in 32 bits, trim it down to that.
5256 if (base == 16 && value < 0 && value >= INT32_MIN) {
5257 uvalue &= 0xffffffff;
5258 }
5259 str = String::num_uint64(uvalue, base, capitalize);
5260 }
5261 int number_len = str.length();
5262
5263 bool negative = value < 0 && !as_unsigned;
5264
5265 // Padding.
5266 int pad_chars_count = (negative || show_sign) ? min_chars - 1 : min_chars;
5267 const String &pad_char = pad_with_zeros ? ZERO : SPACE;
5268 if (left_justified) {
5269 str = str.rpad(pad_chars_count, pad_char);
5270 } else {
5271 str = str.lpad(pad_chars_count, pad_char);
5272 }
5273
5274 // Sign.
5275 if (show_sign || negative) {
5276 const String &sign_char = negative ? MINUS : PLUS;
5277 if (left_justified) {
5278 str = str.insert(0, sign_char);
5279 } else {
5280 str = str.insert(pad_with_zeros ? 0 : str.length() - number_len, sign_char);
5281 }
5282 }
5283
5284 formatted += str;
5285 ++value_index;
5286 in_format = false;
5287
5288 break;
5289 }
5290 case 'f': { // Float
5291 if (value_index >= values.size()) {
5292 return "not enough arguments for format string";
5293 }
5294
5295 if (!values[value_index].is_num()) {
5296 return "a number is required";
5297 }
5298
5299 double value = values[value_index];
5300 bool is_negative = std::signbit(value);
5301 String str = String::num(Math::abs(value), min_decimals);
5302 const bool is_finite = Math::is_finite(value);
5303
5304 // Pad decimals out.
5305 if (is_finite) {
5306 str = str.pad_decimals(min_decimals);
5307 }
5308
5309 int initial_len = str.length();
5310
5311 // Padding. Leave room for sign later if required.
5312 int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars;
5313 const String &pad_char = (pad_with_zeros && is_finite) ? ZERO : SPACE; // Never pad NaN or inf with zeros
5314 if (left_justified) {
5315 str = str.rpad(pad_chars_count, pad_char);
5316 } else {
5317 str = str.lpad(pad_chars_count, pad_char);
5318 }
5319
5320 // Add sign if needed.
5321 if (show_sign || is_negative) {
5322 const String &sign_char = is_negative ? MINUS : PLUS;
5323 if (left_justified) {
5324 str = str.insert(0, sign_char);
5325 } else {
5326 str = str.insert(pad_with_zeros ? 0 : str.length() - initial_len, sign_char);
5327 }
5328 }
5329
5330 formatted += str;
5331 ++value_index;
5332 in_format = false;
5333 break;
5334 }
5335 case 'v': { // Vector2/3/4/2i/3i/4i
5336 if (value_index >= values.size()) {
5337 return "not enough arguments for format string";
5338 }
5339
5340 int count;
5341 switch (values[value_index].get_type()) {
5342 case Variant::VECTOR2:
5343 case Variant::VECTOR2I: {
5344 count = 2;
5345 } break;
5346 case Variant::VECTOR3:
5347 case Variant::VECTOR3I: {
5348 count = 3;
5349 } break;
5350 case Variant::VECTOR4:
5351 case Variant::VECTOR4I: {
5352 count = 4;
5353 } break;
5354 default: {
5355 return "%v requires a vector type (Vector2/3/4/2i/3i/4i)";
5356 }
5357 }
5358
5359 Vector4 vec = values[value_index];
5360 String str = "(";
5361 for (int i = 0; i < count; i++) {
5362 double val = vec[i];
5363 String number_str = String::num(Math::abs(val), min_decimals);
5364 const bool is_finite = Math::is_finite(val);
5365
5366 // Pad decimals out.
5367 if (is_finite) {
5368 number_str = number_str.pad_decimals(min_decimals);
5369 }
5370
5371 int initial_len = number_str.length();
5372
5373 // Padding. Leave room for sign later if required.
5374 int pad_chars_count = val < 0 ? min_chars - 1 : min_chars;
5375 const String &pad_char = (pad_with_zeros && is_finite) ? ZERO : SPACE; // Never pad NaN or inf with zeros
5376 if (left_justified) {
5377 number_str = number_str.rpad(pad_chars_count, pad_char);
5378 } else {
5379 number_str = number_str.lpad(pad_chars_count, pad_char);
5380 }
5381
5382 // Add sign if needed.
5383 if (val < 0) {
5384 if (left_justified) {
5385 number_str = number_str.insert(0, MINUS);
5386 } else {
5387 number_str = number_str.insert(pad_with_zeros ? 0 : number_str.length() - initial_len, MINUS);
5388 }
5389 }
5390
5391 // Add number to combined string
5392 str += number_str;
5393
5394 if (i < count - 1) {
5395 str += ", ";
5396 }
5397 }
5398 str += ")";
5399
5400 formatted += str;
5401 ++value_index;
5402 in_format = false;
5403 break;
5404 }
5405 case 's': { // String
5406 if (value_index >= values.size()) {
5407 return "not enough arguments for format string";
5408 }
5409
5410 String str = values[value_index];
5411 // Padding.
5412 if (left_justified) {
5413 str = str.rpad(min_chars);
5414 } else {
5415 str = str.lpad(min_chars);
5416 }
5417
5418 formatted += str;
5419 ++value_index;
5420 in_format = false;
5421 break;
5422 }
5423 case 'c': {
5424 if (value_index >= values.size()) {
5425 return "not enough arguments for format string";
5426 }
5427
5428 // Convert to character.
5429 String str;
5430 if (values[value_index].is_num()) {
5431 int value = values[value_index];
5432 if (value < 0) {
5433 return "unsigned integer is lower than minimum";
5434 } else if (value >= 0xd800 && value <= 0xdfff) {
5435 return "unsigned integer is invalid Unicode character";
5436 } else if (value > 0x10ffff) {
5437 return "unsigned integer is greater than maximum";
5438 }
5439 str = chr(values[value_index]);
5440 } else if (values[value_index].get_type() == Variant::STRING) {
5441 str = values[value_index];
5442 if (str.length() != 1) {
5443 return "%c requires number or single-character string";
5444 }
5445 } else {
5446 return "%c requires number or single-character string";
5447 }
5448
5449 // Padding.
5450 if (left_justified) {
5451 str = str.rpad(min_chars);
5452 } else {
5453 str = str.lpad(min_chars);
5454 }
5455
5456 formatted += str;
5457 ++value_index;
5458 in_format = false;
5459 break;
5460 }
5461 case '-': { // Left justify
5462 left_justified = true;
5463 break;
5464 }
5465 case '+': { // Show + if positive.
5466 show_sign = true;
5467 break;
5468 }
5469 case 'u': { // Treat as unsigned (for int/hex).
5470 as_unsigned = true;
5471 break;
5472 }
5473 case '0':
5474 case '1':
5475 case '2':
5476 case '3':
5477 case '4':
5478 case '5':
5479 case '6':
5480 case '7':
5481 case '8':
5482 case '9': {
5483 int n = c - '0';
5484 if (in_decimals) {
5485 min_decimals *= 10;
5486 min_decimals += n;
5487 } else {
5488 if (c == '0' && min_chars == 0) {
5489 if (left_justified) {
5490 WARN_PRINT("'0' flag ignored with '-' flag in string format");
5491 } else {
5492 pad_with_zeros = true;
5493 }
5494 } else {
5495 min_chars *= 10;
5496 min_chars += n;
5497 }
5498 }
5499 break;
5500 }
5501 case '.': { // Float/Vector separator.
5502 if (in_decimals) {
5503 return "too many decimal points in format";
5504 }
5505 in_decimals = true;
5506 min_decimals = 0; // We want to add the value manually.
5507 break;
5508 }
5509
5510 case '*': { // Dynamic width, based on value.
5511 if (value_index >= values.size()) {
5512 return "not enough arguments for format string";
5513 }
5514
5515 Variant::Type value_type = values[value_index].get_type();
5516 if (!values[value_index].is_num() &&
5517 value_type != Variant::VECTOR2 && value_type != Variant::VECTOR2I &&
5518 value_type != Variant::VECTOR3 && value_type != Variant::VECTOR3I &&
5519 value_type != Variant::VECTOR4 && value_type != Variant::VECTOR4I) {
5520 return "* wants number or vector";
5521 }
5522
5523 int size = values[value_index];
5524
5525 if (in_decimals) {
5526 min_decimals = size;
5527 } else {
5528 min_chars = size;
5529 }
5530
5531 ++value_index;
5532 break;
5533 }
5534
5535 default: {
5536 return "unsupported format character";
5537 }
5538 }
5539 } else { // Not in format string.
5540 switch (c) {
5541 case '%':
5542 in_format = true;
5543 // Back to defaults:
5544 min_chars = 0;
5545 min_decimals = 6;
5546 pad_with_zeros = false;
5547 left_justified = false;
5548 show_sign = false;
5549 in_decimals = false;
5550 break;
5551 default:
5552 formatted += c;
5553 }
5554 }
5555 }
5556
5557 if (in_format) {
5558 return "incomplete format";
5559 }
5560
5561 if (value_index != values.size()) {
5562 return "not all arguments converted during string formatting";
5563 }
5564
5565 if (error) {
5566 *error = false;
5567 }
5568 return formatted;
5569 }
5570
5571 String String::quote(const String &quotechar) const {
5572 return quotechar + *this + quotechar;
5573 }
5574
5575 String String::unquote() const {
5576 if (!is_quoted()) {
5577 return *this;
5578 }
5579
5580 return substr(1, length() - 2);
5581 }
5582
5583 Vector<uint8_t> String::to_ascii_buffer() const {
5584 const String *s = this;
5585 if (s->is_empty()) {
5586 return Vector<uint8_t>();
5587 }
5588 CharString charstr = s->ascii();
5589
5590 Vector<uint8_t> retval;
5591 size_t len = charstr.length();
5592 retval.resize_uninitialized(len);
5593 uint8_t *w = retval.ptrw();
5594 memcpy(w, charstr.ptr(), len);
5595
5596 return retval;
5597 }
5598
5599 Vector<uint8_t> String::to_utf8_buffer() const {
5600 const String *s = this;
5601 if (s->is_empty()) {
5602 return Vector<uint8_t>();
5603 }
5604 CharString charstr = s->utf8();
5605
5606 Vector<uint8_t> retval;
5607 size_t len = charstr.length();
5608 retval.resize_uninitialized(len);
5609 uint8_t *w = retval.ptrw();
5610 memcpy(w, charstr.ptr(), len);
5611
5612 return retval;
5613 }
5614
5615 Vector<uint8_t> String::to_utf16_buffer() const {
5616 const String *s = this;
5617 if (s->is_empty()) {
5618 return Vector<uint8_t>();
5619 }
5620 Char16String charstr = s->utf16();
5621
5622 Vector<uint8_t> retval;
5623 size_t len = charstr.length() * sizeof(char16_t);
5624 retval.resize_uninitialized(len);
5625 uint8_t *w = retval.ptrw();
5626 memcpy(w, (const void *)charstr.ptr(), len);
5627
5628 return retval;
5629 }
5630
5631 Vector<uint8_t> String::to_utf32_buffer() const {
5632 const String *s = this;
5633 if (s->is_empty()) {
5634 return Vector<uint8_t>();
5635 }
5636
5637 Vector<uint8_t> retval;
5638 size_t len = s->length() * sizeof(char32_t);
5639 retval.resize_uninitialized(len);
5640 uint8_t *w = retval.ptrw();
5641 memcpy(w, (const void *)s->ptr(), len);
5642
5643 return retval;
5644 }
5645
5646 Vector<uint8_t> String::to_wchar_buffer() const {
5647 #ifdef WINDOWS_ENABLED
5648 return to_utf16_buffer();
5649 #else
5650 return to_utf32_buffer();
5651 #endif
5652 }
5653
5654 Vector<uint8_t> String::to_multibyte_char_buffer(const String &p_encoding) const {
5655 return OS::get_singleton()->string_to_multibyte(p_encoding, *this);
5656 }
5657
5658 #ifdef TOOLS_ENABLED
5659 /**
5660 * "Tools TRanslate". Performs string replacement for internationalization
5661 * within the editor. A translation context can optionally be specified to
5662 * disambiguate between identical source strings in translations. When
5663 * placeholders are desired, use `vformat(TTR("Example: %s"), some_string)`.
5664 * If a string mentions a quantity (and may therefore need a dynamic plural form),
5665 * use `TTRN()` instead of `TTR()`.
5666 *
5667 * NOTE: Only use `TTR()` in editor-only code (typically within the `editor/` folder).
5668 * For translations that can be supplied by exported projects, use `RTR()` instead.
5669 */
5670 String TTR(const String &p_text, const String &p_context) {
5671 if (TranslationServer::get_singleton()) {
5672 return TranslationServer::get_singleton()->get_editor_domain()->translate(p_text, p_context);
5673 }
5674
5675 return p_text;
5676 }
5677
5678 /**
5679 * "Tools TRanslate for N items". Performs string replacement for
5680 * internationalization within the editor. A translation context can optionally
5681 * be specified to disambiguate between identical source strings in
5682 * translations. Use `TTR()` if the string doesn't need dynamic plural form.
5683 * When placeholders are desired, use
5684 * `vformat(TTRN("%d item", "%d items", some_integer), some_integer)`.
5685 * The placeholder must be present in both strings to avoid run-time warnings in `vformat()`.
5686 *
5687 * NOTE: Only use `TTRN()` in editor-only code (typically within the `editor/` folder).
5688 * For translations that can be supplied by exported projects, use `RTRN()` instead.
5689 */
5690 String TTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
5691 if (TranslationServer::get_singleton()) {
5692 return TranslationServer::get_singleton()->get_editor_domain()->translate_plural(p_text, p_text_plural, p_n, p_context);
5693 }
5694
5695 // Return message based on English plural rule if translation is not possible.
5696 if (p_n == 1) {
5697 return p_text;
5698 }
5699 return p_text_plural;
5700 }
5701
5702 /**
5703 * "Docs TRanslate". Used for the editor class reference documentation,
5704 * handling descriptions extracted from the XML.
5705 * It also replaces `$DOCS_URL` with the actual URL to the documentation's branch,
5706 * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
5707 */
5708 String DTR(const String &p_text, const String &p_context) {
5709 // Comes straight from the XML, so remove indentation and any trailing whitespace.
5710 const String text = p_text.dedent().strip_edges();
5711
5712 if (TranslationServer::get_singleton()) {
5713 return String(TranslationServer::get_singleton()->get_doc_domain()->translate(text, p_context)).replace("$DOCS_URL", GODOT_VERSION_DOCS_URL);
5714 }
5715
5716 return text.replace("$DOCS_URL", GODOT_VERSION_DOCS_URL);
5717 }
5718
5719 /**
5720 * "Docs TRanslate for N items". Used for the editor class reference documentation
5721 * (with support for plurals), handling descriptions extracted from the XML.
5722 * It also replaces `$DOCS_URL` with the actual URL to the documentation's branch,
5723 * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
5724 */
5725 String DTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
5726 const String text = p_text.dedent().strip_edges();
5727 const String text_plural = p_text_plural.dedent().strip_edges();
5728
5729 if (TranslationServer::get_singleton()) {
5730 return String(TranslationServer::get_singleton()->get_doc_domain()->translate_plural(text, text_plural, p_n, p_context)).replace("$DOCS_URL", GODOT_VERSION_DOCS_URL);
5731 }
5732
5733 // Return message based on English plural rule if translation is not possible.
5734 if (p_n == 1) {
5735 return text.replace("$DOCS_URL", GODOT_VERSION_DOCS_URL);
5736 }
5737 return text_plural.replace("$DOCS_URL", GODOT_VERSION_DOCS_URL);
5738 }
5739 #endif
5740
5741 /**
5742 * "Run-time TRanslate". Performs string replacement for internationalization
5743 * without the editor. A translation context can optionally be specified to
5744 * disambiguate between identical source strings in translations. When
5745 * placeholders are desired, use `vformat(RTR("Example: %s"), some_string)`.
5746 * If a string mentions a quantity (and may therefore need a dynamic plural form),
5747 * use `RTRN()` instead of `RTR()`.
5748 *
5749 * NOTE: Do not use `RTR()` in editor-only code (typically within the `editor/`
5750 * folder). For editor translations, use `TTR()` instead.
5751 */
5752 String RTR(const String &p_text, const String &p_context) {
5753 if (TranslationServer::get_singleton()) {
5754 #ifdef TOOLS_ENABLED
5755 String rtr = TranslationServer::get_singleton()->get_editor_domain()->translate(p_text, p_context);
5756 if (!rtr.is_empty() && rtr != p_text) {
5757 return rtr;
5758 }
5759 #endif // TOOLS_ENABLED
5760 return TranslationServer::get_singleton()->translate(p_text, p_context);
5761 }
5762
5763 return p_text;
5764 }
5765
5766 /**
5767 * "Run-time TRanslate for N items". Performs string replacement for
5768 * internationalization without the editor. A translation context can optionally
5769 * be specified to disambiguate between identical source strings in translations.
5770 * Use `RTR()` if the string doesn't need dynamic plural form. When placeholders
5771 * are desired, use `vformat(RTRN("%d item", "%d items", some_integer), some_integer)`.
5772 * The placeholder must be present in both strings to avoid run-time warnings in `vformat()`.
5773 *
5774 * NOTE: Do not use `RTRN()` in editor-only code (typically within the `editor/`
5775 * folder). For editor translations, use `TTRN()` instead.
5776 */
5777 String RTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
5778 if (TranslationServer::get_singleton()) {
5779 #ifdef TOOLS_ENABLED
5780 String rtr = TranslationServer::get_singleton()->get_editor_domain()->translate_plural(p_text, p_text_plural, p_n, p_context);
5781 if (!rtr.is_empty() && rtr != p_text && rtr != p_text_plural) {
5782 return rtr;
5783 }
5784 #endif // TOOLS_ENABLED
5785 return TranslationServer::get_singleton()->translate_plural(p_text, p_text_plural, p_n, p_context);
5786 }
5787
5788 // Return message based on English plural rule if translation is not possible.
5789 if (p_n == 1) {
5790 return p_text;
5791 }
5792 return p_text_plural;
5793 }