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