test_string.h 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  1. /*************************************************************************/
  2. /* test_string.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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, 0xD801, 0 };
  145. String s;
  146. Error err = s.parse_utf8((const char *)u8str);
  147. CHECK(err == ERR_PARSE_ERROR);
  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, 0x20, 0x20, 0x20, 0x20, 0x3088, 0x3046, 0x20, 0x1F3A4, 0x20AC, 0xD801, 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. }
  193. TEST_CASE("[String] Comparisons (not equal)") {
  194. String s = "Test Compare";
  195. CHECK(s != "Peanut");
  196. CHECK(s != U"Coconut");
  197. CHECK(s != L"Coconut");
  198. CHECK(s != String("Butter"));
  199. }
  200. TEST_CASE("[String] Comparisons (operator <)") {
  201. String s = "Bees";
  202. CHECK(s < "Elephant");
  203. CHECK(!(s < U"Amber"));
  204. CHECK(!(s < L"Amber"));
  205. CHECK(!(s < String("Beatrix")));
  206. }
  207. TEST_CASE("[String] Concatenation") {
  208. String s;
  209. s += "Have";
  210. s += ' ';
  211. s += 'a';
  212. s += String(" ");
  213. s = s + U"Nice";
  214. s = s + " ";
  215. s = s + String("Day");
  216. CHECK(s == "Have a Nice Day");
  217. }
  218. TEST_CASE("[String] Testing size and length of string") {
  219. // todo: expand this test to do more tests on size() as it is complicated under the hood.
  220. CHECK(String("Mellon").size() == 7);
  221. CHECK(String("Mellon1").size() == 8);
  222. // length works fine and is easier to test
  223. CHECK(String("Mellon").length() == 6);
  224. CHECK(String("Mellon1").length() == 7);
  225. CHECK(String("Mellon2").length() == 7);
  226. CHECK(String("Mellon3").length() == 7);
  227. }
  228. TEST_CASE("[String] Testing for empty string") {
  229. CHECK(!String("Mellon").is_empty());
  230. // do this more than once, to check for string corruption
  231. CHECK(String("").is_empty());
  232. CHECK(String("").is_empty());
  233. CHECK(String("").is_empty());
  234. }
  235. TEST_CASE("[String] Contains") {
  236. String s = "C:\\Godot\\project\\string_test.tscn";
  237. CHECK(s.contains(":\\"));
  238. CHECK(s.contains("Godot"));
  239. CHECK(s.contains(String("project\\string_test")));
  240. CHECK(s.contains(String("\\string_test.tscn")));
  241. CHECK(!s.contains("://"));
  242. CHECK(!s.contains("Godoh"));
  243. CHECK(!s.contains(String("project\\string test")));
  244. CHECK(!s.contains(String("\\char_test.tscn")));
  245. }
  246. TEST_CASE("[String] Test chr") {
  247. CHECK(String::chr('H') == "H");
  248. CHECK(String::chr(0x3012)[0] == 0x3012);
  249. ERR_PRINT_OFF
  250. CHECK(String::chr(0xd812)[0] == 0xd812); // Unpaired UTF-16 surrogate
  251. CHECK(String::chr(0x20d812)[0] == 0x20d812); // Outside UTF-32 range
  252. ERR_PRINT_ON
  253. }
  254. TEST_CASE("[String] Operator []") {
  255. String a = "Kugar Sane";
  256. a[0] = 'S';
  257. a[6] = 'C';
  258. CHECK(a == "Sugar Cane");
  259. CHECK(a[1] == 'u');
  260. CHECK(a.unicode_at(1) == 'u');
  261. }
  262. TEST_CASE("[String] Case function test") {
  263. String a = "MoMoNgA";
  264. CHECK(a.to_upper() == "MOMONGA");
  265. CHECK(a.to_lower() == "momonga");
  266. }
  267. TEST_CASE("[String] Case compare function test") {
  268. String a = "MoMoNgA";
  269. CHECK(a.casecmp_to("momonga") != 0);
  270. CHECK(a.nocasecmp_to("momonga") == 0);
  271. }
  272. TEST_CASE("[String] Natural compare function test") {
  273. String a = "img2.png";
  274. CHECK(a.nocasecmp_to("img10.png") > 0);
  275. CHECK(a.naturalnocasecmp_to("img10.png") < 0);
  276. }
  277. TEST_CASE("[String] hex_encode_buffer") {
  278. static const uint8_t u8str[] = { 0x45, 0xE3, 0x81, 0x8A, 0x8F, 0xE3 };
  279. String s = String::hex_encode_buffer(u8str, 6);
  280. CHECK(s == U"45e3818a8fe3");
  281. }
  282. TEST_CASE("[String] Substr") {
  283. String s = "Killer Baby";
  284. CHECK(s.substr(3, 4) == "ler ");
  285. CHECK(s.substr(3) == "ler Baby");
  286. }
  287. TEST_CASE("[String] Find") {
  288. String s = "Pretty Woman Woman";
  289. CHECK(s.find("tty") == 3);
  290. CHECK(s.find("Wo", 9) == 13);
  291. CHECK(s.find("Revenge of the Monster Truck") == -1);
  292. CHECK(s.rfind("man") == 15);
  293. }
  294. TEST_CASE("[String] Find no case") {
  295. String s = "Pretty Whale Whale";
  296. CHECK(s.findn("WHA") == 7);
  297. CHECK(s.findn("WHA", 9) == 13);
  298. CHECK(s.findn("Revenge of the Monster SawFish") == -1);
  299. CHECK(s.rfindn("WHA") == 13);
  300. }
  301. TEST_CASE("[String] Find MK") {
  302. Vector<String> keys;
  303. keys.push_back("sty");
  304. keys.push_back("tty");
  305. keys.push_back("man");
  306. String s = "Pretty Woman";
  307. int key = 0;
  308. CHECK(s.findmk(keys, 0, &key) == 3);
  309. CHECK(key == 1);
  310. CHECK(s.findmk(keys, 5, &key) == 9);
  311. CHECK(key == 2);
  312. }
  313. TEST_CASE("[String] Find and replace") {
  314. String s = "Happy Birthday, Anna!";
  315. s = s.replace("Birthday", "Halloween");
  316. CHECK(s == "Happy Halloween, Anna!");
  317. s = s.replace_first("H", "W");
  318. CHECK(s == "Wappy Halloween, Anna!");
  319. }
  320. TEST_CASE("[String] Insertion") {
  321. String s = "Who is Frederic?";
  322. s = s.insert(s.find("?"), " Chopin");
  323. CHECK(s == "Who is Frederic Chopin?");
  324. }
  325. TEST_CASE("[String] Number to string") {
  326. CHECK(String::num(0) == "0");
  327. CHECK(String::num(0.0) == "0"); // No trailing zeros.
  328. CHECK(String::num(-0.0) == "-0"); // Includes sign even for zero.
  329. CHECK(String::num(3.141593) == "3.141593");
  330. CHECK(String::num(3.141593, 3) == "3.142");
  331. CHECK(String::num_scientific(30000000) == "3e+07");
  332. CHECK(String::num_int64(3141593) == "3141593");
  333. CHECK(String::num_int64(0xA141593, 16) == "a141593");
  334. CHECK(String::num_int64(0xA141593, 16, true) == "A141593");
  335. CHECK(String::num(42.100023, 4) == "42.1"); // No trailing zeros.
  336. // String::num_real tests.
  337. CHECK(String::num_real(1.0) == "1.0");
  338. CHECK(String::num_real(1.0, false) == "1");
  339. CHECK(String::num_real(9.9) == "9.9");
  340. CHECK(String::num_real(9.99) == "9.99");
  341. CHECK(String::num_real(9.999) == "9.999");
  342. CHECK(String::num_real(9.9999) == "9.9999");
  343. CHECK(String::num_real(3.141593) == "3.141593");
  344. CHECK(String::num_real(3.141) == "3.141"); // No trailing zeros.
  345. #ifdef REAL_T_IS_DOUBLE
  346. CHECK_MESSAGE(String::num_real(Math_PI) == "3.14159265358979", "Prints the appropriate amount of digits for real_t = double.");
  347. 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.");
  348. #else
  349. CHECK_MESSAGE(String::num_real(Math_PI) == "3.141593", "Prints the appropriate amount of digits for real_t = float.");
  350. CHECK_MESSAGE(String::num_real(3.1415f) == "3.1415", "Prints only reliable digits of 32-bit float when real_t = float.");
  351. #endif // REAL_T_IS_DOUBLE
  352. // Checks doubles with many decimal places.
  353. CHECK(String::num(0.0000012345432123454321, -1) == "0.00000123454321"); // -1 uses 14 as sane default.
  354. CHECK(String::num(0.0000012345432123454321) == "0.00000123454321"); // -1 is the default value.
  355. CHECK(String::num(-0.0000012345432123454321) == "-0.00000123454321");
  356. CHECK(String::num(-10000.0000012345432123454321) == "-10000.0000012345");
  357. CHECK(String::num(0.0000000000012345432123454321) == "0.00000000000123");
  358. CHECK(String::num(0.0000000000012345432123454321, 3) == "0");
  359. // Note: When relevant (remainder > 0.5), the last digit gets rounded up,
  360. // which can also lead to not include a trailing zero, e.g. "...89" -> "...9".
  361. CHECK(String::num(0.0000056789876567898765) == "0.00000567898766"); // Should round last digit.
  362. CHECK(String::num(10000.000005678999999999) == "10000.000005679"); // We cut at ...789|99 which is rounded to ...79, so only 13 decimals.
  363. CHECK(String::num(42.12999999, 6) == "42.13"); // Also happens with lower decimals count.
  364. // 32 is MAX_DECIMALS. We can't reliably store that many so we can't compare against a string,
  365. // but we can check that the string length is 34 (32 + 2 for "0.").
  366. CHECK(String::num(0.00000123456789987654321123456789987654321, 32).length() == 34);
  367. CHECK(String::num(0.00000123456789987654321123456789987654321, 42).length() == 34); // Should enforce MAX_DECIMALS.
  368. CHECK(String::num(10000.00000123456789987654321123456789987654321, 42).length() == 38); // 32 decimals + "10000.".
  369. }
  370. TEST_CASE("[String] String to integer") {
  371. static const char *nums[4] = { "1237461283", "- 22", "0", " - 1123412" };
  372. static const int num[4] = { 1237461283, -22, 0, -1123412 };
  373. for (int i = 0; i < 4; i++) {
  374. CHECK(String(nums[i]).to_int() == num[i]);
  375. }
  376. }
  377. TEST_CASE("[String] Hex to integer") {
  378. static const char *nums[4] = { "0xFFAE", "22", "0", "AADDAD" };
  379. static const int64_t num[4] = { 0xFFAE, 0x22, 0, 0xAADDAD };
  380. for (int i = 0; i < 4; i++) {
  381. CHECK(String(nums[i]).hex_to_int() == num[i]);
  382. }
  383. }
  384. TEST_CASE("[String] String to float") {
  385. static const char *nums[4] = { "-12348298412.2", "0.05", "2.0002", " -0.0001" };
  386. static const double num[4] = { -12348298412.2, 0.05, 2.0002, -0.0001 };
  387. for (int i = 0; i < 4; i++) {
  388. CHECK(!(ABS(String(nums[i]).to_float() - num[i]) > 0.00001));
  389. }
  390. }
  391. TEST_CASE("[String] CamelCase to underscore") {
  392. CHECK(String("TestTestStringGD").camelcase_to_underscore(false) == String("Test_Test_String_GD"));
  393. CHECK(String("TestTestStringGD").camelcase_to_underscore(true) == String("test_test_string_gd"));
  394. }
  395. TEST_CASE("[String] Slicing") {
  396. String s = "Mars,Jupiter,Saturn,Uranus";
  397. const char *slices[4] = { "Mars", "Jupiter", "Saturn", "Uranus" };
  398. for (int i = 0; i < s.get_slice_count(","); i++) {
  399. CHECK(s.get_slice(",", i) == slices[i]);
  400. }
  401. }
  402. TEST_CASE("[String] Splitting") {
  403. String s = "Mars,Jupiter,Saturn,Uranus";
  404. Vector<String> l;
  405. const char *slices_l[3] = { "Mars", "Jupiter", "Saturn,Uranus" };
  406. const char *slices_r[3] = { "Mars,Jupiter", "Saturn", "Uranus" };
  407. l = s.split(",", true, 2);
  408. CHECK(l.size() == 3);
  409. for (int i = 0; i < l.size(); i++) {
  410. CHECK(l[i] == slices_l[i]);
  411. }
  412. l = s.rsplit(",", true, 2);
  413. CHECK(l.size() == 3);
  414. for (int i = 0; i < l.size(); i++) {
  415. CHECK(l[i] == slices_r[i]);
  416. }
  417. s = "Mars Jupiter Saturn Uranus";
  418. const char *slices_s[4] = { "Mars", "Jupiter", "Saturn", "Uranus" };
  419. l = s.split_spaces();
  420. for (int i = 0; i < l.size(); i++) {
  421. CHECK(l[i] == slices_s[i]);
  422. }
  423. s = "1.2;2.3 4.5";
  424. const double slices_d[3] = { 1.2, 2.3, 4.5 };
  425. Vector<float> f;
  426. f = s.split_floats(";");
  427. CHECK(f.size() == 2);
  428. for (int i = 0; i < f.size(); i++) {
  429. CHECK(ABS(f[i] - slices_d[i]) <= 0.00001);
  430. }
  431. Vector<String> keys;
  432. keys.push_back(";");
  433. keys.push_back(" ");
  434. f = s.split_floats_mk(keys);
  435. CHECK(f.size() == 3);
  436. for (int i = 0; i < f.size(); i++) {
  437. CHECK(ABS(f[i] - slices_d[i]) <= 0.00001);
  438. }
  439. s = "1;2 4";
  440. const int slices_i[3] = { 1, 2, 4 };
  441. Vector<int> ii;
  442. ii = s.split_ints(";");
  443. CHECK(ii.size() == 2);
  444. for (int i = 0; i < ii.size(); i++) {
  445. CHECK(ii[i] == slices_i[i]);
  446. }
  447. ii = s.split_ints_mk(keys);
  448. CHECK(ii.size() == 3);
  449. for (int i = 0; i < ii.size(); i++) {
  450. CHECK(ii[i] == slices_i[i]);
  451. }
  452. }
  453. struct test_27_data {
  454. char const *data;
  455. char const *part;
  456. bool expected;
  457. };
  458. TEST_CASE("[String] Begins with") {
  459. test_27_data tc[] = {
  460. { "res://foobar", "res://", true },
  461. { "res", "res://", false },
  462. { "abc", "abc", true }
  463. };
  464. size_t count = sizeof(tc) / sizeof(tc[0]);
  465. bool state = true;
  466. for (size_t i = 0; state && i < count; ++i) {
  467. String s = tc[i].data;
  468. state = s.begins_with(tc[i].part) == tc[i].expected;
  469. if (state) {
  470. String sb = tc[i].part;
  471. state = s.begins_with(sb) == tc[i].expected;
  472. }
  473. CHECK(state);
  474. if (!state) {
  475. break;
  476. }
  477. };
  478. CHECK(state);
  479. }
  480. TEST_CASE("[String] Ends with") {
  481. test_27_data tc[] = {
  482. { "res://foobar", "foobar", true },
  483. { "res", "res://", false },
  484. { "abc", "abc", true }
  485. };
  486. size_t count = sizeof(tc) / sizeof(tc[0]);
  487. bool state = true;
  488. for (size_t i = 0; state && i < count; ++i) {
  489. String s = tc[i].data;
  490. state = s.ends_with(tc[i].part) == tc[i].expected;
  491. if (state) {
  492. String sb = tc[i].part;
  493. state = s.ends_with(sb) == tc[i].expected;
  494. }
  495. CHECK(state);
  496. if (!state) {
  497. break;
  498. }
  499. };
  500. CHECK(state);
  501. }
  502. TEST_CASE("[String] format") {
  503. const String value_format = "red=\"$red\" green=\"$green\" blue=\"$blue\" alpha=\"$alpha\"";
  504. Dictionary value_dictionary;
  505. value_dictionary["red"] = 10;
  506. value_dictionary["green"] = 20;
  507. value_dictionary["blue"] = "bla";
  508. value_dictionary["alpha"] = 0.4;
  509. String value = value_format.format(value_dictionary, "$_");
  510. CHECK(value == "red=\"10\" green=\"20\" blue=\"bla\" alpha=\"0.4\"");
  511. }
  512. TEST_CASE("[String] sprintf") {
  513. String format, output;
  514. Array args;
  515. bool error;
  516. // %%
  517. format = "fish %% frog";
  518. args.clear();
  519. output = format.sprintf(args, &error);
  520. REQUIRE(error == false);
  521. CHECK(output == String("fish % frog"));
  522. //////// INTS
  523. // Int
  524. format = "fish %d frog";
  525. args.clear();
  526. args.push_back(5);
  527. output = format.sprintf(args, &error);
  528. REQUIRE(error == false);
  529. CHECK(output == String("fish 5 frog"));
  530. // Int left padded with zeroes.
  531. format = "fish %05d frog";
  532. args.clear();
  533. args.push_back(5);
  534. output = format.sprintf(args, &error);
  535. REQUIRE(error == false);
  536. CHECK(output == String("fish 00005 frog"));
  537. // Int left padded with spaces.
  538. format = "fish %5d frog";
  539. args.clear();
  540. args.push_back(5);
  541. output = format.sprintf(args, &error);
  542. REQUIRE(error == false);
  543. CHECK(output == String("fish 5 frog"));
  544. // Int right padded with spaces.
  545. format = "fish %-5d frog";
  546. args.clear();
  547. args.push_back(5);
  548. output = format.sprintf(args, &error);
  549. REQUIRE(error == false);
  550. CHECK(output == String("fish 5 frog"));
  551. // Int with sign (positive).
  552. format = "fish %+d frog";
  553. args.clear();
  554. args.push_back(5);
  555. output = format.sprintf(args, &error);
  556. REQUIRE(error == false);
  557. CHECK(output == String("fish +5 frog"));
  558. // Negative int.
  559. format = "fish %d frog";
  560. args.clear();
  561. args.push_back(-5);
  562. output = format.sprintf(args, &error);
  563. REQUIRE(error == false);
  564. CHECK(output == String("fish -5 frog"));
  565. // Negative int left padded with spaces.
  566. format = "fish %5d frog";
  567. args.clear();
  568. args.push_back(-5);
  569. output = format.sprintf(args, &error);
  570. REQUIRE(error == false);
  571. CHECK(output == String("fish -5 frog"));
  572. // Negative int left padded with zeros.
  573. format = "fish %05d frog";
  574. args.clear();
  575. args.push_back(-5);
  576. output = format.sprintf(args, &error);
  577. REQUIRE(error == false);
  578. CHECK(output == String("fish -0005 frog"));
  579. // Negative int right padded with spaces.
  580. format = "fish %-5d frog";
  581. args.clear();
  582. args.push_back(-5);
  583. output = format.sprintf(args, &error);
  584. REQUIRE(error == false);
  585. CHECK(output == String("fish -5 frog"));
  586. // Negative int right padded with zeros. (0 ignored)
  587. format = "fish %-05d frog";
  588. args.clear();
  589. args.push_back(-5);
  590. ERR_PRINT_OFF; // Silence warning about 0 ignored.
  591. output = format.sprintf(args, &error);
  592. ERR_PRINT_ON;
  593. REQUIRE(error == false);
  594. CHECK(output == String("fish -5 frog"));
  595. // Hex (lower)
  596. format = "fish %x frog";
  597. args.clear();
  598. args.push_back(45);
  599. output = format.sprintf(args, &error);
  600. REQUIRE(error == false);
  601. CHECK(output == String("fish 2d frog"));
  602. // Hex (upper)
  603. format = "fish %X frog";
  604. args.clear();
  605. args.push_back(45);
  606. output = format.sprintf(args, &error);
  607. REQUIRE(error == false);
  608. CHECK(output == String("fish 2D frog"));
  609. // Octal
  610. format = "fish %o frog";
  611. args.clear();
  612. args.push_back(99);
  613. output = format.sprintf(args, &error);
  614. REQUIRE(error == false);
  615. CHECK(output == String("fish 143 frog"));
  616. ////// REALS
  617. // Real
  618. format = "fish %f frog";
  619. args.clear();
  620. args.push_back(99.99);
  621. output = format.sprintf(args, &error);
  622. REQUIRE(error == false);
  623. CHECK(output == String("fish 99.990000 frog"));
  624. // Real left-padded
  625. format = "fish %11f frog";
  626. args.clear();
  627. args.push_back(99.99);
  628. output = format.sprintf(args, &error);
  629. REQUIRE(error == false);
  630. CHECK(output == String("fish 99.990000 frog"));
  631. // Real right-padded
  632. format = "fish %-11f frog";
  633. args.clear();
  634. args.push_back(99.99);
  635. output = format.sprintf(args, &error);
  636. REQUIRE(error == false);
  637. CHECK(output == String("fish 99.990000 frog"));
  638. // Real given int.
  639. format = "fish %f frog";
  640. args.clear();
  641. args.push_back(99);
  642. output = format.sprintf(args, &error);
  643. REQUIRE(error == false);
  644. CHECK(output == String("fish 99.000000 frog"));
  645. // Real with sign (positive).
  646. format = "fish %+f frog";
  647. args.clear();
  648. args.push_back(99.99);
  649. output = format.sprintf(args, &error);
  650. REQUIRE(error == false);
  651. CHECK(output == String("fish +99.990000 frog"));
  652. // Real with 1 decimals.
  653. format = "fish %.1f frog";
  654. args.clear();
  655. args.push_back(99.99);
  656. output = format.sprintf(args, &error);
  657. REQUIRE(error == false);
  658. CHECK(output == String("fish 100.0 frog"));
  659. // Real with 12 decimals.
  660. format = "fish %.12f frog";
  661. args.clear();
  662. args.push_back(99.99);
  663. output = format.sprintf(args, &error);
  664. REQUIRE(error == false);
  665. CHECK(output == String("fish 99.990000000000 frog"));
  666. // Real with no decimals.
  667. format = "fish %.f frog";
  668. args.clear();
  669. args.push_back(99.99);
  670. output = format.sprintf(args, &error);
  671. REQUIRE(error == false);
  672. CHECK(output == String("fish 100 frog"));
  673. // Negative real right padded with zeros. (0 ignored)
  674. format = "fish %-011f frog";
  675. args.clear();
  676. args.push_back(-99.99);
  677. ERR_PRINT_OFF; // Silence warning about 0 ignored.
  678. output = format.sprintf(args, &error);
  679. ERR_PRINT_ON;
  680. REQUIRE(error == false);
  681. CHECK(output == String("fish -99.990000 frog"));
  682. /////// Strings.
  683. // String
  684. format = "fish %s frog";
  685. args.clear();
  686. args.push_back("cheese");
  687. output = format.sprintf(args, &error);
  688. REQUIRE(error == false);
  689. CHECK(output == String("fish cheese frog"));
  690. // String left-padded
  691. format = "fish %10s frog";
  692. args.clear();
  693. args.push_back("cheese");
  694. output = format.sprintf(args, &error);
  695. REQUIRE(error == false);
  696. CHECK(output == String("fish cheese frog"));
  697. // String right-padded
  698. format = "fish %-10s frog";
  699. args.clear();
  700. args.push_back("cheese");
  701. output = format.sprintf(args, &error);
  702. REQUIRE(error == false);
  703. CHECK(output == String("fish cheese frog"));
  704. ///// Characters
  705. // Character as string.
  706. format = "fish %c frog";
  707. args.clear();
  708. args.push_back("A");
  709. output = format.sprintf(args, &error);
  710. REQUIRE(error == false);
  711. CHECK(output == String("fish A frog"));
  712. // Character as int.
  713. format = "fish %c frog";
  714. args.clear();
  715. args.push_back(65);
  716. output = format.sprintf(args, &error);
  717. REQUIRE(error == false);
  718. CHECK(output == String("fish A frog"));
  719. ///// Dynamic width
  720. // String dynamic width
  721. format = "fish %*s frog";
  722. args.clear();
  723. args.push_back(10);
  724. args.push_back("cheese");
  725. output = format.sprintf(args, &error);
  726. REQUIRE(error == false);
  727. REQUIRE(output == String("fish cheese frog"));
  728. // Int dynamic width
  729. format = "fish %*d frog";
  730. args.clear();
  731. args.push_back(10);
  732. args.push_back(99);
  733. output = format.sprintf(args, &error);
  734. REQUIRE(error == false);
  735. REQUIRE(output == String("fish 99 frog"));
  736. // Float dynamic width
  737. format = "fish %*.*f frog";
  738. args.clear();
  739. args.push_back(10);
  740. args.push_back(3);
  741. args.push_back(99.99);
  742. output = format.sprintf(args, &error);
  743. REQUIRE(error == false);
  744. CHECK(output == String("fish 99.990 frog"));
  745. ///// Errors
  746. // More formats than arguments.
  747. format = "fish %s %s frog";
  748. args.clear();
  749. args.push_back("cheese");
  750. output = format.sprintf(args, &error);
  751. REQUIRE(error);
  752. CHECK(output == "not enough arguments for format string");
  753. // More arguments than formats.
  754. format = "fish %s frog";
  755. args.clear();
  756. args.push_back("hello");
  757. args.push_back("cheese");
  758. output = format.sprintf(args, &error);
  759. REQUIRE(error);
  760. CHECK(output == "not all arguments converted during string formatting");
  761. // Incomplete format.
  762. format = "fish %10";
  763. args.clear();
  764. args.push_back("cheese");
  765. output = format.sprintf(args, &error);
  766. REQUIRE(error);
  767. CHECK(output == "incomplete format");
  768. // Bad character in format string
  769. format = "fish %&f frog";
  770. args.clear();
  771. args.push_back("cheese");
  772. output = format.sprintf(args, &error);
  773. REQUIRE(error);
  774. CHECK(output == "unsupported format character");
  775. // Too many decimals.
  776. format = "fish %2.2.2f frog";
  777. args.clear();
  778. args.push_back(99.99);
  779. output = format.sprintf(args, &error);
  780. REQUIRE(error);
  781. CHECK(output == "too many decimal points in format");
  782. // * not a number
  783. format = "fish %*f frog";
  784. args.clear();
  785. args.push_back("cheese");
  786. args.push_back(99.99);
  787. output = format.sprintf(args, &error);
  788. REQUIRE(error);
  789. CHECK(output == "* wants number");
  790. // Character too long.
  791. format = "fish %c frog";
  792. args.clear();
  793. args.push_back("sc");
  794. output = format.sprintf(args, &error);
  795. REQUIRE(error);
  796. CHECK(output == "%c requires number or single-character string");
  797. // Character bad type.
  798. format = "fish %c frog";
  799. args.clear();
  800. args.push_back(Array());
  801. output = format.sprintf(args, &error);
  802. REQUIRE(error);
  803. CHECK(output == "%c requires number or single-character string");
  804. }
  805. TEST_CASE("[String] is_numeric") {
  806. CHECK(String("12").is_numeric());
  807. CHECK(String("1.2").is_numeric());
  808. CHECK(!String("AF").is_numeric());
  809. CHECK(String("-12").is_numeric());
  810. CHECK(String("-1.2").is_numeric());
  811. }
  812. TEST_CASE("[String] pad") {
  813. String s = String("test");
  814. CHECK(s.lpad(10, "x") == U"xxxxxxtest");
  815. CHECK(s.rpad(10, "x") == U"testxxxxxx");
  816. s = String("10.10");
  817. CHECK(s.pad_decimals(4) == U"10.1000");
  818. CHECK(s.pad_zeros(4) == U"0010.10");
  819. }
  820. TEST_CASE("[String] is_subsequence_of") {
  821. String a = "is subsequence of";
  822. CHECK(String("sub").is_subsequence_of(a));
  823. CHECK(!String("Sub").is_subsequence_of(a));
  824. CHECK(String("Sub").is_subsequence_ofn(a));
  825. }
  826. TEST_CASE("[String] match") {
  827. CHECK(String("img1.png").match("*.png"));
  828. CHECK(!String("img1.jpeg").match("*.png"));
  829. CHECK(!String("img1.Png").match("*.png"));
  830. CHECK(String("img1.Png").matchn("*.png"));
  831. }
  832. TEST_CASE("[String] IPVX address to string") {
  833. IPAddress ip0("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
  834. IPAddress ip(0x0123, 0x4567, 0x89ab, 0xcdef, true);
  835. IPAddress ip2("fe80::52e5:49ff:fe93:1baf");
  836. IPAddress ip3("::ffff:192.168.0.1");
  837. String ip4 = "192.168.0.1";
  838. CHECK(ip4.is_valid_ip_address());
  839. ip4 = "192.368.0.1";
  840. CHECK(!ip4.is_valid_ip_address());
  841. String ip6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
  842. CHECK(ip6.is_valid_ip_address());
  843. ip6 = "2001:0db8:85j3:0000:0000:8a2e:0370:7334";
  844. CHECK(!ip6.is_valid_ip_address());
  845. ip6 = "2001:0db8:85f345:0000:0000:8a2e:0370:7334";
  846. CHECK(!ip6.is_valid_ip_address());
  847. ip6 = "2001:0db8::0:8a2e:370:7334";
  848. CHECK(ip6.is_valid_ip_address());
  849. ip6 = "::ffff:192.168.0.1";
  850. CHECK(ip6.is_valid_ip_address());
  851. }
  852. TEST_CASE("[String] Capitalize against many strings") {
  853. String input = "bytes2var";
  854. String output = "Bytes 2 Var";
  855. CHECK(input.capitalize() == output);
  856. input = "linear2db";
  857. output = "Linear 2 Db";
  858. CHECK(input.capitalize() == output);
  859. input = "vector3";
  860. output = "Vector 3";
  861. CHECK(input.capitalize() == output);
  862. input = "sha256";
  863. output = "Sha 256";
  864. CHECK(input.capitalize() == output);
  865. input = "2db";
  866. output = "2 Db";
  867. CHECK(input.capitalize() == output);
  868. input = "PascalCase";
  869. output = "Pascal Case";
  870. CHECK(input.capitalize() == output);
  871. input = "PascalPascalCase";
  872. output = "Pascal Pascal Case";
  873. CHECK(input.capitalize() == output);
  874. input = "snake_case";
  875. output = "Snake Case";
  876. CHECK(input.capitalize() == output);
  877. input = "snake_snake_case";
  878. output = "Snake Snake Case";
  879. CHECK(input.capitalize() == output);
  880. input = "sha256sum";
  881. output = "Sha 256 Sum";
  882. CHECK(input.capitalize() == output);
  883. input = "cat2dog";
  884. output = "Cat 2 Dog";
  885. CHECK(input.capitalize() == output);
  886. input = "function(name)";
  887. output = "Function(name)";
  888. CHECK(input.capitalize() == output);
  889. input = "snake_case_function(snake_case_arg)";
  890. output = "Snake Case Function(snake Case Arg)";
  891. CHECK(input.capitalize() == output);
  892. input = "snake_case_function( snake_case_arg )";
  893. output = "Snake Case Function( Snake Case Arg )";
  894. CHECK(input.capitalize() == output);
  895. }
  896. TEST_CASE("[String] Checking string is empty when it should be") {
  897. bool state = true;
  898. bool success;
  899. String a = "";
  900. success = a[0] == 0;
  901. if (!success) {
  902. state = false;
  903. }
  904. String b = "Godot";
  905. success = b[b.size()] == 0;
  906. if (!success) {
  907. state = false;
  908. }
  909. const String c = "";
  910. success = c[0] == 0;
  911. if (!success) {
  912. state = false;
  913. }
  914. const String d = "Godot";
  915. success = d[d.size()] == 0;
  916. if (!success) {
  917. state = false;
  918. }
  919. CHECK(state);
  920. }
  921. TEST_CASE("[String] lstrip and rstrip") {
  922. #define STRIP_TEST(x) \
  923. { \
  924. bool success = x; \
  925. state = state && success; \
  926. }
  927. bool state = true;
  928. // strip none
  929. STRIP_TEST(String("abc").lstrip("") == "abc");
  930. STRIP_TEST(String("abc").rstrip("") == "abc");
  931. // strip one
  932. STRIP_TEST(String("abc").lstrip("a") == "bc");
  933. STRIP_TEST(String("abc").rstrip("c") == "ab");
  934. // strip lots
  935. STRIP_TEST(String("bababbababccc").lstrip("ab") == "ccc");
  936. STRIP_TEST(String("aaabcbcbcbbcbbc").rstrip("cb") == "aaa");
  937. // strip empty string
  938. STRIP_TEST(String("").lstrip("") == "");
  939. STRIP_TEST(String("").rstrip("") == "");
  940. // strip to empty string
  941. STRIP_TEST(String("abcabcabc").lstrip("bca") == "");
  942. STRIP_TEST(String("abcabcabc").rstrip("bca") == "");
  943. // don't strip wrong end
  944. STRIP_TEST(String("abc").lstrip("c") == "abc");
  945. STRIP_TEST(String("abca").lstrip("a") == "bca");
  946. STRIP_TEST(String("abc").rstrip("a") == "abc");
  947. STRIP_TEST(String("abca").rstrip("a") == "abc");
  948. // in utf-8 "¿" (\u00bf) has the same first byte as "µ" (\u00b5)
  949. // and the same second as "ÿ" (\u00ff)
  950. STRIP_TEST(String::utf8("¿").lstrip(String::utf8("µÿ")) == String::utf8("¿"));
  951. STRIP_TEST(String::utf8("¿").rstrip(String::utf8("µÿ")) == String::utf8("¿"));
  952. STRIP_TEST(String::utf8("µ¿ÿ").lstrip(String::utf8("µÿ")) == String::utf8("¿ÿ"));
  953. STRIP_TEST(String::utf8("µ¿ÿ").rstrip(String::utf8("µÿ")) == String::utf8("µ¿"));
  954. // the above tests repeated with additional superfluous strip chars
  955. // strip none
  956. STRIP_TEST(String("abc").lstrip("qwjkl") == "abc");
  957. STRIP_TEST(String("abc").rstrip("qwjkl") == "abc");
  958. // strip one
  959. STRIP_TEST(String("abc").lstrip("qwajkl") == "bc");
  960. STRIP_TEST(String("abc").rstrip("qwcjkl") == "ab");
  961. // strip lots
  962. STRIP_TEST(String("bababbababccc").lstrip("qwabjkl") == "ccc");
  963. STRIP_TEST(String("aaabcbcbcbbcbbc").rstrip("qwcbjkl") == "aaa");
  964. // strip empty string
  965. STRIP_TEST(String("").lstrip("qwjkl") == "");
  966. STRIP_TEST(String("").rstrip("qwjkl") == "");
  967. // strip to empty string
  968. STRIP_TEST(String("abcabcabc").lstrip("qwbcajkl") == "");
  969. STRIP_TEST(String("abcabcabc").rstrip("qwbcajkl") == "");
  970. // don't strip wrong end
  971. STRIP_TEST(String("abc").lstrip("qwcjkl") == "abc");
  972. STRIP_TEST(String("abca").lstrip("qwajkl") == "bca");
  973. STRIP_TEST(String("abc").rstrip("qwajkl") == "abc");
  974. STRIP_TEST(String("abca").rstrip("qwajkl") == "abc");
  975. // in utf-8 "¿" (\u00bf) has the same first byte as "µ" (\u00b5)
  976. // and the same second as "ÿ" (\u00ff)
  977. STRIP_TEST(String::utf8("¿").lstrip(String::utf8("qwaµÿjkl")) == String::utf8("¿"));
  978. STRIP_TEST(String::utf8("¿").rstrip(String::utf8("qwaµÿjkl")) == String::utf8("¿"));
  979. STRIP_TEST(String::utf8("µ¿ÿ").lstrip(String::utf8("qwaµÿjkl")) == String::utf8("¿ÿ"));
  980. STRIP_TEST(String::utf8("µ¿ÿ").rstrip(String::utf8("qwaµÿjkl")) == String::utf8("µ¿"));
  981. CHECK(state);
  982. #undef STRIP_TEST
  983. }
  984. TEST_CASE("[String] Ensuring empty string into parse_utf8 passes empty string") {
  985. String empty;
  986. CHECK(empty.parse_utf8(nullptr, -1) == ERR_INVALID_DATA);
  987. }
  988. TEST_CASE("[String] Cyrillic to_lower()") {
  989. String upper = String::utf8("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ");
  990. String lower = String::utf8("абвгдеёжзийклмнопрстуфхцчшщъыьэюя");
  991. String test = upper.to_lower();
  992. bool state = test == lower;
  993. CHECK(state);
  994. }
  995. TEST_CASE("[String] Count and countn functionality") {
  996. #define COUNT_TEST(x) \
  997. { \
  998. bool success = x; \
  999. state = state && success; \
  1000. }
  1001. bool state = true;
  1002. COUNT_TEST(String("").count("Test") == 0);
  1003. COUNT_TEST(String("Test").count("") == 0);
  1004. COUNT_TEST(String("Test").count("test") == 0);
  1005. COUNT_TEST(String("Test").count("TEST") == 0);
  1006. COUNT_TEST(String("TEST").count("TEST") == 1);
  1007. COUNT_TEST(String("Test").count("Test") == 1);
  1008. COUNT_TEST(String("aTest").count("Test") == 1);
  1009. COUNT_TEST(String("Testa").count("Test") == 1);
  1010. COUNT_TEST(String("TestTestTest").count("Test") == 3);
  1011. COUNT_TEST(String("TestTestTest").count("TestTest") == 1);
  1012. COUNT_TEST(String("TestGodotTestGodotTestGodot").count("Test") == 3);
  1013. COUNT_TEST(String("TestTestTestTest").count("Test", 4, 8) == 1);
  1014. COUNT_TEST(String("TestTestTestTest").count("Test", 4, 12) == 2);
  1015. COUNT_TEST(String("TestTestTestTest").count("Test", 4, 16) == 3);
  1016. COUNT_TEST(String("TestTestTestTest").count("Test", 4) == 3);
  1017. COUNT_TEST(String("Test").countn("test") == 1);
  1018. COUNT_TEST(String("Test").countn("TEST") == 1);
  1019. COUNT_TEST(String("testTest-Testatest").countn("tEst") == 4);
  1020. COUNT_TEST(String("testTest-TeStatest").countn("tEsT", 4, 16) == 2);
  1021. CHECK(state);
  1022. #undef COUNT_TEST
  1023. }
  1024. TEST_CASE("[String] Bigrams") {
  1025. String s = "abcd";
  1026. Vector<String> bigr = s.bigrams();
  1027. CHECK(bigr.size() == 3);
  1028. CHECK(bigr[0] == "ab");
  1029. CHECK(bigr[1] == "bc");
  1030. CHECK(bigr[2] == "cd");
  1031. }
  1032. TEST_CASE("[String] c-escape/unescape") {
  1033. String s = "\\1\a2\b\f3\n45\r6\t7\v8\'9\?0\"";
  1034. CHECK(s.c_escape().c_unescape() == s);
  1035. }
  1036. TEST_CASE("[String] indent") {
  1037. static const char *input[] = {
  1038. "",
  1039. "aaa\nbbb",
  1040. "\tcontains\n\tindent",
  1041. "empty\n\nline",
  1042. };
  1043. static const char *expected[] = {
  1044. "",
  1045. "\taaa\n\tbbb",
  1046. "\t\tcontains\n\t\tindent",
  1047. "\tempty\n\n\tline",
  1048. };
  1049. for (int i = 0; i < 3; i++) {
  1050. CHECK(String(input[i]).indent("\t") == expected[i]);
  1051. }
  1052. }
  1053. TEST_CASE("[String] dedent") {
  1054. String s = " aaa\n bbb";
  1055. String t = "aaa\nbbb";
  1056. CHECK(s.dedent() == t);
  1057. }
  1058. TEST_CASE("[String] Path functions") {
  1059. static const char *path[7] = { "C:\\Godot\\project\\test.tscn", "/Godot/project/test.xscn", "../Godot/project/test.scn", "Godot\\test.doc", "C:\\test.", "res://test", "/.test" };
  1060. static const char *base_dir[7] = { "C:\\Godot\\project", "/Godot/project", "../Godot/project", "Godot", "C:\\", "res://", "/" };
  1061. static const char *base_name[7] = { "C:\\Godot\\project\\test", "/Godot/project/test", "../Godot/project/test", "Godot\\test", "C:\\test", "res://test", "/" };
  1062. static const char *ext[7] = { "tscn", "xscn", "scn", "doc", "", "", "test" };
  1063. static const char *file[7] = { "test.tscn", "test.xscn", "test.scn", "test.doc", "test.", "test", ".test" };
  1064. static const bool abs[7] = { true, true, false, false, true, true, true };
  1065. for (int i = 0; i < 7; i++) {
  1066. CHECK(String(path[i]).get_base_dir() == base_dir[i]);
  1067. CHECK(String(path[i]).get_basename() == base_name[i]);
  1068. CHECK(String(path[i]).get_extension() == ext[i]);
  1069. CHECK(String(path[i]).get_file() == file[i]);
  1070. CHECK(String(path[i]).is_absolute_path() == abs[i]);
  1071. CHECK(String(path[i]).is_relative_path() != abs[i]);
  1072. CHECK(String(path[i]).simplify_path().get_base_dir().plus_file(file[i]) == String(path[i]).simplify_path());
  1073. }
  1074. static const char *file_name[3] = { "test.tscn", "test://.xscn", "?tes*t.scn" };
  1075. static const bool valid[3] = { true, false, false };
  1076. for (int i = 0; i < 3; i++) {
  1077. CHECK(String(file_name[i]).is_valid_filename() == valid[i]);
  1078. }
  1079. }
  1080. TEST_CASE("[String] hash") {
  1081. String a = "Test";
  1082. String b = "Test";
  1083. String c = "West";
  1084. CHECK(a.hash() == b.hash());
  1085. CHECK(a.hash() != c.hash());
  1086. CHECK(a.hash64() == b.hash64());
  1087. CHECK(a.hash64() != c.hash64());
  1088. }
  1089. TEST_CASE("[String] uri_encode/unescape") {
  1090. String s = "Godot Engine:'docs'";
  1091. String t = "Godot%20Engine%3A%27docs%27";
  1092. String x1 = "T%C4%93%C5%A1t";
  1093. static const uint8_t u8str[] = { 0x54, 0xC4, 0x93, 0xC5, 0xA1, 0x74, 0x00 };
  1094. String x2 = String::utf8((const char *)u8str);
  1095. String x3 = U"Tēšt";
  1096. CHECK(x1.uri_decode() == x2);
  1097. CHECK(x1.uri_decode() == x3);
  1098. CHECK((x1 + x3).uri_decode() == (x2 + x3)); // Mixed unicode and URL encoded string, e.g. GTK+ bookmark.
  1099. CHECK(x2.uri_encode() == x1);
  1100. CHECK(x3.uri_encode() == x1);
  1101. CHECK(s.uri_encode() == t);
  1102. CHECK(t.uri_decode() == s);
  1103. }
  1104. TEST_CASE("[String] xml_escape/unescape") {
  1105. String s = "\"Test\" <test@test&'test'>";
  1106. CHECK(s.xml_escape(true).xml_unescape() == s);
  1107. CHECK(s.xml_escape(false).xml_unescape() == s);
  1108. }
  1109. TEST_CASE("[String] xml_unescape") {
  1110. // Named entities
  1111. String input = "&quot;&amp;&apos;&lt;&gt;";
  1112. CHECK(input.xml_unescape() == "\"&\'<>");
  1113. // Numeric entities
  1114. input = "&#x41;&#66;";
  1115. CHECK(input.xml_unescape() == "AB");
  1116. input = "&#0;&x#0;More text";
  1117. String result = input.xml_unescape();
  1118. // Didn't put in a leading NUL and terminate the string
  1119. CHECK(input.length() > 0);
  1120. CHECK(input[0] != '\0');
  1121. // Entity should be left as-is if invalid
  1122. CHECK(input.xml_unescape() == input);
  1123. // Check near char32_t range
  1124. input = "&#xFFFFFFFF;";
  1125. result = input.xml_unescape();
  1126. CHECK(result.length() == 1);
  1127. CHECK(result[0] == 0xFFFFFFFF);
  1128. input = "&#4294967295;";
  1129. result = input.xml_unescape();
  1130. CHECK(result.length() == 1);
  1131. CHECK(result[0] == 0xFFFFFFFF);
  1132. // Check out of range of char32_t
  1133. input = "&#xFFFFFFFFF;";
  1134. CHECK(input.xml_unescape() == input);
  1135. input = "&#4294967296;";
  1136. CHECK(input.xml_unescape() == input);
  1137. // Shouldn't consume without ending in a ';'
  1138. input = "&#66";
  1139. CHECK(input.xml_unescape() == input);
  1140. input = "&#x41";
  1141. CHECK(input.xml_unescape() == input);
  1142. // Invalid characters should make the entity ignored
  1143. input = "&#x41SomeIrrelevantText;";
  1144. CHECK(input.xml_unescape() == input);
  1145. input = "&#66SomeIrrelevantText;";
  1146. CHECK(input.xml_unescape() == input);
  1147. }
  1148. TEST_CASE("[String] Strip escapes") {
  1149. String s = "\t\tTest Test\r\n Test";
  1150. CHECK(s.strip_escapes() == "Test Test Test");
  1151. }
  1152. TEST_CASE("[String] Similarity") {
  1153. String a = "Test";
  1154. String b = "West";
  1155. String c = "Toad";
  1156. CHECK(a.similarity(b) > a.similarity(c));
  1157. }
  1158. TEST_CASE("[String] Strip edges") {
  1159. String s = "\t Test Test ";
  1160. CHECK(s.strip_edges(true, false) == "Test Test ");
  1161. CHECK(s.strip_edges(false, true) == "\t Test Test");
  1162. CHECK(s.strip_edges(true, true) == "Test Test");
  1163. }
  1164. TEST_CASE("[String] Trim") {
  1165. String s = "aaaTestbbb";
  1166. CHECK(s.trim_prefix("aaa") == "Testbbb");
  1167. CHECK(s.trim_suffix("bbb") == "aaaTest");
  1168. CHECK(s.trim_suffix("Test") == s);
  1169. }
  1170. TEST_CASE("[String] Right/Left") {
  1171. String s = "aaaTestbbb";
  1172. // ^
  1173. CHECK(s.right(6) == "estbbb");
  1174. CHECK(s.right(-6) == "tbbb");
  1175. CHECK(s.left(6) == "aaaTes");
  1176. CHECK(s.left(-6) == "aaaT");
  1177. }
  1178. TEST_CASE("[String] Repeat") {
  1179. String s = "abababab";
  1180. String x = "ab";
  1181. String t = x.repeat(4);
  1182. CHECK(t == s);
  1183. }
  1184. TEST_CASE("[String] SHA1/SHA256/MD5") {
  1185. String s = "Godot";
  1186. String sha1 = "a1e91f39b9fce6a9998b14bdbe2aa2b39dc2d201";
  1187. static uint8_t sha1_buf[20] = {
  1188. 0xA1, 0xE9, 0x1F, 0x39, 0xB9, 0xFC, 0xE6, 0xA9, 0x99, 0x8B, 0x14, 0xBD, 0xBE, 0x2A, 0xA2, 0xB3,
  1189. 0x9D, 0xC2, 0xD2, 0x01
  1190. };
  1191. String sha256 = "2a02b2443f7985d89d09001086ae3dcfa6eb0f55c6ef170715d42328e16e6cb8";
  1192. static uint8_t sha256_buf[32] = {
  1193. 0x2A, 0x02, 0xB2, 0x44, 0x3F, 0x79, 0x85, 0xD8, 0x9D, 0x09, 0x00, 0x10, 0x86, 0xAE, 0x3D, 0xCF,
  1194. 0xA6, 0xEB, 0x0F, 0x55, 0xC6, 0xEF, 0x17, 0x07, 0x15, 0xD4, 0x23, 0x28, 0xE1, 0x6E, 0x6C, 0xB8
  1195. };
  1196. String md5 = "4a336d087aeb0390da10ee2ea7cb87f8";
  1197. static uint8_t md5_buf[16] = {
  1198. 0x4A, 0x33, 0x6D, 0x08, 0x7A, 0xEB, 0x03, 0x90, 0xDA, 0x10, 0xEE, 0x2E, 0xA7, 0xCB, 0x87, 0xF8
  1199. };
  1200. PackedByteArray buf = s.sha1_buffer();
  1201. CHECK(memcmp(sha1_buf, buf.ptr(), 20) == 0);
  1202. CHECK(s.sha1_text() == sha1);
  1203. buf = s.sha256_buffer();
  1204. CHECK(memcmp(sha256_buf, buf.ptr(), 32) == 0);
  1205. CHECK(s.sha256_text() == sha256);
  1206. buf = s.md5_buffer();
  1207. CHECK(memcmp(md5_buf, buf.ptr(), 16) == 0);
  1208. CHECK(s.md5_text() == md5);
  1209. }
  1210. TEST_CASE("[String] Join") {
  1211. String s = ", ";
  1212. Vector<String> parts;
  1213. parts.push_back("One");
  1214. parts.push_back("B");
  1215. parts.push_back("C");
  1216. String t = s.join(parts);
  1217. CHECK(t == "One, B, C");
  1218. }
  1219. TEST_CASE("[String] Is_*") {
  1220. static const char *data[12] = { "-30", "100", "10.1", "10,1", "1e2", "1e-2", "1e2e3", "0xAB", "AB", "Test1", "1Test", "Test*1" };
  1221. static bool isnum[12] = { true, true, true, false, false, false, false, false, false, false, false, false };
  1222. static bool isint[12] = { true, true, false, false, false, false, false, false, false, false, false, false };
  1223. static bool ishex[12] = { true, true, false, false, true, false, true, false, true, false, false, false };
  1224. static bool ishex_p[12] = { false, false, false, false, false, false, false, true, false, false, false, false };
  1225. static bool isflt[12] = { true, true, true, false, true, true, false, false, false, false, false, false };
  1226. static bool isid[12] = { false, false, false, false, false, false, false, false, true, true, false, false };
  1227. for (int i = 0; i < 12; i++) {
  1228. String s = String(data[i]);
  1229. CHECK(s.is_numeric() == isnum[i]);
  1230. CHECK(s.is_valid_int() == isint[i]);
  1231. CHECK(s.is_valid_hex_number(false) == ishex[i]);
  1232. CHECK(s.is_valid_hex_number(true) == ishex_p[i]);
  1233. CHECK(s.is_valid_float() == isflt[i]);
  1234. CHECK(s.is_valid_identifier() == isid[i]);
  1235. }
  1236. }
  1237. TEST_CASE("[String] humanize_size") {
  1238. CHECK(String::humanize_size(1000) == "1000 B");
  1239. CHECK(String::humanize_size(1025) == "1.00 KiB");
  1240. CHECK(String::humanize_size(1025300) == "1001.2 KiB");
  1241. CHECK(String::humanize_size(100523550) == "95.86 MiB");
  1242. CHECK(String::humanize_size(5345555000) == "4.97 GiB");
  1243. }
  1244. TEST_CASE("[String] validate_node_name") {
  1245. String numeric_only = "12345";
  1246. CHECK(numeric_only.validate_node_name() == "12345");
  1247. String name_with_spaces = "Name with spaces";
  1248. CHECK(name_with_spaces.validate_node_name() == "Name with spaces");
  1249. String name_with_kana = U"Name with kana ゴドツ";
  1250. CHECK(name_with_kana.validate_node_name() == U"Name with kana ゴドツ");
  1251. String name_with_invalid_chars = "Name with invalid characters :.@removed!";
  1252. CHECK(name_with_invalid_chars.validate_node_name() == "Name with invalid characters removed!");
  1253. }
  1254. TEST_CASE("[String] validate_identifier") {
  1255. String empty_string;
  1256. CHECK(empty_string.validate_identifier() == "_");
  1257. String numeric_only = "12345";
  1258. CHECK(numeric_only.validate_identifier() == "_2345");
  1259. String name_with_spaces = "Name with spaces";
  1260. CHECK(name_with_spaces.validate_identifier() == "Name_with_spaces");
  1261. String name_with_invalid_chars = String::utf8("Invalid characters:@*#&世界");
  1262. CHECK(name_with_invalid_chars.validate_identifier() == "Invalid_characters_______");
  1263. }
  1264. TEST_CASE("[String] Variant indexed get") {
  1265. Variant s = String("abcd");
  1266. bool valid = false;
  1267. bool oob = true;
  1268. String r = s.get_indexed(1, valid, oob);
  1269. CHECK(valid);
  1270. CHECK_FALSE(oob);
  1271. CHECK_EQ(r, String("b"));
  1272. }
  1273. TEST_CASE("[String] Variant validated indexed get") {
  1274. Variant s = String("abcd");
  1275. Variant::ValidatedIndexedGetter getter = Variant::get_member_validated_indexed_getter(Variant::STRING);
  1276. Variant r;
  1277. bool oob = true;
  1278. getter(&s, 1, &r, &oob);
  1279. CHECK_FALSE(oob);
  1280. CHECK_EQ(r, String("b"));
  1281. }
  1282. TEST_CASE("[String] Variant ptr indexed get") {
  1283. String s("abcd");
  1284. Variant::PTRIndexedGetter getter = Variant::get_member_ptr_indexed_getter(Variant::STRING);
  1285. String r;
  1286. getter(&s, 1, &r);
  1287. CHECK_EQ(r, String("b"));
  1288. }
  1289. TEST_CASE("[String] Variant indexed set") {
  1290. Variant s = String("abcd");
  1291. bool valid = false;
  1292. bool oob = true;
  1293. s.set_indexed(1, String("z"), valid, oob);
  1294. CHECK(valid);
  1295. CHECK_FALSE(oob);
  1296. CHECK_EQ(s, String("azcd"));
  1297. }
  1298. TEST_CASE("[String] Variant validated indexed set") {
  1299. Variant s = String("abcd");
  1300. Variant::ValidatedIndexedSetter setter = Variant::get_member_validated_indexed_setter(Variant::STRING);
  1301. Variant v = String("z");
  1302. bool oob = true;
  1303. setter(&s, 1, &v, &oob);
  1304. CHECK_FALSE(oob);
  1305. CHECK_EQ(s, String("azcd"));
  1306. }
  1307. TEST_CASE("[String] Variant ptr indexed set") {
  1308. String s("abcd");
  1309. Variant::PTRIndexedSetter setter = Variant::get_member_ptr_indexed_setter(Variant::STRING);
  1310. String v("z");
  1311. setter(&s, 1, &v);
  1312. CHECK_EQ(s, String("azcd"));
  1313. }
  1314. TEST_CASE("[Stress][String] Empty via ' == String()'") {
  1315. for (int i = 0; i < 100000; ++i) {
  1316. String str = "Hello World!";
  1317. if (str.is_empty()) {
  1318. continue;
  1319. }
  1320. }
  1321. }
  1322. TEST_CASE("[Stress][String] Empty via `is_empty()`") {
  1323. for (int i = 0; i < 100000; ++i) {
  1324. String str = "Hello World!";
  1325. if (str.is_empty()) {
  1326. continue;
  1327. }
  1328. }
  1329. }
  1330. } // namespace TestString
  1331. #endif // TEST_STRING_H