test_string.h 76 KB

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