test_string.h 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  1. /**************************************************************************/
  2. /* test_string.h */
  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. #pragma once
  31. #include "core/string/ustring.h"
  32. #include "tests/test_macros.h"
  33. namespace TestString {
  34. int u32scmp(const char32_t *l, const char32_t *r) {
  35. for (; *l == *r && *l && *r; l++, r++) {
  36. // Continue.
  37. }
  38. return *l - *r;
  39. }
  40. TEST_CASE("[String] Assign Latin-1 char string") {
  41. String s = "Hello";
  42. CHECK(u32scmp(s.get_data(), U"Hello") == 0);
  43. }
  44. TEST_CASE("[String] Assign from Latin-1 char string (operator=)") {
  45. String s = "Dolly";
  46. const String &t = s;
  47. CHECK(u32scmp(t.get_data(), U"Dolly") == 0);
  48. }
  49. TEST_CASE("[String] Assign from Latin-1 char string (copycon)") {
  50. String s("Sheep");
  51. const String &t1(s);
  52. CHECK(u32scmp(t1.get_data(), U"Sheep") == 0);
  53. String t2 = String::latin1(Span("Sheep", 3));
  54. CHECK(u32scmp(t2.get_data(), U"She") == 0);
  55. }
  56. TEST_CASE("[String] Assign from wchar_t string (operator=)") {
  57. String s = L"Give me";
  58. CHECK(u32scmp(s.get_data(), U"Give me") == 0);
  59. }
  60. TEST_CASE("[String] Assign from wchar_t string (copycon)") {
  61. String s(L"Wool");
  62. CHECK(u32scmp(s.get_data(), U"Wool") == 0);
  63. }
  64. TEST_CASE("[String] Assign from char32_t string (operator=)") {
  65. String s = U"Give me";
  66. CHECK(u32scmp(s.get_data(), U"Give me") == 0);
  67. }
  68. TEST_CASE("[String] Assign from char32_t string (copycon)") {
  69. String s(U"Wool");
  70. CHECK(u32scmp(s.get_data(), U"Wool") == 0);
  71. }
  72. TEST_CASE("[String] UTF8") {
  73. /* how can i embed UTF in here? */
  74. static const char32_t u32str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
  75. static const uint8_t u8str[] = { 0x45, 0x20, 0xE3, 0x81, 0x8A, 0xE3, 0x98, 0x8F, 0xE3, 0x82, 0x88, 0xE3, 0x81, 0x86, 0xF0, 0x9F, 0x8E, 0xA4, 0 };
  76. String expected = u32str;
  77. String parsed;
  78. Error err = parsed.append_utf8(expected.utf8().get_data());
  79. CHECK(err == OK);
  80. CHECK(parsed == u32str);
  81. parsed.clear();
  82. err = parsed.append_utf8((const char *)u8str);
  83. CHECK(err == OK);
  84. CHECK(parsed == u32str);
  85. CharString cs = (const char *)u8str;
  86. CHECK(String::utf8(cs) == parsed);
  87. }
  88. TEST_CASE("[String] UTF16") {
  89. /* how can i embed UTF in here? */
  90. static const char32_t u32str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
  91. static const char16_t u16str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0xD83C, 0xDFA4, 0 };
  92. String expected = u32str;
  93. String parsed;
  94. Error err = parsed.append_utf16(expected.utf16().get_data());
  95. CHECK(err == OK);
  96. CHECK(parsed == u32str);
  97. parsed.clear();
  98. err = parsed.append_utf16(u16str);
  99. CHECK(err == OK);
  100. CHECK(parsed == u32str);
  101. Char16String cs = u16str;
  102. CHECK(String::utf16(cs) == parsed);
  103. }
  104. TEST_CASE("[String] UTF8 with BOM") {
  105. /* how can i embed UTF in here? */
  106. static const char32_t u32str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
  107. static const uint8_t u8str[] = { 0xEF, 0xBB, 0xBF, 0x45, 0x20, 0xE3, 0x81, 0x8A, 0xE3, 0x98, 0x8F, 0xE3, 0x82, 0x88, 0xE3, 0x81, 0x86, 0xF0, 0x9F, 0x8E, 0xA4, 0 };
  108. String s;
  109. Error err = s.append_utf8((const char *)u8str);
  110. CHECK(err == OK);
  111. CHECK(s == u32str);
  112. CharString cs = (const char *)u8str;
  113. CHECK(String::utf8(cs) == s);
  114. }
  115. TEST_CASE("[String] UTF16 with BOM") {
  116. /* how can i embed UTF in here? */
  117. static const char32_t u32str[] = { 0x0020, 0x0045, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
  118. static const char16_t u16str[] = { 0xFEFF, 0x0020, 0x0045, 0x304A, 0x360F, 0x3088, 0x3046, 0xD83C, 0xDFA4, 0 };
  119. static const char16_t u16str_swap[] = { 0xFFFE, 0x2000, 0x4500, 0x4A30, 0x0F36, 0x8830, 0x4630, 0x3CD8, 0xA4DF, 0 };
  120. String s;
  121. Error err = s.append_utf16(u16str);
  122. CHECK(err == OK);
  123. CHECK(s == u32str);
  124. s.clear();
  125. err = s.append_utf16(u16str_swap);
  126. CHECK(err == OK);
  127. CHECK(s == u32str);
  128. Char16String cs = u16str;
  129. CHECK(String::utf16(cs) == s);
  130. cs = u16str_swap;
  131. CHECK(String::utf16(cs) == s);
  132. }
  133. TEST_CASE("[String] UTF8 with CR") {
  134. const String base = U"Hello darkness\r\nMy old friend\nI've come to talk\rWith you again";
  135. String keep_cr;
  136. Error err = keep_cr.append_utf8(base.utf8().get_data());
  137. CHECK(err == OK);
  138. CHECK(keep_cr == base);
  139. String no_cr;
  140. err = no_cr.append_utf8(base.utf8().get_data(), -1, true); // Skip CR.
  141. CHECK(err == OK);
  142. CHECK(no_cr == base.replace("\r", ""));
  143. }
  144. TEST_CASE("[String] Invalid UTF8 (non shortest form sequence)") {
  145. ERR_PRINT_OFF
  146. // Examples from the unicode standard : 3.9 Unicode Encoding Forms - Table 3.8.
  147. static const uint8_t u8str[] = { 0xC0, 0xAF, 0xE0, 0x80, 0xBF, 0xF0, 0x81, 0x82, 0x41, 0 };
  148. static const char32_t u32str[] = { 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x41, 0 };
  149. String s;
  150. Error err = s.append_utf8((const char *)u8str);
  151. CHECK(err == ERR_INVALID_DATA);
  152. CHECK(s == u32str);
  153. CharString cs = (const char *)u8str;
  154. CHECK(String::utf8(cs) == s);
  155. ERR_PRINT_ON
  156. }
  157. TEST_CASE("[String] Invalid UTF8 (ill formed sequences for surrogates)") {
  158. ERR_PRINT_OFF
  159. // Examples from the unicode standard : 3.9 Unicode Encoding Forms - Table 3.9.
  160. static const uint8_t u8str[] = { 0xED, 0xA0, 0x80, 0xED, 0xBF, 0xBF, 0xED, 0xAF, 0x41, 0 };
  161. static const char32_t u32str[] = { 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x41, 0 };
  162. String s;
  163. Error err = s.append_utf8((const char *)u8str);
  164. CHECK(err == ERR_INVALID_DATA);
  165. CHECK(s == u32str);
  166. CharString cs = (const char *)u8str;
  167. CHECK(String::utf8(cs) == s);
  168. ERR_PRINT_ON
  169. }
  170. TEST_CASE("[String] Invalid UTF8 (other ill formed sequences)") {
  171. ERR_PRINT_OFF
  172. // Examples from the unicode standard : 3.9 Unicode Encoding Forms - Table 3.10.
  173. static const uint8_t u8str[] = { 0xF4, 0x91, 0x92, 0x93, 0xFF, 0x41, 0x80, 0xBF, 0x42, 0 };
  174. static const char32_t u32str[] = { 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x41, 0xFFFD, 0xFFFD, 0x42, 0 };
  175. String s;
  176. Error err = s.append_utf8((const char *)u8str);
  177. CHECK(err == ERR_INVALID_DATA);
  178. CHECK(s == u32str);
  179. CharString cs = (const char *)u8str;
  180. CHECK(String::utf8(cs) == s);
  181. ERR_PRINT_ON
  182. }
  183. TEST_CASE("[String] Invalid UTF8 (truncated sequences)") {
  184. ERR_PRINT_OFF
  185. // Examples from the unicode standard : 3.9 Unicode Encoding Forms - Table 3.11.
  186. static const uint8_t u8str[] = { 0xE1, 0x80, 0xE2, 0xF0, 0x91, 0x92, 0xF1, 0xBF, 0x41, 0 };
  187. static const char32_t u32str[] = { 0xFFFD, 0xFFFD, 0xFFFD, 0xFFFD, 0x41, 0 };
  188. String s;
  189. Error err = s.append_utf8((const char *)u8str);
  190. CHECK(err == ERR_INVALID_DATA);
  191. CHECK(s == u32str);
  192. CharString cs = (const char *)u8str;
  193. CHECK(String::utf8(cs) == s);
  194. ERR_PRINT_ON
  195. }
  196. TEST_CASE("[String] Invalid UTF16 (non-standard)") {
  197. ERR_PRINT_OFF
  198. static const char16_t u16str[] = { 0x0045, 0x304A, 0x3088, 0x3046, 0xDFA4, 0 };
  199. // + + + + unpaired
  200. static const char32_t u32str[] = { 0x0045, 0x304A, 0x3088, 0x3046, 0xDFA4, 0 };
  201. String s;
  202. Error err = s.append_utf16(u16str);
  203. CHECK(err == ERR_PARSE_ERROR);
  204. CHECK(s == u32str);
  205. Char16String cs = u16str;
  206. CHECK(String::utf16(cs) == s);
  207. ERR_PRINT_ON
  208. }
  209. TEST_CASE("[String] ASCII") {
  210. String s = U"Primero Leche";
  211. String t = s.ascii(false).get_data();
  212. CHECK(s == t);
  213. t = s.ascii(true).get_data();
  214. CHECK(s == t);
  215. }
  216. TEST_CASE("[String] Comparisons (equal)") {
  217. String s = "Test Compare";
  218. CHECK(s == "Test Compare");
  219. CHECK(s == U"Test Compare");
  220. CHECK(s == L"Test Compare");
  221. CHECK(s == String("Test Compare"));
  222. CharString empty = "";
  223. CharString cs = "Test Compare";
  224. CHECK(!(empty == cs));
  225. CHECK(!(cs == empty));
  226. CHECK(cs == CharString("Test Compare"));
  227. }
  228. TEST_CASE("[String] Comparisons (not equal)") {
  229. String s = "Test Compare";
  230. CHECK(s != "Peanut");
  231. CHECK(s != U"Coconut");
  232. CHECK(s != L"Coconut");
  233. CHECK(s != String("Butter"));
  234. }
  235. TEST_CASE("[String] Comparisons (operator <)") {
  236. String s = "Bees";
  237. CHECK(s < "Elephant");
  238. CHECK(!(s < U"Amber"));
  239. CHECK(!(s < L"Amber"));
  240. CHECK(!(s < String("Beatrix")));
  241. }
  242. TEST_CASE("[String] Concatenation") {
  243. String s;
  244. s += "Have";
  245. s += ' ';
  246. s += 'a';
  247. s += String(" ");
  248. s = s + U"Nice";
  249. s = s + " ";
  250. s = s + String("Day");
  251. CHECK(s == "Have a Nice Day");
  252. }
  253. TEST_CASE("[String] Testing size and length of string") {
  254. // todo: expand this test to do more tests on size() as it is complicated under the hood.
  255. CHECK(String("Mellon").size() == 7);
  256. CHECK(String("Mellon1").size() == 8);
  257. // length works fine and is easier to test
  258. CHECK(String("Mellon").length() == 6);
  259. CHECK(String("Mellon1").length() == 7);
  260. CHECK(String("Mellon2").length() == 7);
  261. CHECK(String("Mellon3").length() == 7);
  262. }
  263. TEST_CASE("[String] Testing for empty string") {
  264. CHECK(!String("Mellon").is_empty());
  265. // do this more than once, to check for string corruption
  266. CHECK(String("").is_empty());
  267. CHECK(String("").is_empty());
  268. CHECK(String("").is_empty());
  269. }
  270. TEST_CASE("[String] Contains") {
  271. String s = "C:\\Godot\\project\\string_test.tscn";
  272. CHECK(s.contains(":\\"));
  273. CHECK(s.contains("Godot"));
  274. CHECK(s.contains(String("project\\string_test")));
  275. CHECK(s.contains(String("\\string_test.tscn")));
  276. CHECK(!s.contains("://"));
  277. CHECK(!s.contains("Godoh"));
  278. CHECK(!s.contains(String("project\\string test")));
  279. CHECK(!s.contains(String("\\char_test.tscn")));
  280. }
  281. TEST_CASE("[String] Contains case insensitive") {
  282. String s = "C:\\Godot\\project\\string_test.tscn";
  283. CHECK(s.containsn("Godot"));
  284. CHECK(s.containsn("godot"));
  285. CHECK(s.containsn(String("Project\\string_test")));
  286. CHECK(s.containsn(String("\\string_Test.tscn")));
  287. CHECK(!s.containsn("Godoh"));
  288. CHECK(!s.containsn("godoh"));
  289. CHECK(!s.containsn(String("project\\string test")));
  290. CHECK(!s.containsn(String("\\char_test.tscn")));
  291. }
  292. TEST_CASE("[String] Test chr") {
  293. CHECK(String::chr('H') == "H");
  294. CHECK(String::chr(0x3012)[0] == 0x3012);
  295. ERR_PRINT_OFF
  296. CHECK(String::chr(0xd812)[0] == 0xfffd); // Unpaired UTF-16 surrogate
  297. CHECK(String::chr(0x20d812)[0] == 0xfffd); // Outside UTF-32 range
  298. ERR_PRINT_ON
  299. }
  300. TEST_CASE("[String] Operator []") {
  301. String a = "Kugar Sane";
  302. a[0] = 'S';
  303. a[6] = 'C';
  304. CHECK(a == "Sugar Cane");
  305. CHECK(a[1] == 'u');
  306. CHECK(a.unicode_at(1) == 'u');
  307. }
  308. TEST_CASE("[String] Case function test") {
  309. String a = "MoMoNgA";
  310. CHECK(a.to_upper() == "MOMONGA");
  311. CHECK(a.to_lower() == "momonga");
  312. }
  313. TEST_CASE("[String] Case compare function test") {
  314. String a = "MoMoNgA";
  315. CHECK(a.casecmp_to("momonga") != 0);
  316. CHECK(a.nocasecmp_to("momonga") == 0);
  317. }
  318. TEST_CASE("[String] Natural compare function test") {
  319. String a = "img2.png";
  320. CHECK(a.nocasecmp_to("img10.png") > 0);
  321. CHECK(a.naturalnocasecmp_to("img10.png") < 0);
  322. }
  323. TEST_CASE("[String] File compare function test") {
  324. String a = "_img2.png";
  325. String b = "img2.png";
  326. CHECK(a.nocasecmp_to("img10.png") > 0);
  327. CHECK_MESSAGE(a.filenocasecmp_to("img10.png") < 0, "Should sort before letters.");
  328. CHECK_MESSAGE(a.filenocasecmp_to(".img10.png") > 0, "Should sort after period.");
  329. CHECK(b.filenocasecmp_to("img3.png") < 0);
  330. }
  331. TEST_CASE("[String] hex_encode_buffer") {
  332. static const uint8_t u8str[] = { 0x45, 0xE3, 0x81, 0x8A, 0x8F, 0xE3 };
  333. String s = String::hex_encode_buffer(u8str, 6);
  334. CHECK(s == U"45e3818a8fe3");
  335. }
  336. TEST_CASE("[String] Substr") {
  337. String s = "Killer Baby";
  338. CHECK(s.substr(3, 4) == "ler ");
  339. CHECK(s.substr(3) == "ler Baby");
  340. }
  341. TEST_CASE("[String] Find") {
  342. String s = "Pretty Woman Woman";
  343. MULTICHECK_STRING_EQ(s, find, "tty", 3);
  344. MULTICHECK_STRING_EQ(s, find, "Revenge of the Monster Truck", -1);
  345. MULTICHECK_STRING_INT_EQ(s, find, "Wo", 9, 13);
  346. MULTICHECK_STRING_EQ(s, find, "", -1);
  347. MULTICHECK_STRING_EQ(s, find, "Pretty Woman Woman", 0);
  348. MULTICHECK_STRING_EQ(s, find, "WOMAN", -1);
  349. MULTICHECK_STRING_INT_EQ(s, find, "", 9, -1);
  350. MULTICHECK_STRING_EQ(s, rfind, "", -1);
  351. MULTICHECK_STRING_EQ(s, rfind, "foo", -1);
  352. MULTICHECK_STRING_EQ(s, rfind, "Pretty Woman Woman", 0);
  353. MULTICHECK_STRING_EQ(s, rfind, "man", 15);
  354. MULTICHECK_STRING_EQ(s, rfind, "WOMAN", -1);
  355. MULTICHECK_STRING_INT_EQ(s, rfind, "", 15, -1);
  356. }
  357. TEST_CASE("[String] Find character") {
  358. String s = "racecar";
  359. CHECK_EQ(s.find_char('r'), 0);
  360. CHECK_EQ(s.find_char('r', 1), 6);
  361. CHECK_EQ(s.find_char('e'), 3);
  362. CHECK_EQ(s.find_char('e', 4), -1);
  363. CHECK_EQ(s.rfind_char('r'), 6);
  364. CHECK_EQ(s.rfind_char('r', 5), 0);
  365. CHECK_EQ(s.rfind_char('e'), 3);
  366. CHECK_EQ(s.rfind_char('e', 2), -1);
  367. }
  368. TEST_CASE("[String] Find case insensitive") {
  369. String s = "Pretty Whale Whale";
  370. MULTICHECK_STRING_EQ(s, findn, "WHA", 7);
  371. MULTICHECK_STRING_INT_EQ(s, findn, "WHA", 9, 13);
  372. MULTICHECK_STRING_EQ(s, findn, "Revenge of the Monster SawFish", -1);
  373. MULTICHECK_STRING_EQ(s, findn, "", -1);
  374. MULTICHECK_STRING_EQ(s, findn, "wha", 7);
  375. MULTICHECK_STRING_EQ(s, findn, "Wha", 7);
  376. MULTICHECK_STRING_INT_EQ(s, findn, "", 3, -1);
  377. MULTICHECK_STRING_EQ(s, rfindn, "WHA", 13);
  378. MULTICHECK_STRING_EQ(s, rfindn, "", -1);
  379. MULTICHECK_STRING_EQ(s, rfindn, "wha", 13);
  380. MULTICHECK_STRING_EQ(s, rfindn, "Wha", 13);
  381. MULTICHECK_STRING_INT_EQ(s, rfindn, "", 13, -1);
  382. }
  383. TEST_CASE("[String] Find MK") {
  384. Vector<String> keys;
  385. keys.push_back("sty");
  386. keys.push_back("tty");
  387. keys.push_back("man");
  388. String s = "Pretty Woman";
  389. int key = 0;
  390. CHECK(s.findmk(keys, 0, &key) == 3);
  391. CHECK(key == 1);
  392. CHECK(s.findmk(keys, 5, &key) == 9);
  393. CHECK(key == 2);
  394. }
  395. TEST_CASE("[String] Find and replace") {
  396. String s = "Happy Birthday, Anna!";
  397. MULTICHECK_STRING_STRING_EQ(s, replace, "Birthday", "Halloween", "Happy Halloween, Anna!");
  398. MULTICHECK_STRING_STRING_EQ(s, replace_first, "y", "Y", "HappY Birthday, Anna!");
  399. MULTICHECK_STRING_STRING_EQ(s, replacen, "Y", "Y", "HappY BirthdaY, Anna!");
  400. }
  401. TEST_CASE("[String] Insertion") {
  402. String s = "Who is Frederic?";
  403. s = s.insert(s.find("?"), " Chopin");
  404. CHECK(s == "Who is Frederic Chopin?");
  405. s = "foobar";
  406. CHECK(s.insert(0, "X") == "Xfoobar");
  407. CHECK(s.insert(-100, "X") == "foobar");
  408. CHECK(s.insert(6, "X") == "foobarX");
  409. CHECK(s.insert(100, "X") == "foobarX");
  410. CHECK(s.insert(2, "") == "foobar");
  411. s = "";
  412. CHECK(s.insert(0, "abc") == "abc");
  413. CHECK(s.insert(100, "abc") == "abc");
  414. CHECK(s.insert(-100, "abc") == "");
  415. CHECK(s.insert(0, "") == "");
  416. }
  417. TEST_CASE("[String] Erasing") {
  418. String s = "Josephine is such a cute girl!";
  419. s = s.erase(s.find("cute "), String("cute ").length());
  420. CHECK(s == "Josephine is such a girl!");
  421. }
  422. TEST_CASE("[String] remove_char") {
  423. String s = "Banana";
  424. CHECK(s.remove_char('a') == "Bnn");
  425. CHECK(s.remove_char('\0') == "Banana");
  426. CHECK(s.remove_char('x') == "Banana");
  427. }
  428. TEST_CASE("[String] remove_chars") {
  429. String s = "Banana";
  430. CHECK(s.remove_chars("Ba") == "nn");
  431. CHECK(s.remove_chars(String("Ba")) == "nn");
  432. CHECK(s.remove_chars("") == "Banana");
  433. CHECK(s.remove_chars(String()) == "Banana");
  434. CHECK(s.remove_chars("xy") == "Banana");
  435. CHECK(s.remove_chars(String("xy")) == "Banana");
  436. }
  437. TEST_CASE("[String] Number to string") {
  438. CHECK(String::num(0) == "0.0"); // The method takes double, so always add zeros.
  439. CHECK(String::num(0.0) == "0.0");
  440. CHECK(String::num(-0.0) == "-0.0"); // Includes sign even for zero.
  441. CHECK(String::num(3.141593) == "3.141593");
  442. CHECK(String::num(3.141593, 3) == "3.142");
  443. CHECK(String::num(42.100023, 4) == "42.1"); // No trailing zeros.
  444. CHECK(String::num_scientific(30000000) == "3e+07");
  445. // String::num_int64 tests.
  446. CHECK(String::num_int64(3141593) == "3141593");
  447. CHECK(String::num_int64(-3141593) == "-3141593");
  448. CHECK(String::num_int64(0xA141593, 16) == "a141593");
  449. CHECK(String::num_int64(0xA141593, 16, true) == "A141593");
  450. ERR_PRINT_OFF;
  451. CHECK(String::num_int64(3141593, 1) == ""); // Invalid base < 2.
  452. CHECK(String::num_int64(3141593, 37) == ""); // Invalid base > 36.
  453. ERR_PRINT_ON;
  454. // String::num_uint64 tests.
  455. CHECK(String::num_uint64(4294967295) == "4294967295");
  456. CHECK(String::num_uint64(0xF141593, 16) == "f141593");
  457. CHECK(String::num_uint64(0xF141593, 16, true) == "F141593");
  458. ERR_PRINT_OFF;
  459. CHECK(String::num_uint64(4294967295, 1) == ""); // Invalid base < 2.
  460. CHECK(String::num_uint64(4294967295, 37) == ""); // Invalid base > 36.
  461. ERR_PRINT_ON;
  462. // String::num_real tests.
  463. CHECK(String::num_real(1.0) == "1.0");
  464. CHECK(String::num_real(1.0, false) == "1");
  465. CHECK(String::num_real(9.9) == "9.9");
  466. CHECK(String::num_real(9.99) == "9.99");
  467. CHECK(String::num_real(9.999) == "9.999");
  468. CHECK(String::num_real(9.9999) == "9.9999");
  469. CHECK(String::num_real(3.141593) == "3.141593");
  470. CHECK(String::num_real(3.141) == "3.141"); // No trailing zeros.
  471. #ifdef REAL_T_IS_DOUBLE
  472. CHECK_MESSAGE(String::num_real(real_t(123.456789)) == "123.456789", "Prints the appropriate amount of digits for real_t = double.");
  473. CHECK_MESSAGE(String::num_real(real_t(-123.456789)) == "-123.456789", "Prints the appropriate amount of digits for real_t = double.");
  474. CHECK_MESSAGE(String::num_real(real_t(Math_PI)) == "3.14159265358979", "Prints the appropriate amount of digits for real_t = double.");
  475. CHECK_MESSAGE(String::num_real(real_t(3.1415f)) == "3.1414999961853", "Prints more digits of 32-bit float when real_t = double (ones that would be reliable for double) and no trailing zero.");
  476. #else
  477. CHECK_MESSAGE(String::num_real(real_t(123.456789)) == "123.4568", "Prints the appropriate amount of digits for real_t = float.");
  478. CHECK_MESSAGE(String::num_real(real_t(-123.456789)) == "-123.4568", "Prints the appropriate amount of digits for real_t = float.");
  479. CHECK_MESSAGE(String::num_real(real_t(Math_PI)) == "3.141593", "Prints the appropriate amount of digits for real_t = float.");
  480. CHECK_MESSAGE(String::num_real(real_t(3.1415f)) == "3.1415", "Prints only reliable digits of 32-bit float when real_t = float.");
  481. #endif // REAL_T_IS_DOUBLE
  482. // Checks doubles with many decimal places.
  483. CHECK(String::num(0.0000012345432123454321, -1) == "0.00000123454321"); // -1 uses 14 as sane default.
  484. CHECK(String::num(0.0000012345432123454321) == "0.00000123454321"); // -1 is the default value.
  485. CHECK(String::num(-0.0000012345432123454321) == "-0.00000123454321");
  486. CHECK(String::num(-10000.0000012345432123454321) == "-10000.0000012345");
  487. CHECK(String::num(0.0000000000012345432123454321) == "0.00000000000123");
  488. CHECK(String::num(0.0000000000012345432123454321, 3) == "0.0");
  489. // Note: When relevant (remainder > 0.5), the last digit gets rounded up,
  490. // which can also lead to not include a trailing zero, e.g. "...89" -> "...9".
  491. CHECK(String::num(0.0000056789876567898765) == "0.00000567898766"); // Should round last digit.
  492. CHECK(String::num(10000.000005678999999999) == "10000.000005679"); // We cut at ...789|99 which is rounded to ...79, so only 13 decimals.
  493. CHECK(String::num(42.12999999, 6) == "42.13"); // Also happens with lower decimals count.
  494. // 32 is MAX_DECIMALS. We can't reliably store that many so we can't compare against a string,
  495. // but we can check that the string length is 34 (32 + 2 for "0.").
  496. CHECK(String::num(0.00000123456789987654321123456789987654321, 32).length() == 34);
  497. CHECK(String::num(0.00000123456789987654321123456789987654321, 42).length() == 34); // Should enforce MAX_DECIMALS.
  498. CHECK(String::num(10000.00000123456789987654321123456789987654321, 42).length() == 38); // 32 decimals + "10000.".
  499. }
  500. TEST_CASE("[String] String to integer") {
  501. static const char *nums[14] = { "1237461283", "- 22", "0", " - 1123412", "", "10_000_000", "-1_2_3_4", "10__000", " 1 2 34 ", "-0", "007", "--45", "---46", "-7-2" };
  502. static const int num[14] = { 1237461283, -22, 0, -1123412, 0, 10000000, -1234, 10000, 1234, 0, 7, 45, -46, -72 };
  503. for (int i = 0; i < 14; i++) {
  504. CHECK(String(nums[i]).to_int() == num[i]);
  505. }
  506. CHECK(String("0b1011").to_int() == 1011); // Looks like a binary number, but to_int() handles this as a base-10 number, "b" is just ignored.
  507. CHECK(String("0B1011").to_int() == 1011);
  508. CHECK(String("0x1012").to_int() == 1012); // Looks like a hexadecimal number, but to_int() handles this as a base-10 number, "x" is just ignored.
  509. CHECK(String("0X1012").to_int() == 1012);
  510. ERR_PRINT_OFF
  511. CHECK(String("999999999999999999999999999999999999999999999999999999999").to_int() == INT64_MAX); // Too large, largest possible is returned.
  512. CHECK(String("-999999999999999999999999999999999999999999999999999999999").to_int() == INT64_MIN); // Too small, smallest possible is returned.
  513. ERR_PRINT_ON
  514. }
  515. TEST_CASE("[String] Hex to integer") {
  516. static const char *nums[13] = { "0xFFAE", "22", "0", "AADDAD", "0x7FFFFFFFFFFFFFFF", "-0xf", "", "000", "000f", "0xaA", "-ff", "-", "0XFFAE" };
  517. static const int64_t num[13] = { 0xFFAE, 0x22, 0, 0xAADDAD, 0x7FFFFFFFFFFFFFFF, -0xf, 0, 0, 0xf, 0xaa, -0xff, 0x0, 0xFFAE };
  518. for (int i = 0; i < 13; i++) {
  519. CHECK(String(nums[i]).hex_to_int() == num[i]);
  520. }
  521. // Invalid hex strings should return 0.
  522. static const char *invalid_nums[15] = { "qwerty", "QWERTY", "0xqwerty", "0x00qwerty", "qwerty00", "0x", "0x__", "__", "x12", "+", " ff", "ff ", "f f", "+ff", "--0x78" };
  523. ERR_PRINT_OFF
  524. for (int i = 0; i < 15; i++) {
  525. CHECK(String(invalid_nums[i]).hex_to_int() == 0);
  526. }
  527. CHECK(String("0xFFFFFFFFFFFFFFFFFFFFFFF").hex_to_int() == INT64_MAX); // Too large, largest possible is returned.
  528. CHECK(String("-0xFFFFFFFFFFFFFFFFFFFFFFF").hex_to_int() == INT64_MIN); // Too small, smallest possible is returned.
  529. ERR_PRINT_ON
  530. }
  531. TEST_CASE("[String] Bin to integer") {
  532. static const char *nums[11] = { "", "0", "0b0", "0b1", "0b", "1", "0b1010", "-0b11", "-1010", "0b0111111111111111111111111111111111111111111111111111111111111111", "0B1010" };
  533. static const int64_t num[11] = { 0, 0, 0, 1, 0, 1, 10, -3, -10, 0x7FFFFFFFFFFFFFFF, 10 };
  534. for (int i = 0; i < 11; i++) {
  535. CHECK(String(nums[i]).bin_to_int() == num[i]);
  536. }
  537. // Invalid bin strings should return 0. The long "0x11...11" is just too long for a 64 bit int.
  538. static const char *invalid_nums[16] = { "qwerty", "QWERTY", "0bqwerty", "0b00qwerty", "qwerty00", "0x__", "0b__", "__", "b12", "+", "-", "0x12ab", " 11", "11 ", "1 1", "--0b11" };
  539. for (int i = 0; i < 16; i++) {
  540. CHECK(String(invalid_nums[i]).bin_to_int() == 0);
  541. }
  542. ERR_PRINT_OFF
  543. CHECK(String("0b111111111111111111111111111111111111111111111111111111111111111111111111111111111").bin_to_int() == INT64_MAX); // Too large, largest possible is returned.
  544. CHECK(String("-0b111111111111111111111111111111111111111111111111111111111111111111111111111111111").bin_to_int() == INT64_MIN); // Too small, smallest possible is returned.
  545. ERR_PRINT_ON
  546. }
  547. TEST_CASE("[String] String to float") {
  548. static const char *nums[12] = { "-12348298412.2", "0.05", "2.0002", " -0.0001", "0", "000", "123", "0.0", "000.000", "000.007", "234__", "3..14" };
  549. static const double num[12] = { -12348298412.2, 0.05, 2.0002, -0.0001, 0.0, 0.0, 123.0, 0.0, 0.0, 0.007, 234.0, 3.0 };
  550. for (int i = 0; i < 12; i++) {
  551. CHECK(!(Math::abs(String(nums[i]).to_float() - num[i]) > 0.00001));
  552. }
  553. // Invalid float strings should return 0.
  554. static const char *invalid_nums[6] = { "qwerty", "qwerty123", "0xffff", "0b1010", "--3.13", "__345" };
  555. for (int i = 0; i < 6; i++) {
  556. CHECK(String(invalid_nums[i]).to_float() == 0);
  557. }
  558. // Very large exponents.
  559. CHECK(String("1e308").to_float() == 1e308);
  560. CHECK(String("-1e308").to_float() == -1e308);
  561. // Exponent is so high that value is INFINITY/-INFINITY.
  562. CHECK(String("1e309").to_float() == INFINITY);
  563. CHECK(String("1e511").to_float() == INFINITY);
  564. CHECK(String("-1e309").to_float() == -INFINITY);
  565. CHECK(String("-1e511").to_float() == -INFINITY);
  566. // Exponent is so high that a warning message is printed. Value is INFINITY/-INFINITY.
  567. ERR_PRINT_OFF
  568. CHECK(String("1e512").to_float() == INFINITY);
  569. CHECK(String("-1e512").to_float() == -INFINITY);
  570. ERR_PRINT_ON
  571. }
  572. TEST_CASE("[String] Slicing") {
  573. String s = "Mars,Jupiter,Saturn,Uranus";
  574. const char *slices[4] = { "Mars", "Jupiter", "Saturn", "Uranus" };
  575. MULTICHECK_GET_SLICE(s, ",", slices);
  576. }
  577. TEST_CASE("[String] Begins with") {
  578. // Test cases for true:
  579. MULTICHECK_STRING_EQ(String("res://foobar"), begins_with, "res://", true);
  580. MULTICHECK_STRING_EQ(String("abc"), begins_with, "abc", true);
  581. MULTICHECK_STRING_EQ(String("abc"), begins_with, "", true);
  582. MULTICHECK_STRING_EQ(String(""), begins_with, "", true);
  583. // Test cases for false:
  584. MULTICHECK_STRING_EQ(String("res"), begins_with, "res://", false);
  585. MULTICHECK_STRING_EQ(String("abcdef"), begins_with, "foo", false);
  586. MULTICHECK_STRING_EQ(String("abc"), begins_with, "ax", false);
  587. MULTICHECK_STRING_EQ(String(""), begins_with, "abc", false);
  588. // Test "const char *" version also with nullptr.
  589. String s("foo");
  590. bool state = s.begins_with(nullptr) == false;
  591. CHECK_MESSAGE(state, "nullptr check failed");
  592. String empty("");
  593. state = empty.begins_with(nullptr) == false;
  594. CHECK_MESSAGE(state, "nullptr check with empty string failed");
  595. }
  596. TEST_CASE("[String] Ends with") {
  597. // Test cases for true:
  598. MULTICHECK_STRING_EQ(String("res://foobar"), ends_with, "foobar", true);
  599. MULTICHECK_STRING_EQ(String("abc"), ends_with, "abc", true);
  600. MULTICHECK_STRING_EQ(String("abc"), ends_with, "", true);
  601. MULTICHECK_STRING_EQ(String(""), ends_with, "", true);
  602. // Test cases for false:
  603. MULTICHECK_STRING_EQ(String("res"), ends_with, "res://", false);
  604. MULTICHECK_STRING_EQ(String("abcdef"), ends_with, "foo", false);
  605. MULTICHECK_STRING_EQ(String("abc"), ends_with, "ax", false);
  606. MULTICHECK_STRING_EQ(String(""), ends_with, "abc", false);
  607. // Test "const char *" version also with nullptr.
  608. String s("foo");
  609. bool state = s.ends_with(nullptr) == false;
  610. CHECK_MESSAGE(state, "nullptr check failed");
  611. String empty("");
  612. state = empty.ends_with(nullptr) == false;
  613. CHECK_MESSAGE(state, "nullptr check with empty string failed");
  614. }
  615. TEST_CASE("[String] Splitting") {
  616. {
  617. const String s = "Mars,Jupiter,Saturn,Uranus";
  618. const char *slices_l[3] = { "Mars", "Jupiter", "Saturn,Uranus" };
  619. MULTICHECK_SPLIT(s, split, ",", true, 2, slices_l, 3);
  620. const char *slices_r[3] = { "Mars,Jupiter", "Saturn", "Uranus" };
  621. MULTICHECK_SPLIT(s, rsplit, ",", true, 2, slices_r, 3);
  622. }
  623. {
  624. const String s = "test";
  625. const char *slices[4] = { "t", "e", "s", "t" };
  626. MULTICHECK_SPLIT(s, split, "", true, 0, slices, 4);
  627. }
  628. {
  629. const String s = "";
  630. const char *slices[1] = { "" };
  631. MULTICHECK_SPLIT(s, split, "", true, 0, slices, 1);
  632. MULTICHECK_SPLIT(s, split, "", false, 0, slices, 0);
  633. }
  634. {
  635. const String s = "Mars Jupiter Saturn Uranus";
  636. const char *slices[4] = { "Mars", "Jupiter", "Saturn", "Uranus" };
  637. Vector<String> l = s.split_spaces();
  638. for (int i = 0; i < l.size(); i++) {
  639. CHECK(l[i] == slices[i]);
  640. }
  641. }
  642. {
  643. const String s = "Mars Jupiter Saturn Uranus";
  644. const char *slices[2] = { "Mars", "Jupiter Saturn Uranus" };
  645. Vector<String> l = s.split_spaces(1);
  646. for (int i = 0; i < l.size(); i++) {
  647. CHECK(l[i] == slices[i]);
  648. }
  649. }
  650. {
  651. const String s = "1.2;2.3 4.5";
  652. const double slices[3] = { 1.2, 2.3, 4.5 };
  653. const Vector<double> d_arr = s.split_floats(";");
  654. CHECK(d_arr.size() == 2);
  655. for (int i = 0; i < d_arr.size(); i++) {
  656. CHECK(Math::abs(d_arr[i] - slices[i]) <= 0.00001);
  657. }
  658. const Vector<String> keys = { ";", " " };
  659. const Vector<float> f_arr = s.split_floats_mk(keys);
  660. CHECK(f_arr.size() == 3);
  661. for (int i = 0; i < f_arr.size(); i++) {
  662. CHECK(Math::abs(f_arr[i] - slices[i]) <= 0.00001);
  663. }
  664. }
  665. {
  666. const String s = " -2.0 5";
  667. const double slices[10] = { 0, -2, 0, 0, 0, 0, 0, 0, 0, 5 };
  668. const Vector<double> arr = s.split_floats(" ");
  669. CHECK(arr.size() == 10);
  670. for (int i = 0; i < arr.size(); i++) {
  671. CHECK(Math::abs(arr[i] - slices[i]) <= 0.00001);
  672. }
  673. const Vector<String> keys = { ";", " " };
  674. const Vector<float> mk = s.split_floats_mk(keys);
  675. CHECK(mk.size() == 10);
  676. for (int i = 0; i < mk.size(); i++) {
  677. CHECK(mk[i] == slices[i]);
  678. }
  679. }
  680. {
  681. const String s = "1;2 4";
  682. const int slices[3] = { 1, 2, 4 };
  683. const Vector<int> arr = s.split_ints(";");
  684. CHECK(arr.size() == 2);
  685. for (int i = 0; i < arr.size(); i++) {
  686. CHECK(arr[i] == slices[i]);
  687. }
  688. const Vector<String> keys = { ";", " " };
  689. const Vector<int> mk = s.split_ints_mk(keys);
  690. CHECK(mk.size() == 3);
  691. for (int i = 0; i < mk.size(); i++) {
  692. CHECK(mk[i] == slices[i]);
  693. }
  694. }
  695. }
  696. TEST_CASE("[String] format") {
  697. const String value_format = "red=\"$red\" green=\"$green\" blue=\"$blue\" alpha=\"$alpha\"";
  698. Dictionary value_dictionary;
  699. value_dictionary["red"] = 10;
  700. value_dictionary["green"] = 20;
  701. value_dictionary["blue"] = "bla";
  702. value_dictionary["alpha"] = 0.4;
  703. String value = value_format.format(value_dictionary, "$_");
  704. CHECK(value == "red=\"10\" green=\"20\" blue=\"bla\" alpha=\"0.4\"");
  705. }
  706. TEST_CASE("[String] sprintf") {
  707. String format, output;
  708. Array args;
  709. bool error;
  710. // %%
  711. format = "fish %% frog";
  712. args.clear();
  713. output = format.sprintf(args, &error);
  714. REQUIRE(error == false);
  715. CHECK(output == String("fish % frog"));
  716. ///// Ints
  717. // Int
  718. format = "fish %d frog";
  719. args.clear();
  720. args.push_back(5);
  721. output = format.sprintf(args, &error);
  722. REQUIRE(error == false);
  723. CHECK(output == String("fish 5 frog"));
  724. // Int left padded with zeroes.
  725. format = "fish %05d frog";
  726. args.clear();
  727. args.push_back(5);
  728. output = format.sprintf(args, &error);
  729. REQUIRE(error == false);
  730. CHECK(output == String("fish 00005 frog"));
  731. // Int left padded with spaces.
  732. format = "fish %5d frog";
  733. args.clear();
  734. args.push_back(5);
  735. output = format.sprintf(args, &error);
  736. REQUIRE(error == false);
  737. CHECK(output == String("fish 5 frog"));
  738. // Int right padded with spaces.
  739. format = "fish %-5d frog";
  740. args.clear();
  741. args.push_back(5);
  742. output = format.sprintf(args, &error);
  743. REQUIRE(error == false);
  744. CHECK(output == String("fish 5 frog"));
  745. // Int with sign (positive).
  746. format = "fish %+d frog";
  747. args.clear();
  748. args.push_back(5);
  749. output = format.sprintf(args, &error);
  750. REQUIRE(error == false);
  751. CHECK(output == String("fish +5 frog"));
  752. // Negative int.
  753. format = "fish %d frog";
  754. args.clear();
  755. args.push_back(-5);
  756. output = format.sprintf(args, &error);
  757. REQUIRE(error == false);
  758. CHECK(output == String("fish -5 frog"));
  759. // Negative int left padded with spaces.
  760. format = "fish %5d frog";
  761. args.clear();
  762. args.push_back(-5);
  763. output = format.sprintf(args, &error);
  764. REQUIRE(error == false);
  765. CHECK(output == String("fish -5 frog"));
  766. // Negative int left padded with zeros.
  767. format = "fish %05d frog";
  768. args.clear();
  769. args.push_back(-5);
  770. output = format.sprintf(args, &error);
  771. REQUIRE(error == false);
  772. CHECK(output == String("fish -0005 frog"));
  773. // Negative int right padded with spaces.
  774. format = "fish %-5d frog";
  775. args.clear();
  776. args.push_back(-5);
  777. output = format.sprintf(args, &error);
  778. REQUIRE(error == false);
  779. CHECK(output == String("fish -5 frog"));
  780. // Negative int right padded with zeros. (0 ignored)
  781. format = "fish %-05d frog";
  782. args.clear();
  783. args.push_back(-5);
  784. ERR_PRINT_OFF; // Silence warning about 0 ignored.
  785. output = format.sprintf(args, &error);
  786. ERR_PRINT_ON;
  787. REQUIRE(error == false);
  788. CHECK(output == String("fish -5 frog"));
  789. // Hex (lower)
  790. format = "fish %x frog";
  791. args.clear();
  792. args.push_back(45);
  793. output = format.sprintf(args, &error);
  794. REQUIRE(error == false);
  795. CHECK(output == String("fish 2d frog"));
  796. // Hex (upper)
  797. format = "fish %X frog";
  798. args.clear();
  799. args.push_back(45);
  800. output = format.sprintf(args, &error);
  801. REQUIRE(error == false);
  802. CHECK(output == String("fish 2D frog"));
  803. // Octal
  804. format = "fish %o frog";
  805. args.clear();
  806. args.push_back(99);
  807. output = format.sprintf(args, &error);
  808. REQUIRE(error == false);
  809. CHECK(output == String("fish 143 frog"));
  810. ///// Reals
  811. // Real
  812. format = "fish %f frog";
  813. args.clear();
  814. args.push_back(99.99);
  815. output = format.sprintf(args, &error);
  816. REQUIRE(error == false);
  817. CHECK(output == String("fish 99.990000 frog"));
  818. // Real left-padded.
  819. format = "fish %11f frog";
  820. args.clear();
  821. args.push_back(99.99);
  822. output = format.sprintf(args, &error);
  823. REQUIRE(error == false);
  824. CHECK(output == String("fish 99.990000 frog"));
  825. // Real (infinity) left-padded
  826. format = "fish %11f frog";
  827. args.clear();
  828. args.push_back(INFINITY);
  829. output = format.sprintf(args, &error);
  830. REQUIRE(error == false);
  831. CHECK(output == String("fish inf frog"));
  832. // Real right-padded.
  833. format = "fish %-11f frog";
  834. args.clear();
  835. args.push_back(99.99);
  836. output = format.sprintf(args, &error);
  837. REQUIRE(error == false);
  838. CHECK(output == String("fish 99.990000 frog"));
  839. // Real given int.
  840. format = "fish %f frog";
  841. args.clear();
  842. args.push_back(99);
  843. output = format.sprintf(args, &error);
  844. REQUIRE(error == false);
  845. CHECK(output == String("fish 99.000000 frog"));
  846. // Real with sign (positive).
  847. format = "fish %+f frog";
  848. args.clear();
  849. args.push_back(99.99);
  850. output = format.sprintf(args, &error);
  851. REQUIRE(error == false);
  852. CHECK(output == String("fish +99.990000 frog"));
  853. // Real with sign (negative zero).
  854. format = "fish %+f frog";
  855. args.clear();
  856. args.push_back(-0.0);
  857. output = format.sprintf(args, &error);
  858. REQUIRE(error == false);
  859. CHECK(output == String("fish -0.000000 frog"));
  860. // Real with sign (positive zero).
  861. format = "fish %+f frog";
  862. args.clear();
  863. args.push_back(0.0);
  864. output = format.sprintf(args, &error);
  865. REQUIRE(error == false);
  866. CHECK(output == String("fish +0.000000 frog"));
  867. // Real with 1 decimal.
  868. format = "fish %.1f frog";
  869. args.clear();
  870. args.push_back(99.99);
  871. output = format.sprintf(args, &error);
  872. REQUIRE(error == false);
  873. CHECK(output == String("fish 100.0 frog"));
  874. // Real with 12 decimals.
  875. format = "fish %.12f frog";
  876. args.clear();
  877. args.push_back(99.99);
  878. output = format.sprintf(args, &error);
  879. REQUIRE(error == false);
  880. CHECK(output == String("fish 99.990000000000 frog"));
  881. // Real with no decimals.
  882. format = "fish %.f frog";
  883. args.clear();
  884. args.push_back(99.99);
  885. output = format.sprintf(args, &error);
  886. REQUIRE(error == false);
  887. CHECK(output == String("fish 100 frog"));
  888. // Negative real right padded with zeros. (0 ignored)
  889. format = "fish %-011f frog";
  890. args.clear();
  891. args.push_back(-99.99);
  892. ERR_PRINT_OFF; // Silence warning about 0 ignored.
  893. output = format.sprintf(args, &error);
  894. ERR_PRINT_ON;
  895. REQUIRE(error == false);
  896. CHECK(output == String("fish -99.990000 frog"));
  897. ///// Vectors
  898. // Vector2
  899. format = "fish %v frog";
  900. args.clear();
  901. args.push_back(Variant(Vector2(19.99, 1.00)));
  902. output = format.sprintf(args, &error);
  903. REQUIRE(error == false);
  904. CHECK(output == String("fish (19.990000, 1.000000) frog"));
  905. // Vector3
  906. format = "fish %v frog";
  907. args.clear();
  908. args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
  909. output = format.sprintf(args, &error);
  910. REQUIRE(error == false);
  911. CHECK(output == String("fish (19.990000, 1.000000, -2.050000) frog"));
  912. // Vector4
  913. format = "fish %v frog";
  914. args.clear();
  915. args.push_back(Variant(Vector4(19.99, 1.00, -2.05, 5.5)));
  916. output = format.sprintf(args, &error);
  917. REQUIRE(error == false);
  918. CHECK(output == String("fish (19.990000, 1.000000, -2.050000, 5.500000) frog"));
  919. // Vector with negative values.
  920. format = "fish %v frog";
  921. args.clear();
  922. args.push_back(Variant(Vector2(-19.99, -1.00)));
  923. output = format.sprintf(args, &error);
  924. REQUIRE(error == false);
  925. CHECK(output == String("fish (-19.990000, -1.000000) frog"));
  926. // Vector left-padded.
  927. format = "fish %11v frog";
  928. args.clear();
  929. args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
  930. output = format.sprintf(args, &error);
  931. REQUIRE(error == false);
  932. CHECK(output == String("fish ( 19.990000, 1.000000, -2.050000) frog"));
  933. // Vector left-padded with inf/nan
  934. format = "fish %11v frog";
  935. args.clear();
  936. args.push_back(Variant(Vector2(INFINITY, NAN)));
  937. output = format.sprintf(args, &error);
  938. REQUIRE(error == false);
  939. CHECK(output == String("fish ( inf, nan) frog"));
  940. // Vector right-padded.
  941. format = "fish %-11v frog";
  942. args.clear();
  943. args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
  944. output = format.sprintf(args, &error);
  945. REQUIRE(error == false);
  946. CHECK(output == String("fish (19.990000 , 1.000000 , -2.050000 ) frog"));
  947. // Vector left-padded with zeros.
  948. format = "fish %011v frog";
  949. args.clear();
  950. args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
  951. output = format.sprintf(args, &error);
  952. REQUIRE(error == false);
  953. CHECK(output == String("fish (0019.990000, 0001.000000, -002.050000) frog"));
  954. // Vector given Vector3i.
  955. format = "fish %v frog";
  956. args.clear();
  957. args.push_back(Variant(Vector3i(19, 1, -2)));
  958. output = format.sprintf(args, &error);
  959. REQUIRE(error == false);
  960. CHECK(output == String("fish (19.000000, 1.000000, -2.000000) frog"));
  961. // Vector with 1 decimal.
  962. format = "fish %.1v frog";
  963. args.clear();
  964. args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
  965. output = format.sprintf(args, &error);
  966. REQUIRE(error == false);
  967. CHECK(output == String("fish (20.0, 1.0, -2.0) frog"));
  968. // Vector with 12 decimals.
  969. format = "fish %.12v frog";
  970. args.clear();
  971. args.push_back(Variant(Vector3(19.00, 1.00, -2.00)));
  972. output = format.sprintf(args, &error);
  973. REQUIRE(error == false);
  974. CHECK(output == String("fish (19.000000000000, 1.000000000000, -2.000000000000) frog"));
  975. // Vector with no decimals.
  976. format = "fish %.v frog";
  977. args.clear();
  978. args.push_back(Variant(Vector3(19.99, 1.00, -2.05)));
  979. output = format.sprintf(args, &error);
  980. REQUIRE(error == false);
  981. CHECK(output == String("fish (20, 1, -2) frog"));
  982. ///// Strings
  983. // String
  984. format = "fish %s frog";
  985. args.clear();
  986. args.push_back("cheese");
  987. output = format.sprintf(args, &error);
  988. REQUIRE(error == false);
  989. CHECK(output == String("fish cheese frog"));
  990. // String left-padded.
  991. format = "fish %10s frog";
  992. args.clear();
  993. args.push_back("cheese");
  994. output = format.sprintf(args, &error);
  995. REQUIRE(error == false);
  996. CHECK(output == String("fish cheese frog"));
  997. // String right-padded.
  998. format = "fish %-10s frog";
  999. args.clear();
  1000. args.push_back("cheese");
  1001. output = format.sprintf(args, &error);
  1002. REQUIRE(error == false);
  1003. CHECK(output == String("fish cheese frog"));
  1004. ///// Characters
  1005. // Character as string.
  1006. format = "fish %c frog";
  1007. args.clear();
  1008. args.push_back("A");
  1009. output = format.sprintf(args, &error);
  1010. REQUIRE(error == false);
  1011. CHECK(output == String("fish A frog"));
  1012. // Character as int.
  1013. format = "fish %c frog";
  1014. args.clear();
  1015. args.push_back(65);
  1016. output = format.sprintf(args, &error);
  1017. REQUIRE(error == false);
  1018. CHECK(output == String("fish A frog"));
  1019. ///// Dynamic width
  1020. // String dynamic width.
  1021. format = "fish %*s frog";
  1022. args.clear();
  1023. args.push_back(10);
  1024. args.push_back("cheese");
  1025. output = format.sprintf(args, &error);
  1026. REQUIRE(error == false);
  1027. REQUIRE(output == String("fish cheese frog"));
  1028. // Int dynamic width.
  1029. format = "fish %*d frog";
  1030. args.clear();
  1031. args.push_back(10);
  1032. args.push_back(99);
  1033. output = format.sprintf(args, &error);
  1034. REQUIRE(error == false);
  1035. REQUIRE(output == String("fish 99 frog"));
  1036. // Float dynamic width.
  1037. format = "fish %*.*f frog";
  1038. args.clear();
  1039. args.push_back(10);
  1040. args.push_back(3);
  1041. args.push_back(99.99);
  1042. output = format.sprintf(args, &error);
  1043. REQUIRE(error == false);
  1044. CHECK(output == String("fish 99.990 frog"));
  1045. ///// Errors
  1046. // More formats than arguments.
  1047. format = "fish %s %s frog";
  1048. args.clear();
  1049. args.push_back("cheese");
  1050. output = format.sprintf(args, &error);
  1051. REQUIRE(error);
  1052. CHECK(output == "not enough arguments for format string");
  1053. // More arguments than formats.
  1054. format = "fish %s frog";
  1055. args.clear();
  1056. args.push_back("hello");
  1057. args.push_back("cheese");
  1058. output = format.sprintf(args, &error);
  1059. REQUIRE(error);
  1060. CHECK(output == "not all arguments converted during string formatting");
  1061. // Incomplete format.
  1062. format = "fish %10";
  1063. args.clear();
  1064. args.push_back("cheese");
  1065. output = format.sprintf(args, &error);
  1066. REQUIRE(error);
  1067. CHECK(output == "incomplete format");
  1068. // Bad character in format string.
  1069. format = "fish %&f frog";
  1070. args.clear();
  1071. args.push_back("cheese");
  1072. output = format.sprintf(args, &error);
  1073. REQUIRE(error);
  1074. CHECK(output == "unsupported format character");
  1075. // Too many decimals.
  1076. format = "fish %2.2.2f frog";
  1077. args.clear();
  1078. args.push_back(99.99);
  1079. output = format.sprintf(args, &error);
  1080. REQUIRE(error);
  1081. CHECK(output == "too many decimal points in format");
  1082. // * not a number or vector.
  1083. format = "fish %*f frog";
  1084. args.clear();
  1085. args.push_back("cheese");
  1086. args.push_back(99.99);
  1087. output = format.sprintf(args, &error);
  1088. REQUIRE(error);
  1089. CHECK(output == "* wants number or vector");
  1090. // Character too long.
  1091. format = "fish %c frog";
  1092. args.clear();
  1093. args.push_back("sc");
  1094. output = format.sprintf(args, &error);
  1095. REQUIRE(error);
  1096. CHECK(output == "%c requires number or single-character string");
  1097. // Character bad type.
  1098. format = "fish %c frog";
  1099. args.clear();
  1100. args.push_back(Array());
  1101. output = format.sprintf(args, &error);
  1102. REQUIRE(error);
  1103. CHECK(output == "%c requires number or single-character string");
  1104. }
  1105. TEST_CASE("[String] is_numeric") {
  1106. CHECK(String("12").is_numeric());
  1107. CHECK(String("1.2").is_numeric());
  1108. CHECK(!String("AF").is_numeric());
  1109. CHECK(String("-12").is_numeric());
  1110. CHECK(String("-1.2").is_numeric());
  1111. }
  1112. TEST_CASE("[String] pad") {
  1113. String s = String("test");
  1114. CHECK(s.lpad(10, "x") == U"xxxxxxtest");
  1115. CHECK(s.rpad(10, "x") == U"testxxxxxx");
  1116. s = String("10.10");
  1117. CHECK(s.pad_decimals(4) == U"10.1000");
  1118. CHECK(s.pad_decimals(1) == U"10.1");
  1119. CHECK(s.pad_zeros(4) == U"0010.10");
  1120. CHECK(s.pad_zeros(1) == U"10.10");
  1121. }
  1122. TEST_CASE("[String] is_subsequence_of") {
  1123. String a = "is subsequence of";
  1124. CHECK(String("sub").is_subsequence_of(a));
  1125. CHECK(!String("Sub").is_subsequence_of(a));
  1126. CHECK(String("Sub").is_subsequence_ofn(a));
  1127. }
  1128. TEST_CASE("[String] is_lowercase") {
  1129. CHECK(String("abcd1234 !@#$%^&*()_-=+,.<>/\\|[]{};':\"`~").is_lowercase());
  1130. CHECK(String("").is_lowercase());
  1131. CHECK(!String("abc_ABC").is_lowercase());
  1132. }
  1133. TEST_CASE("[String] match") {
  1134. CHECK(String("img1.png").match("*.png"));
  1135. CHECK(!String("img1.jpeg").match("*.png"));
  1136. CHECK(!String("img1.Png").match("*.png"));
  1137. CHECK(String("img1.Png").matchn("*.png"));
  1138. }
  1139. TEST_CASE("[String] IPVX address to string") {
  1140. IPAddress ip0("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
  1141. IPAddress ip(0x0123, 0x4567, 0x89ab, 0xcdef, true);
  1142. IPAddress ip2("fe80::52e5:49ff:fe93:1baf");
  1143. IPAddress ip3("::ffff:192.168.0.1");
  1144. String ip4 = "192.168.0.1";
  1145. CHECK(ip4.is_valid_ip_address());
  1146. ip4 = "192.368.0.1";
  1147. CHECK(!ip4.is_valid_ip_address());
  1148. String ip6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
  1149. CHECK(ip6.is_valid_ip_address());
  1150. ip6 = "2001:0db8:85j3:0000:0000:8a2e:0370:7334";
  1151. CHECK(!ip6.is_valid_ip_address());
  1152. ip6 = "2001:0db8:85f345:0000:0000:8a2e:0370:7334";
  1153. CHECK(!ip6.is_valid_ip_address());
  1154. ip6 = "2001:0db8::0:8a2e:370:7334";
  1155. CHECK(ip6.is_valid_ip_address());
  1156. ip6 = "::ffff:192.168.0.1";
  1157. CHECK(ip6.is_valid_ip_address());
  1158. }
  1159. TEST_CASE("[String] Capitalize against many strings") {
  1160. String input = "2D";
  1161. String output = "2d";
  1162. CHECK(input.capitalize() == output);
  1163. input = "2d";
  1164. output = "2d";
  1165. CHECK(input.capitalize() == output);
  1166. input = "2db";
  1167. output = "2 Db";
  1168. CHECK(input.capitalize() == output);
  1169. input = "HTML5 Html5 html5 html_5";
  1170. output = "Html 5 Html 5 Html 5 Html 5";
  1171. CHECK(input.capitalize() == output);
  1172. input = "Node2D Node2d NODE2D NODE_2D node_2d";
  1173. output = "Node 2d Node 2d Node 2d Node 2d Node 2d";
  1174. CHECK(input.capitalize() == output);
  1175. input = "Node2DPosition";
  1176. output = "Node 2d Position";
  1177. CHECK(input.capitalize() == output);
  1178. input = "Number2Digits";
  1179. output = "Number 2 Digits";
  1180. CHECK(input.capitalize() == output);
  1181. input = "bytes2var";
  1182. output = "Bytes 2 Var";
  1183. CHECK(input.capitalize() == output);
  1184. input = "linear2db";
  1185. output = "Linear 2 Db";
  1186. CHECK(input.capitalize() == output);
  1187. input = "vector3";
  1188. output = "Vector 3";
  1189. CHECK(input.capitalize() == output);
  1190. input = "sha256";
  1191. output = "Sha 256";
  1192. CHECK(input.capitalize() == output);
  1193. input = "PascalCase";
  1194. output = "Pascal Case";
  1195. CHECK(input.capitalize() == output);
  1196. input = "PascalPascalCase";
  1197. output = "Pascal Pascal Case";
  1198. CHECK(input.capitalize() == output);
  1199. input = "snake_case";
  1200. output = "Snake Case";
  1201. CHECK(input.capitalize() == output);
  1202. input = "snake_snake_case";
  1203. output = "Snake Snake Case";
  1204. CHECK(input.capitalize() == output);
  1205. input = "sha256sum";
  1206. output = "Sha 256 Sum";
  1207. CHECK(input.capitalize() == output);
  1208. input = "cat2dog";
  1209. output = "Cat 2 Dog";
  1210. CHECK(input.capitalize() == output);
  1211. input = "function(name)";
  1212. output = "Function(name)";
  1213. CHECK(input.capitalize() == output);
  1214. input = "snake_case_function(snake_case_arg)";
  1215. output = "Snake Case Function(snake Case Arg)";
  1216. CHECK(input.capitalize() == output);
  1217. input = "snake_case_function( snake_case_arg )";
  1218. output = "Snake Case Function( Snake Case Arg )";
  1219. CHECK(input.capitalize() == output);
  1220. input = U"словоСлово_слово слово";
  1221. output = U"Слово Слово Слово Слово";
  1222. CHECK(input.capitalize() == output);
  1223. input = U"λέξηΛέξη_λέξη λέξη";
  1224. output = U"Λέξη Λέξη Λέξη Λέξη";
  1225. CHECK(input.capitalize() == output);
  1226. input = U"բառԲառ_բառ բառ";
  1227. output = U"Բառ Բառ Բառ Բառ";
  1228. CHECK(input.capitalize() == output);
  1229. }
  1230. struct StringCasesTestCase {
  1231. const char32_t *input;
  1232. const char32_t *camel_case;
  1233. const char32_t *pascal_case;
  1234. const char32_t *snake_case;
  1235. };
  1236. TEST_CASE("[String] Checking case conversion methods") {
  1237. StringCasesTestCase test_cases[] = {
  1238. /* clang-format off */
  1239. { U"2D", U"2d", U"2d", U"2d" },
  1240. { U"2d", U"2d", U"2d", U"2d" },
  1241. { U"2db", U"2Db", U"2Db", U"2_db" },
  1242. { U"Vector3", U"vector3", U"Vector3", U"vector_3" },
  1243. { U"sha256", U"sha256", U"Sha256", U"sha_256" },
  1244. { U"Node2D", U"node2d", U"Node2d", U"node_2d" },
  1245. { U"RichTextLabel", U"richTextLabel", U"RichTextLabel", U"rich_text_label" },
  1246. { U"HTML5", U"html5", U"Html5", U"html_5" },
  1247. { U"Node2DPosition", U"node2dPosition", U"Node2dPosition", U"node_2d_position" },
  1248. { U"Number2Digits", U"number2Digits", U"Number2Digits", U"number_2_digits" },
  1249. { U"get_property_list", U"getPropertyList", U"GetPropertyList", U"get_property_list" },
  1250. { U"get_camera_2d", U"getCamera2d", U"GetCamera2d", U"get_camera_2d" },
  1251. { U"_physics_process", U"physicsProcess", U"PhysicsProcess", U"_physics_process" },
  1252. { U"bytes2var", U"bytes2Var", U"Bytes2Var", U"bytes_2_var" },
  1253. { U"linear2db", U"linear2Db", U"Linear2Db", U"linear_2_db" },
  1254. { U"sha256sum", U"sha256Sum", U"Sha256Sum", U"sha_256_sum" },
  1255. { U"camelCase", U"camelCase", U"CamelCase", U"camel_case" },
  1256. { U"PascalCase", U"pascalCase", U"PascalCase", U"pascal_case" },
  1257. { U"snake_case", U"snakeCase", U"SnakeCase", U"snake_case" },
  1258. { U"Test TEST test", U"testTestTest", U"TestTestTest", U"test_test_test" },
  1259. { U"словоСлово_слово слово", U"словоСловоСловоСлово", U"СловоСловоСловоСлово", U"слово_слово_слово_слово" },
  1260. { U"λέξηΛέξη_λέξη λέξη", U"λέξηΛέξηΛέξηΛέξη", U"ΛέξηΛέξηΛέξηΛέξη", U"λέξη_λέξη_λέξη_λέξη" },
  1261. { U"բառԲառ_բառ բառ", U"բառԲառԲառԲառ", U"ԲառԲառԲառԲառ", U"բառ_բառ_բառ_բառ" },
  1262. { nullptr, nullptr, nullptr, nullptr },
  1263. /* clang-format on */
  1264. };
  1265. int idx = 0;
  1266. while (test_cases[idx].input != nullptr) {
  1267. String input = test_cases[idx].input;
  1268. CHECK(input.to_camel_case() == test_cases[idx].camel_case);
  1269. CHECK(input.to_pascal_case() == test_cases[idx].pascal_case);
  1270. CHECK(input.to_snake_case() == test_cases[idx].snake_case);
  1271. idx++;
  1272. }
  1273. }
  1274. TEST_CASE("[String] Checking string is empty when it should be") {
  1275. bool state = true;
  1276. bool success;
  1277. String a = "";
  1278. success = a[0] == 0;
  1279. if (!success) {
  1280. state = false;
  1281. }
  1282. String b = "Godot";
  1283. success = b[b.size()] == 0;
  1284. if (!success) {
  1285. state = false;
  1286. }
  1287. const String c = "";
  1288. success = c[0] == 0;
  1289. if (!success) {
  1290. state = false;
  1291. }
  1292. const String d = "Godot";
  1293. success = d[d.size()] == 0;
  1294. if (!success) {
  1295. state = false;
  1296. }
  1297. CHECK(state);
  1298. }
  1299. TEST_CASE("[String] lstrip and rstrip") {
  1300. #define STRIP_TEST(x) \
  1301. { \
  1302. bool success = x; \
  1303. state = state && success; \
  1304. }
  1305. bool state = true;
  1306. // strip none
  1307. STRIP_TEST(String("abc").lstrip("") == "abc");
  1308. STRIP_TEST(String("abc").rstrip("") == "abc");
  1309. // strip one
  1310. STRIP_TEST(String("abc").lstrip("a") == "bc");
  1311. STRIP_TEST(String("abc").rstrip("c") == "ab");
  1312. // strip lots
  1313. STRIP_TEST(String("bababbababccc").lstrip("ab") == "ccc");
  1314. STRIP_TEST(String("aaabcbcbcbbcbbc").rstrip("cb") == "aaa");
  1315. // strip empty string
  1316. STRIP_TEST(String("").lstrip("") == "");
  1317. STRIP_TEST(String("").rstrip("") == "");
  1318. // strip to empty string
  1319. STRIP_TEST(String("abcabcabc").lstrip("bca") == "");
  1320. STRIP_TEST(String("abcabcabc").rstrip("bca") == "");
  1321. // don't strip wrong end
  1322. STRIP_TEST(String("abc").lstrip("c") == "abc");
  1323. STRIP_TEST(String("abca").lstrip("a") == "bca");
  1324. STRIP_TEST(String("abc").rstrip("a") == "abc");
  1325. STRIP_TEST(String("abca").rstrip("a") == "abc");
  1326. // in utf-8 "¿" (\u00bf) has the same first byte as "µ" (\u00b5)
  1327. // and the same second as "ÿ" (\u00ff)
  1328. STRIP_TEST(String::utf8("¿").lstrip(String::utf8("µÿ")) == String::utf8("¿"));
  1329. STRIP_TEST(String::utf8("¿").rstrip(String::utf8("µÿ")) == String::utf8("¿"));
  1330. STRIP_TEST(String::utf8("µ¿ÿ").lstrip(String::utf8("µÿ")) == String::utf8("¿ÿ"));
  1331. STRIP_TEST(String::utf8("µ¿ÿ").rstrip(String::utf8("µÿ")) == String::utf8("µ¿"));
  1332. // the above tests repeated with additional superfluous strip chars
  1333. // strip none
  1334. STRIP_TEST(String("abc").lstrip("qwjkl") == "abc");
  1335. STRIP_TEST(String("abc").rstrip("qwjkl") == "abc");
  1336. // strip one
  1337. STRIP_TEST(String("abc").lstrip("qwajkl") == "bc");
  1338. STRIP_TEST(String("abc").rstrip("qwcjkl") == "ab");
  1339. // strip lots
  1340. STRIP_TEST(String("bababbababccc").lstrip("qwabjkl") == "ccc");
  1341. STRIP_TEST(String("aaabcbcbcbbcbbc").rstrip("qwcbjkl") == "aaa");
  1342. // strip empty string
  1343. STRIP_TEST(String("").lstrip("qwjkl") == "");
  1344. STRIP_TEST(String("").rstrip("qwjkl") == "");
  1345. // strip to empty string
  1346. STRIP_TEST(String("abcabcabc").lstrip("qwbcajkl") == "");
  1347. STRIP_TEST(String("abcabcabc").rstrip("qwbcajkl") == "");
  1348. // don't strip wrong end
  1349. STRIP_TEST(String("abc").lstrip("qwcjkl") == "abc");
  1350. STRIP_TEST(String("abca").lstrip("qwajkl") == "bca");
  1351. STRIP_TEST(String("abc").rstrip("qwajkl") == "abc");
  1352. STRIP_TEST(String("abca").rstrip("qwajkl") == "abc");
  1353. // in utf-8 "¿" (\u00bf) has the same first byte as "µ" (\u00b5)
  1354. // and the same second as "ÿ" (\u00ff)
  1355. STRIP_TEST(String::utf8("¿").lstrip(String::utf8("qwaµÿjkl")) == String::utf8("¿"));
  1356. STRIP_TEST(String::utf8("¿").rstrip(String::utf8("qwaµÿjkl")) == String::utf8("¿"));
  1357. STRIP_TEST(String::utf8("µ¿ÿ").lstrip(String::utf8("qwaµÿjkl")) == String::utf8("¿ÿ"));
  1358. STRIP_TEST(String::utf8("µ¿ÿ").rstrip(String::utf8("qwaµÿjkl")) == String::utf8("µ¿"));
  1359. CHECK(state);
  1360. #undef STRIP_TEST
  1361. }
  1362. TEST_CASE("[String] Ensuring empty string into extend_utf8 passes empty string") {
  1363. String empty;
  1364. CHECK(empty.append_utf8(nullptr, -1) == ERR_INVALID_DATA);
  1365. }
  1366. TEST_CASE("[String] Cyrillic to_lower()") {
  1367. String upper = U"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
  1368. String lower = U"абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
  1369. String test = upper.to_lower();
  1370. bool state = test == lower;
  1371. CHECK(state);
  1372. }
  1373. TEST_CASE("[String] Count and countn functionality") {
  1374. String s = String("");
  1375. MULTICHECK_STRING_EQ(s, count, "Test", 0);
  1376. s = "Test";
  1377. MULTICHECK_STRING_EQ(s, count, "", 0);
  1378. s = "Test";
  1379. MULTICHECK_STRING_EQ(s, count, "test", 0);
  1380. s = "Test";
  1381. MULTICHECK_STRING_EQ(s, count, "TEST", 0);
  1382. s = "TEST";
  1383. MULTICHECK_STRING_EQ(s, count, "TEST", 1);
  1384. s = "Test";
  1385. MULTICHECK_STRING_EQ(s, count, "Test", 1);
  1386. s = "aTest";
  1387. MULTICHECK_STRING_EQ(s, count, "Test", 1);
  1388. s = "Testa";
  1389. MULTICHECK_STRING_EQ(s, count, "Test", 1);
  1390. s = "TestTestTest";
  1391. MULTICHECK_STRING_EQ(s, count, "Test", 3);
  1392. s = "TestTestTest";
  1393. MULTICHECK_STRING_EQ(s, count, "TestTest", 1);
  1394. s = "TestGodotTestGodotTestGodot";
  1395. MULTICHECK_STRING_EQ(s, count, "Test", 3);
  1396. s = "TestTestTestTest";
  1397. MULTICHECK_STRING_INT_INT_EQ(s, count, "Test", 4, 8, 1);
  1398. s = "TestTestTestTest";
  1399. MULTICHECK_STRING_INT_INT_EQ(s, count, "Test", 4, 12, 2);
  1400. s = "TestTestTestTest";
  1401. MULTICHECK_STRING_INT_INT_EQ(s, count, "Test", 4, 16, 3);
  1402. s = "TestTestTestTest";
  1403. MULTICHECK_STRING_INT_EQ(s, count, "Test", 4, 3);
  1404. s = "Test";
  1405. MULTICHECK_STRING_EQ(s, countn, "test", 1);
  1406. s = "Test";
  1407. MULTICHECK_STRING_EQ(s, countn, "TEST", 1);
  1408. s = "testTest-Testatest";
  1409. MULTICHECK_STRING_EQ(s, countn, "tEst", 4);
  1410. s = "testTest-TeStatest";
  1411. MULTICHECK_STRING_INT_INT_EQ(s, countn, "tEsT", 4, 16, 2);
  1412. }
  1413. TEST_CASE("[String] Bigrams") {
  1414. String s = "abcd";
  1415. Vector<String> bigr = s.bigrams();
  1416. CHECK(bigr.size() == 3);
  1417. CHECK(bigr[0] == "ab");
  1418. CHECK(bigr[1] == "bc");
  1419. CHECK(bigr[2] == "cd");
  1420. }
  1421. TEST_CASE("[String] c-escape/unescape") {
  1422. String s = "\\1\a2\b\f3\n45\r6\t7\v8\'9\?0\"";
  1423. CHECK(s.c_escape().c_unescape() == s);
  1424. }
  1425. TEST_CASE("[String] indent") {
  1426. static const char *input[] = {
  1427. "",
  1428. "aaa\nbbb",
  1429. "\tcontains\n\tindent",
  1430. "empty\n\nline",
  1431. };
  1432. static const char *expected[] = {
  1433. "",
  1434. "\taaa\n\tbbb",
  1435. "\t\tcontains\n\t\tindent",
  1436. "\tempty\n\n\tline",
  1437. };
  1438. for (int i = 0; i < 3; i++) {
  1439. CHECK(String(input[i]).indent("\t") == expected[i]);
  1440. }
  1441. }
  1442. TEST_CASE("[String] dedent") {
  1443. String s = " aaa\n bbb";
  1444. String t = "aaa\nbbb";
  1445. CHECK(s.dedent() == t);
  1446. }
  1447. TEST_CASE("[String] Path functions") {
  1448. static const char *path[8] = { "C:\\Godot\\project\\test.tscn", "/Godot/project/test.xscn", "../Godot/project/test.scn", "Godot\\test.doc", "C:\\test.", "res://test", "user://test", "/.test" };
  1449. static const char *base_dir[8] = { "C:\\Godot\\project", "/Godot/project", "../Godot/project", "Godot", "C:\\", "res://", "user://", "/" };
  1450. static const char *base_name[8] = { "C:\\Godot\\project\\test", "/Godot/project/test", "../Godot/project/test", "Godot\\test", "C:\\test", "res://test", "user://test", "/" };
  1451. static const char *ext[8] = { "tscn", "xscn", "scn", "doc", "", "", "", "test" };
  1452. static const char *file[8] = { "test.tscn", "test.xscn", "test.scn", "test.doc", "test.", "test", "test", ".test" };
  1453. static const char *simplified[8] = { "C:/Godot/project/test.tscn", "/Godot/project/test.xscn", "../Godot/project/test.scn", "Godot/test.doc", "C:/test.", "res://test", "user://test", "/.test" };
  1454. static const bool abs[8] = { true, true, false, false, true, true, true, true };
  1455. for (int i = 0; i < 8; i++) {
  1456. CHECK(String(path[i]).get_base_dir() == base_dir[i]);
  1457. CHECK(String(path[i]).get_basename() == base_name[i]);
  1458. CHECK(String(path[i]).get_extension() == ext[i]);
  1459. CHECK(String(path[i]).get_file() == file[i]);
  1460. CHECK(String(path[i]).is_absolute_path() == abs[i]);
  1461. CHECK(String(path[i]).is_relative_path() != abs[i]);
  1462. CHECK(String(path[i]).simplify_path() == String(simplified[i]));
  1463. CHECK(String(path[i]).simplify_path().get_base_dir().path_join(file[i]) == String(path[i]).simplify_path());
  1464. }
  1465. static const char *file_name[3] = { "test.tscn", "test://.xscn", "?tes*t.scn" };
  1466. static const bool valid[3] = { true, false, false };
  1467. for (int i = 0; i < 3; i++) {
  1468. CHECK(String(file_name[i]).is_valid_filename() == valid[i]);
  1469. }
  1470. CHECK(String("res://texture.png") == String("res://folder/../folder/../texture.png").simplify_path());
  1471. CHECK(String("res://texture.png") == String("res://folder/sub/../../texture.png").simplify_path());
  1472. CHECK(String("res://../../texture.png") == String("res://../../texture.png").simplify_path());
  1473. }
  1474. TEST_CASE("[String] hash") {
  1475. String a = "Test";
  1476. String b = "Test";
  1477. String c = "West";
  1478. CHECK(a.hash() == b.hash());
  1479. CHECK(a.hash() != c.hash());
  1480. CHECK(a.hash64() == b.hash64());
  1481. CHECK(a.hash64() != c.hash64());
  1482. }
  1483. TEST_CASE("[String] uri_encode/unescape") {
  1484. String s = "Godot Engine:'docs'";
  1485. String t = "Godot%20Engine%3A%27docs%27";
  1486. String x1 = "T%C4%93%C5%A1t";
  1487. static const uint8_t u8str[] = { 0x54, 0xC4, 0x93, 0xC5, 0xA1, 0x74, 0x00 };
  1488. String x2 = String::utf8((const char *)u8str);
  1489. String x3 = U"Tēšt";
  1490. CHECK(x1.uri_decode() == x2);
  1491. CHECK(x1.uri_decode() == x3);
  1492. CHECK((x1 + x3).uri_decode() == (x2 + x3)); // Mixed unicode and URL encoded string, e.g. GTK+ bookmark.
  1493. CHECK(x2.uri_encode() == x1);
  1494. CHECK(x3.uri_encode() == x1);
  1495. CHECK(s.uri_encode() == t);
  1496. CHECK(t.uri_decode() == s);
  1497. }
  1498. TEST_CASE("[String] xml_escape/unescape") {
  1499. String s = "\"Test\" <test@test&'test'>";
  1500. CHECK(s.xml_escape(true).xml_unescape() == s);
  1501. CHECK(s.xml_escape(false).xml_unescape() == s);
  1502. }
  1503. TEST_CASE("[String] xml_unescape") {
  1504. // Named entities
  1505. String input = "&quot;&amp;&apos;&lt;&gt;";
  1506. CHECK(input.xml_unescape() == "\"&\'<>");
  1507. // Numeric entities
  1508. input = "&#x41;&#66;";
  1509. CHECK(input.xml_unescape() == "AB");
  1510. input = "&#0;&x#0;More text";
  1511. String result = input.xml_unescape();
  1512. // Didn't put in a leading NUL and terminate the string
  1513. CHECK(input.length() > 0);
  1514. CHECK(input[0] != '\0');
  1515. // Entity should be left as-is if invalid
  1516. CHECK(input.xml_unescape() == input);
  1517. // Check near char32_t range
  1518. input = "&#xFFFFFFFF;";
  1519. result = input.xml_unescape();
  1520. CHECK(result.length() == 1);
  1521. CHECK(result[0] == 0xFFFFFFFF);
  1522. input = "&#4294967295;";
  1523. result = input.xml_unescape();
  1524. CHECK(result.length() == 1);
  1525. CHECK(result[0] == 0xFFFFFFFF);
  1526. // Check out of range of char32_t
  1527. input = "&#xFFFFFFFFF;";
  1528. CHECK(input.xml_unescape() == input);
  1529. input = "&#4294967296;";
  1530. CHECK(input.xml_unescape() == input);
  1531. // Shouldn't consume without ending in a ';'
  1532. input = "&#66";
  1533. CHECK(input.xml_unescape() == input);
  1534. input = "&#x41";
  1535. CHECK(input.xml_unescape() == input);
  1536. // Invalid characters should make the entity ignored
  1537. input = "&#x41SomeIrrelevantText;";
  1538. CHECK(input.xml_unescape() == input);
  1539. input = "&#66SomeIrrelevantText;";
  1540. CHECK(input.xml_unescape() == input);
  1541. }
  1542. TEST_CASE("[String] Strip escapes") {
  1543. String s = "\t\tTest Test\r\n Test";
  1544. CHECK(s.strip_escapes() == "Test Test Test");
  1545. }
  1546. TEST_CASE("[String] Similarity") {
  1547. String a = "Test";
  1548. String b = "West";
  1549. String c = "Toad";
  1550. CHECK(a.similarity(b) > a.similarity(c));
  1551. }
  1552. TEST_CASE("[String] Strip edges") {
  1553. String s = "\t Test Test ";
  1554. CHECK(s.strip_edges(true, false) == "Test Test ");
  1555. CHECK(s.strip_edges(false, true) == "\t Test Test");
  1556. CHECK(s.strip_edges(true, true) == "Test Test");
  1557. }
  1558. TEST_CASE("[String] Trim") {
  1559. String s = "aaaTestbbb";
  1560. MULTICHECK_STRING_EQ(s, trim_prefix, "aaa", "Testbbb");
  1561. MULTICHECK_STRING_EQ(s, trim_prefix, "Test", s);
  1562. MULTICHECK_STRING_EQ(s, trim_prefix, "", s);
  1563. MULTICHECK_STRING_EQ(s, trim_prefix, "aaaTestbbb", "");
  1564. MULTICHECK_STRING_EQ(s, trim_prefix, "bbb", s);
  1565. MULTICHECK_STRING_EQ(s, trim_prefix, "AAA", s);
  1566. MULTICHECK_STRING_EQ(s, trim_suffix, "bbb", "aaaTest");
  1567. MULTICHECK_STRING_EQ(s, trim_suffix, "Test", s);
  1568. MULTICHECK_STRING_EQ(s, trim_suffix, "", s);
  1569. MULTICHECK_STRING_EQ(s, trim_suffix, "aaaTestbbb", "");
  1570. MULTICHECK_STRING_EQ(s, trim_suffix, "aaa", s);
  1571. MULTICHECK_STRING_EQ(s, trim_suffix, "BBB", s);
  1572. }
  1573. TEST_CASE("[String] Right/Left") {
  1574. String s = "aaaTestbbb";
  1575. // ^
  1576. CHECK(s.right(6) == "estbbb");
  1577. CHECK(s.right(-6) == "tbbb");
  1578. CHECK(s.left(6) == "aaaTes");
  1579. CHECK(s.left(-6) == "aaaT");
  1580. }
  1581. TEST_CASE("[String] Repeat") {
  1582. String s = "abababab";
  1583. String x = "ab";
  1584. String t = x.repeat(4);
  1585. CHECK(t == s);
  1586. }
  1587. TEST_CASE("[String] Reverse") {
  1588. String s = "Abcd";
  1589. CHECK(s.reverse() == "dcbA");
  1590. }
  1591. TEST_CASE("[String] SHA1/SHA256/MD5") {
  1592. String s = "Godot";
  1593. String sha1 = "a1e91f39b9fce6a9998b14bdbe2aa2b39dc2d201";
  1594. static uint8_t sha1_buf[20] = {
  1595. 0xA1, 0xE9, 0x1F, 0x39, 0xB9, 0xFC, 0xE6, 0xA9, 0x99, 0x8B, 0x14, 0xBD, 0xBE, 0x2A, 0xA2, 0xB3,
  1596. 0x9D, 0xC2, 0xD2, 0x01
  1597. };
  1598. String sha256 = "2a02b2443f7985d89d09001086ae3dcfa6eb0f55c6ef170715d42328e16e6cb8";
  1599. static uint8_t sha256_buf[32] = {
  1600. 0x2A, 0x02, 0xB2, 0x44, 0x3F, 0x79, 0x85, 0xD8, 0x9D, 0x09, 0x00, 0x10, 0x86, 0xAE, 0x3D, 0xCF,
  1601. 0xA6, 0xEB, 0x0F, 0x55, 0xC6, 0xEF, 0x17, 0x07, 0x15, 0xD4, 0x23, 0x28, 0xE1, 0x6E, 0x6C, 0xB8
  1602. };
  1603. String md5 = "4a336d087aeb0390da10ee2ea7cb87f8";
  1604. static uint8_t md5_buf[16] = {
  1605. 0x4A, 0x33, 0x6D, 0x08, 0x7A, 0xEB, 0x03, 0x90, 0xDA, 0x10, 0xEE, 0x2E, 0xA7, 0xCB, 0x87, 0xF8
  1606. };
  1607. PackedByteArray buf = s.sha1_buffer();
  1608. CHECK(memcmp(sha1_buf, buf.ptr(), 20) == 0);
  1609. CHECK(s.sha1_text() == sha1);
  1610. buf = s.sha256_buffer();
  1611. CHECK(memcmp(sha256_buf, buf.ptr(), 32) == 0);
  1612. CHECK(s.sha256_text() == sha256);
  1613. buf = s.md5_buffer();
  1614. CHECK(memcmp(md5_buf, buf.ptr(), 16) == 0);
  1615. CHECK(s.md5_text() == md5);
  1616. }
  1617. TEST_CASE("[String] Join") {
  1618. String comma = ", ";
  1619. String empty = "";
  1620. Vector<String> parts;
  1621. CHECK(comma.join(parts) == "");
  1622. CHECK(empty.join(parts) == "");
  1623. parts.push_back("One");
  1624. CHECK(comma.join(parts) == "One");
  1625. CHECK(empty.join(parts) == "One");
  1626. parts.push_back("B");
  1627. parts.push_back("C");
  1628. CHECK(comma.join(parts) == "One, B, C");
  1629. CHECK(empty.join(parts) == "OneBC");
  1630. parts.push_back("");
  1631. CHECK(comma.join(parts) == "One, B, C, ");
  1632. CHECK(empty.join(parts) == "OneBC");
  1633. }
  1634. TEST_CASE("[String] Is_*") {
  1635. static const char *data[] = { "-30", "100", "10.1", "10,1", "1e2", "1e-2", "1e2e3", "0xAB", "AB", "Test1", "1Test", "Test*1", "文字", "1E2", "1E-2" };
  1636. static bool isnum[] = { true, true, true, false, false, false, false, false, false, false, false, false, false, false, false };
  1637. static bool isint[] = { true, true, false, false, false, false, false, false, false, false, false, false, false, false, false };
  1638. static bool ishex[] = { true, true, false, false, true, false, true, false, true, false, false, false, false, true, false };
  1639. static bool ishex_p[] = { false, false, false, false, false, false, false, true, false, false, false, false, false, false, false };
  1640. static bool isflt[] = { true, true, true, false, true, true, false, false, false, false, false, false, false, true, true };
  1641. static bool isaid[] = { false, false, false, false, false, false, false, false, true, true, false, false, false, false, false };
  1642. static bool isuid[] = { false, false, false, false, false, false, false, false, true, true, false, false, true, false, false };
  1643. for (unsigned int i = 0; i < std::size(data); i++) {
  1644. String s = String::utf8(data[i]);
  1645. CHECK(s.is_numeric() == isnum[i]);
  1646. CHECK(s.is_valid_int() == isint[i]);
  1647. CHECK(s.is_valid_hex_number(false) == ishex[i]);
  1648. CHECK(s.is_valid_hex_number(true) == ishex_p[i]);
  1649. CHECK(s.is_valid_float() == isflt[i]);
  1650. CHECK(s.is_valid_ascii_identifier() == isaid[i]);
  1651. CHECK(s.is_valid_unicode_identifier() == isuid[i]);
  1652. }
  1653. }
  1654. TEST_CASE("[String] humanize_size") {
  1655. CHECK(String::humanize_size(1000) == "1000 B");
  1656. CHECK(String::humanize_size(1025) == "1.00 KiB");
  1657. CHECK(String::humanize_size(1025300) == "1001.2 KiB");
  1658. CHECK(String::humanize_size(100523550) == "95.86 MiB");
  1659. CHECK(String::humanize_size(5345555000) == "4.97 GiB");
  1660. }
  1661. TEST_CASE("[String] validate_node_name") {
  1662. String numeric_only = "12345";
  1663. CHECK(numeric_only.validate_node_name() == "12345");
  1664. String name_with_spaces = "Name with spaces";
  1665. CHECK(name_with_spaces.validate_node_name() == "Name with spaces");
  1666. String name_with_kana = U"Name with kana ゴドツ";
  1667. CHECK(name_with_kana.validate_node_name() == U"Name with kana ゴドツ");
  1668. String name_with_invalid_chars = "Name with invalid characters :.@%removed!";
  1669. CHECK(name_with_invalid_chars.validate_node_name() == "Name with invalid characters ____removed!");
  1670. }
  1671. TEST_CASE("[String] validate_ascii_identifier") {
  1672. String empty_string;
  1673. CHECK(empty_string.validate_ascii_identifier() == "_");
  1674. String numeric_only = "12345";
  1675. CHECK(numeric_only.validate_ascii_identifier() == "_12345");
  1676. String name_with_spaces = "Name with spaces";
  1677. CHECK(name_with_spaces.validate_ascii_identifier() == "Name_with_spaces");
  1678. String name_with_invalid_chars = U"Invalid characters:@*#&世界";
  1679. CHECK(name_with_invalid_chars.validate_ascii_identifier() == "Invalid_characters_______");
  1680. }
  1681. TEST_CASE("[String] validate_unicode_identifier") {
  1682. String empty_string;
  1683. CHECK(empty_string.validate_unicode_identifier() == "_");
  1684. String numeric_only = "12345";
  1685. CHECK(numeric_only.validate_unicode_identifier() == "_12345");
  1686. String name_with_spaces = "Name with spaces";
  1687. CHECK(name_with_spaces.validate_unicode_identifier() == "Name_with_spaces");
  1688. String name_with_invalid_chars = U"Invalid characters:@*#&世界";
  1689. CHECK(name_with_invalid_chars.validate_unicode_identifier() == U"Invalid_characters_____世界");
  1690. }
  1691. TEST_CASE("[String] Variant indexed get") {
  1692. Variant s = String("abcd");
  1693. bool valid = false;
  1694. bool oob = true;
  1695. String r = s.get_indexed(1, valid, oob);
  1696. CHECK(valid);
  1697. CHECK_FALSE(oob);
  1698. CHECK_EQ(r, String("b"));
  1699. }
  1700. TEST_CASE("[String] Variant validated indexed get") {
  1701. Variant s = String("abcd");
  1702. Variant::ValidatedIndexedGetter getter = Variant::get_member_validated_indexed_getter(Variant::STRING);
  1703. Variant r;
  1704. bool oob = true;
  1705. getter(&s, 1, &r, &oob);
  1706. CHECK_FALSE(oob);
  1707. CHECK_EQ(r, String("b"));
  1708. }
  1709. TEST_CASE("[String] Variant ptr indexed get") {
  1710. String s("abcd");
  1711. Variant::PTRIndexedGetter getter = Variant::get_member_ptr_indexed_getter(Variant::STRING);
  1712. String r;
  1713. getter(&s, 1, &r);
  1714. CHECK_EQ(r, String("b"));
  1715. }
  1716. TEST_CASE("[String] Variant indexed set") {
  1717. Variant s = String("abcd");
  1718. bool valid = false;
  1719. bool oob = true;
  1720. s.set_indexed(1, String("z"), valid, oob);
  1721. CHECK(valid);
  1722. CHECK_FALSE(oob);
  1723. CHECK_EQ(s, String("azcd"));
  1724. }
  1725. TEST_CASE("[String] Variant validated indexed set") {
  1726. Variant s = String("abcd");
  1727. Variant::ValidatedIndexedSetter setter = Variant::get_member_validated_indexed_setter(Variant::STRING);
  1728. Variant v = String("z");
  1729. bool oob = true;
  1730. setter(&s, 1, &v, &oob);
  1731. CHECK_FALSE(oob);
  1732. CHECK_EQ(s, String("azcd"));
  1733. }
  1734. TEST_CASE("[String] Variant ptr indexed set") {
  1735. String s("abcd");
  1736. Variant::PTRIndexedSetter setter = Variant::get_member_ptr_indexed_setter(Variant::STRING);
  1737. String v("z");
  1738. setter(&s, 1, &v);
  1739. CHECK_EQ(s, String("azcd"));
  1740. }
  1741. TEST_CASE("[String][URL] Parse URL") {
  1742. #define CHECK_URL(m_url_to_parse, m_expected_schema, m_expected_host, m_expected_port, m_expected_path, m_expected_fragment, m_expected_error) \
  1743. if (true) { \
  1744. int port; \
  1745. String url(m_url_to_parse), schema, host, path, fragment; \
  1746. \
  1747. CHECK_EQ(url.parse_url(schema, host, port, path, fragment), m_expected_error); \
  1748. CHECK_EQ(schema, m_expected_schema); \
  1749. CHECK_EQ(host, m_expected_host); \
  1750. CHECK_EQ(path, m_expected_path); \
  1751. CHECK_EQ(fragment, m_expected_fragment); \
  1752. CHECK_EQ(port, m_expected_port); \
  1753. } else \
  1754. ((void)0)
  1755. // All elements.
  1756. CHECK_URL("https://www.example.com:8080/path/to/file.html#fragment", "https://", "www.example.com", 8080, "/path/to/file.html", "fragment", Error::OK);
  1757. // Valid URLs.
  1758. CHECK_URL("https://godotengine.org", "https://", "godotengine.org", 0, "", "", Error::OK);
  1759. CHECK_URL("https://godotengine.org/", "https://", "godotengine.org", 0, "/", "", Error::OK);
  1760. CHECK_URL("godotengine.org/", "", "godotengine.org", 0, "/", "", Error::OK);
  1761. CHECK_URL("HTTPS://godotengine.org/", "https://", "godotengine.org", 0, "/", "", Error::OK);
  1762. CHECK_URL("https://GODOTENGINE.ORG/", "https://", "godotengine.org", 0, "/", "", Error::OK);
  1763. CHECK_URL("http://godotengine.org", "http://", "godotengine.org", 0, "", "", Error::OK);
  1764. CHECK_URL("https://godotengine.org:8080", "https://", "godotengine.org", 8080, "", "", Error::OK);
  1765. CHECK_URL("https://godotengine.org/blog", "https://", "godotengine.org", 0, "/blog", "", Error::OK);
  1766. CHECK_URL("https://godotengine.org/blog/", "https://", "godotengine.org", 0, "/blog/", "", Error::OK);
  1767. CHECK_URL("https://docs.godotengine.org/en/stable", "https://", "docs.godotengine.org", 0, "/en/stable", "", Error::OK);
  1768. CHECK_URL("https://docs.godotengine.org/en/stable/", "https://", "docs.godotengine.org", 0, "/en/stable/", "", Error::OK);
  1769. CHECK_URL("https://me:[email protected]", "https://", "godotengine.org", 0, "", "", Error::OK);
  1770. CHECK_URL("https://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]/ipv6", "https://", "fedc:ba98:7654:3210:fedc:ba98:7654:3210", 0, "/ipv6", "", Error::OK);
  1771. // Scheme vs Fragment.
  1772. CHECK_URL("google.com/#goto=http://redirect_url/", "", "google.com", 0, "/", "goto=http://redirect_url/", Error::OK);
  1773. // Invalid URLs.
  1774. // Invalid Scheme.
  1775. CHECK_URL("https_://godotengine.org", "", "https_", 0, "//godotengine.org", "", Error::ERR_INVALID_PARAMETER);
  1776. // Multiple ports.
  1777. CHECK_URL("https://godotengine.org:8080:433", "https://", "", 0, "", "", Error::ERR_INVALID_PARAMETER);
  1778. // Missing ] on literal IPv6.
  1779. CHECK_URL("https://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210/ipv6", "https://", "", 0, "/ipv6", "", Error::ERR_INVALID_PARAMETER);
  1780. // Missing host.
  1781. CHECK_URL("https:///blog", "https://", "", 0, "/blog", "", Error::ERR_INVALID_PARAMETER);
  1782. // Invalid ports.
  1783. CHECK_URL("https://godotengine.org:notaport", "https://", "godotengine.org", 0, "", "", Error::ERR_INVALID_PARAMETER);
  1784. CHECK_URL("https://godotengine.org:-8080", "https://", "godotengine.org", -8080, "", "", Error::ERR_INVALID_PARAMETER);
  1785. CHECK_URL("https://godotengine.org:88888", "https://", "godotengine.org", 88888, "", "", Error::ERR_INVALID_PARAMETER);
  1786. #undef CHECK_URL
  1787. }
  1788. TEST_CASE("[Stress][String] Empty via ' == String()'") {
  1789. for (int i = 0; i < 100000; ++i) {
  1790. String str = "Hello World!";
  1791. if (str == String()) {
  1792. continue;
  1793. }
  1794. }
  1795. }
  1796. TEST_CASE("[Stress][String] Empty via `is_empty()`") {
  1797. for (int i = 0; i < 100000; ++i) {
  1798. String str = "Hello World!";
  1799. if (str.is_empty()) {
  1800. continue;
  1801. }
  1802. }
  1803. }
  1804. } // namespace TestString