test_string.h 62 KB

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