test_string.h 71 KB

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