test_string.h 75 KB

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