ustring.cpp 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858
  1. /*************************************************************************/
  2. /* ustring.cpp */
  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. #include "ustring.h"
  31. #include "core/crypto/crypto_core.h"
  32. #include "core/math/color.h"
  33. #include "core/math/math_funcs.h"
  34. #include "core/os/memory.h"
  35. #include "core/string/print_string.h"
  36. #include "core/string/translation.h"
  37. #include "core/string/ucaps.h"
  38. #include "core/variant/variant.h"
  39. #include "core/version_generated.gen.h"
  40. #include <stdio.h>
  41. #include <stdlib.h>
  42. #include <cstdint>
  43. #ifdef _MSC_VER
  44. #define _CRT_SECURE_NO_WARNINGS // to disable build-time warning which suggested to use strcpy_s instead strcpy
  45. #endif
  46. #if defined(MINGW_ENABLED) || defined(_MSC_VER)
  47. #define snprintf _snprintf_s
  48. #endif
  49. static const int MAX_DECIMALS = 32;
  50. static _FORCE_INLINE_ char32_t lower_case(char32_t c) {
  51. return (is_ascii_upper_case(c) ? (c + ('a' - 'A')) : c);
  52. }
  53. const char CharString::_null = 0;
  54. const char16_t Char16String::_null = 0;
  55. const char32_t String::_null = 0;
  56. bool select_word(const String &p_s, int p_col, int &r_beg, int &r_end) {
  57. const String &s = p_s;
  58. int beg = CLAMP(p_col, 0, s.length());
  59. int end = beg;
  60. if (s[beg] > 32 || beg == s.length()) {
  61. bool symbol = beg < s.length() && is_symbol(s[beg]);
  62. while (beg > 0 && s[beg - 1] > 32 && (symbol == is_symbol(s[beg - 1]))) {
  63. beg--;
  64. }
  65. while (end < s.length() && s[end + 1] > 32 && (symbol == is_symbol(s[end + 1]))) {
  66. end++;
  67. }
  68. if (end < s.length()) {
  69. end += 1;
  70. }
  71. r_beg = beg;
  72. r_end = end;
  73. return true;
  74. } else {
  75. return false;
  76. }
  77. }
  78. /*************************************************************************/
  79. /* Char16String */
  80. /*************************************************************************/
  81. bool Char16String::operator<(const Char16String &p_right) const {
  82. if (length() == 0) {
  83. return p_right.length() != 0;
  84. }
  85. return is_str_less(get_data(), p_right.get_data());
  86. }
  87. Char16String &Char16String::operator+=(char16_t p_char) {
  88. const int lhs_len = length();
  89. resize(lhs_len + 2);
  90. char16_t *dst = ptrw();
  91. dst[lhs_len] = p_char;
  92. dst[lhs_len + 1] = 0;
  93. return *this;
  94. }
  95. void Char16String::operator=(const char16_t *p_cstr) {
  96. copy_from(p_cstr);
  97. }
  98. const char16_t *Char16String::get_data() const {
  99. if (size()) {
  100. return &operator[](0);
  101. } else {
  102. return u"";
  103. }
  104. }
  105. void Char16String::copy_from(const char16_t *p_cstr) {
  106. if (!p_cstr) {
  107. resize(0);
  108. return;
  109. }
  110. const char16_t *s = p_cstr;
  111. for (; *s; s++) {
  112. }
  113. size_t len = s - p_cstr;
  114. if (len == 0) {
  115. resize(0);
  116. return;
  117. }
  118. Error err = resize(++len); // include terminating null char
  119. ERR_FAIL_COND_MSG(err != OK, "Failed to copy char16_t string.");
  120. memcpy(ptrw(), p_cstr, len * sizeof(char16_t));
  121. }
  122. /*************************************************************************/
  123. /* CharString */
  124. /*************************************************************************/
  125. bool CharString::operator<(const CharString &p_right) const {
  126. if (length() == 0) {
  127. return p_right.length() != 0;
  128. }
  129. return is_str_less(get_data(), p_right.get_data());
  130. }
  131. CharString &CharString::operator+=(char p_char) {
  132. const int lhs_len = length();
  133. resize(lhs_len + 2);
  134. char *dst = ptrw();
  135. dst[lhs_len] = p_char;
  136. dst[lhs_len + 1] = 0;
  137. return *this;
  138. }
  139. void CharString::operator=(const char *p_cstr) {
  140. copy_from(p_cstr);
  141. }
  142. const char *CharString::get_data() const {
  143. if (size()) {
  144. return &operator[](0);
  145. } else {
  146. return "";
  147. }
  148. }
  149. void CharString::copy_from(const char *p_cstr) {
  150. if (!p_cstr) {
  151. resize(0);
  152. return;
  153. }
  154. size_t len = strlen(p_cstr);
  155. if (len == 0) {
  156. resize(0);
  157. return;
  158. }
  159. Error err = resize(++len); // include terminating null char
  160. ERR_FAIL_COND_MSG(err != OK, "Failed to copy C-string.");
  161. memcpy(ptrw(), p_cstr, len);
  162. }
  163. /*************************************************************************/
  164. /* String */
  165. /*************************************************************************/
  166. //kind of poor should be rewritten properly
  167. String String::word_wrap(int p_chars_per_line) const {
  168. int from = 0;
  169. int last_space = 0;
  170. String ret;
  171. for (int i = 0; i < length(); i++) {
  172. if (i - from >= p_chars_per_line) {
  173. if (last_space == -1) {
  174. ret += substr(from, i - from + 1) + "\n";
  175. } else {
  176. ret += substr(from, last_space - from) + "\n";
  177. i = last_space; //rewind
  178. }
  179. from = i + 1;
  180. last_space = -1;
  181. } else if (operator[](i) == ' ' || operator[](i) == '\t') {
  182. last_space = i;
  183. } else if (operator[](i) == '\n') {
  184. ret += substr(from, i - from) + "\n";
  185. from = i + 1;
  186. last_space = -1;
  187. }
  188. }
  189. if (from < length()) {
  190. ret += substr(from, length());
  191. }
  192. return ret;
  193. }
  194. Error String::parse_url(String &r_scheme, String &r_host, int &r_port, String &r_path) const {
  195. // Splits the URL into scheme, host, port, path. Strip credentials when present.
  196. String base = *this;
  197. r_scheme = "";
  198. r_host = "";
  199. r_port = 0;
  200. r_path = "";
  201. int pos = base.find("://");
  202. // Scheme
  203. if (pos != -1) {
  204. r_scheme = base.substr(0, pos + 3).to_lower();
  205. base = base.substr(pos + 3, base.length() - pos - 3);
  206. }
  207. pos = base.find("/");
  208. // Path
  209. if (pos != -1) {
  210. r_path = base.substr(pos, base.length() - pos);
  211. base = base.substr(0, pos);
  212. }
  213. // Host
  214. pos = base.find("@");
  215. if (pos != -1) {
  216. // Strip credentials
  217. base = base.substr(pos + 1, base.length() - pos - 1);
  218. }
  219. if (base.begins_with("[")) {
  220. // Literal IPv6
  221. pos = base.rfind("]");
  222. if (pos == -1) {
  223. return ERR_INVALID_PARAMETER;
  224. }
  225. r_host = base.substr(1, pos - 1);
  226. base = base.substr(pos + 1, base.length() - pos - 1);
  227. } else {
  228. // Anything else
  229. if (base.get_slice_count(":") > 2) {
  230. return ERR_INVALID_PARAMETER;
  231. }
  232. pos = base.rfind(":");
  233. if (pos == -1) {
  234. r_host = base;
  235. base = "";
  236. } else {
  237. r_host = base.substr(0, pos);
  238. base = base.substr(pos, base.length() - pos);
  239. }
  240. }
  241. if (r_host.is_empty()) {
  242. return ERR_INVALID_PARAMETER;
  243. }
  244. r_host = r_host.to_lower();
  245. // Port
  246. if (base.begins_with(":")) {
  247. base = base.substr(1, base.length() - 1);
  248. if (!base.is_valid_int()) {
  249. return ERR_INVALID_PARAMETER;
  250. }
  251. r_port = base.to_int();
  252. if (r_port < 1 || r_port > 65535) {
  253. return ERR_INVALID_PARAMETER;
  254. }
  255. }
  256. return OK;
  257. }
  258. void String::copy_from(const char *p_cstr) {
  259. // copy Latin-1 encoded c-string directly
  260. if (!p_cstr) {
  261. resize(0);
  262. return;
  263. }
  264. const size_t len = strlen(p_cstr);
  265. if (len == 0) {
  266. resize(0);
  267. return;
  268. }
  269. resize(len + 1); // include 0
  270. char32_t *dst = this->ptrw();
  271. for (size_t i = 0; i <= len; i++) {
  272. dst[i] = p_cstr[i];
  273. }
  274. }
  275. void String::copy_from(const char *p_cstr, const int p_clip_to) {
  276. // copy Latin-1 encoded c-string directly
  277. if (!p_cstr) {
  278. resize(0);
  279. return;
  280. }
  281. int len = 0;
  282. const char *ptr = p_cstr;
  283. while ((p_clip_to < 0 || len < p_clip_to) && *(ptr++) != 0) {
  284. len++;
  285. }
  286. if (len == 0) {
  287. resize(0);
  288. return;
  289. }
  290. resize(len + 1); // include 0
  291. char32_t *dst = this->ptrw();
  292. for (int i = 0; i < len; i++) {
  293. dst[i] = p_cstr[i];
  294. }
  295. dst[len] = 0;
  296. }
  297. void String::copy_from(const wchar_t *p_cstr) {
  298. #ifdef WINDOWS_ENABLED
  299. // wchar_t is 16-bit, parse as UTF-16
  300. parse_utf16((const char16_t *)p_cstr);
  301. #else
  302. // wchar_t is 32-bit, copy directly
  303. copy_from((const char32_t *)p_cstr);
  304. #endif
  305. }
  306. void String::copy_from(const wchar_t *p_cstr, const int p_clip_to) {
  307. #ifdef WINDOWS_ENABLED
  308. // wchar_t is 16-bit, parse as UTF-16
  309. parse_utf16((const char16_t *)p_cstr, p_clip_to);
  310. #else
  311. // wchar_t is 32-bit, copy directly
  312. copy_from((const char32_t *)p_cstr, p_clip_to);
  313. #endif
  314. }
  315. void String::copy_from(const char32_t &p_char) {
  316. resize(2);
  317. char32_t *dst = ptrw();
  318. if ((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff)) {
  319. print_error("Unicode parsing error: Invalid unicode codepoint " + num_int64(p_char, 16) + ".");
  320. dst[0] = 0xfffd;
  321. } else {
  322. dst[0] = p_char;
  323. }
  324. dst[1] = 0;
  325. }
  326. void String::copy_from(const char32_t *p_cstr) {
  327. if (!p_cstr) {
  328. resize(0);
  329. return;
  330. }
  331. int len = 0;
  332. const char32_t *ptr = p_cstr;
  333. while (*(ptr++) != 0) {
  334. len++;
  335. }
  336. if (len == 0) {
  337. resize(0);
  338. return;
  339. }
  340. copy_from_unchecked(p_cstr, len);
  341. }
  342. void String::copy_from(const char32_t *p_cstr, const int p_clip_to) {
  343. if (!p_cstr) {
  344. resize(0);
  345. return;
  346. }
  347. int len = 0;
  348. const char32_t *ptr = p_cstr;
  349. while ((p_clip_to < 0 || len < p_clip_to) && *(ptr++) != 0) {
  350. len++;
  351. }
  352. if (len == 0) {
  353. resize(0);
  354. return;
  355. }
  356. copy_from_unchecked(p_cstr, len);
  357. }
  358. // assumes the following have already been validated:
  359. // p_char != nullptr
  360. // p_length > 0
  361. // p_length <= p_char strlen
  362. void String::copy_from_unchecked(const char32_t *p_char, const int p_length) {
  363. resize(p_length + 1);
  364. char32_t *dst = ptrw();
  365. dst[p_length] = 0;
  366. for (int i = 0; i < p_length; i++) {
  367. if ((p_char[i] >= 0xd800 && p_char[i] <= 0xdfff) || (p_char[i] > 0x10ffff)) {
  368. print_error("Unicode parsing error: Invalid unicode codepoint " + num_int64(p_char[i], 16) + ".");
  369. dst[i] = 0xfffd;
  370. } else {
  371. dst[i] = p_char[i];
  372. }
  373. }
  374. }
  375. void String::operator=(const char *p_str) {
  376. copy_from(p_str);
  377. }
  378. void String::operator=(const char32_t *p_str) {
  379. copy_from(p_str);
  380. }
  381. void String::operator=(const wchar_t *p_str) {
  382. copy_from(p_str);
  383. }
  384. String String::operator+(const String &p_str) const {
  385. String res = *this;
  386. res += p_str;
  387. return res;
  388. }
  389. String String::operator+(char32_t p_char) const {
  390. String res = *this;
  391. res += p_char;
  392. return res;
  393. }
  394. String operator+(const char *p_chr, const String &p_str) {
  395. String tmp = p_chr;
  396. tmp += p_str;
  397. return tmp;
  398. }
  399. String operator+(const wchar_t *p_chr, const String &p_str) {
  400. #ifdef WINDOWS_ENABLED
  401. // wchar_t is 16-bit
  402. String tmp = String::utf16((const char16_t *)p_chr);
  403. #else
  404. // wchar_t is 32-bi
  405. String tmp = (const char32_t *)p_chr;
  406. #endif
  407. tmp += p_str;
  408. return tmp;
  409. }
  410. String operator+(char32_t p_chr, const String &p_str) {
  411. return (String::chr(p_chr) + p_str);
  412. }
  413. String &String::operator+=(const String &p_str) {
  414. const int lhs_len = length();
  415. if (lhs_len == 0) {
  416. *this = p_str;
  417. return *this;
  418. }
  419. const int rhs_len = p_str.length();
  420. if (rhs_len == 0) {
  421. return *this;
  422. }
  423. resize(lhs_len + rhs_len + 1);
  424. const char32_t *src = p_str.get_data();
  425. char32_t *dst = ptrw() + lhs_len;
  426. memcpy(dst, src, (rhs_len + 1) * sizeof(char32_t));
  427. return *this;
  428. }
  429. String &String::operator+=(const char *p_str) {
  430. if (!p_str || p_str[0] == 0) {
  431. return *this;
  432. }
  433. const int lhs_len = length();
  434. const size_t rhs_len = strlen(p_str);
  435. resize(lhs_len + rhs_len + 1);
  436. char32_t *dst = ptrw() + lhs_len;
  437. for (size_t i = 0; i <= rhs_len; i++) {
  438. dst[i] = p_str[i];
  439. }
  440. return *this;
  441. }
  442. String &String::operator+=(const wchar_t *p_str) {
  443. #ifdef WINDOWS_ENABLED
  444. // wchar_t is 16-bit
  445. *this += String::utf16((const char16_t *)p_str);
  446. #else
  447. // wchar_t is 32-bit
  448. *this += String((const char32_t *)p_str);
  449. #endif
  450. return *this;
  451. }
  452. String &String::operator+=(const char32_t *p_str) {
  453. *this += String(p_str);
  454. return *this;
  455. }
  456. String &String::operator+=(char32_t p_char) {
  457. const int lhs_len = length();
  458. resize(lhs_len + 2);
  459. char32_t *dst = ptrw();
  460. if ((p_char >= 0xd800 && p_char <= 0xdfff) || (p_char > 0x10ffff)) {
  461. print_error("Unicode parsing error: Invalid unicode codepoint " + num_int64(p_char, 16) + ".");
  462. dst[lhs_len] = 0xfffd;
  463. } else {
  464. dst[lhs_len] = p_char;
  465. }
  466. dst[lhs_len + 1] = 0;
  467. return *this;
  468. }
  469. bool String::operator==(const char *p_str) const {
  470. // compare Latin-1 encoded c-string
  471. int len = 0;
  472. const char *aux = p_str;
  473. while (*(aux++) != 0) {
  474. len++;
  475. }
  476. if (length() != len) {
  477. return false;
  478. }
  479. if (is_empty()) {
  480. return true;
  481. }
  482. int l = length();
  483. const char32_t *dst = get_data();
  484. // Compare char by char
  485. for (int i = 0; i < l; i++) {
  486. if ((char32_t)p_str[i] != dst[i]) {
  487. return false;
  488. }
  489. }
  490. return true;
  491. }
  492. bool String::operator==(const wchar_t *p_str) const {
  493. #ifdef WINDOWS_ENABLED
  494. // wchar_t is 16-bit, parse as UTF-16
  495. return *this == String::utf16((const char16_t *)p_str);
  496. #else
  497. // wchar_t is 32-bit, compare char by char
  498. return *this == (const char32_t *)p_str;
  499. #endif
  500. }
  501. bool String::operator==(const char32_t *p_str) const {
  502. int len = 0;
  503. const char32_t *aux = p_str;
  504. while (*(aux++) != 0) {
  505. len++;
  506. }
  507. if (length() != len) {
  508. return false;
  509. }
  510. if (is_empty()) {
  511. return true;
  512. }
  513. int l = length();
  514. const char32_t *dst = get_data();
  515. /* Compare char by char */
  516. for (int i = 0; i < l; i++) {
  517. if (p_str[i] != dst[i]) {
  518. return false;
  519. }
  520. }
  521. return true;
  522. }
  523. bool String::operator==(const String &p_str) const {
  524. if (length() != p_str.length()) {
  525. return false;
  526. }
  527. if (is_empty()) {
  528. return true;
  529. }
  530. int l = length();
  531. const char32_t *src = get_data();
  532. const char32_t *dst = p_str.get_data();
  533. /* Compare char by char */
  534. for (int i = 0; i < l; i++) {
  535. if (src[i] != dst[i]) {
  536. return false;
  537. }
  538. }
  539. return true;
  540. }
  541. bool String::operator==(const StrRange &p_str_range) const {
  542. int len = p_str_range.len;
  543. if (length() != len) {
  544. return false;
  545. }
  546. if (is_empty()) {
  547. return true;
  548. }
  549. const char32_t *c_str = p_str_range.c_str;
  550. const char32_t *dst = &operator[](0);
  551. /* Compare char by char */
  552. for (int i = 0; i < len; i++) {
  553. if (c_str[i] != dst[i]) {
  554. return false;
  555. }
  556. }
  557. return true;
  558. }
  559. bool operator==(const char *p_chr, const String &p_str) {
  560. return p_str == p_chr;
  561. }
  562. bool operator==(const wchar_t *p_chr, const String &p_str) {
  563. #ifdef WINDOWS_ENABLED
  564. // wchar_t is 16-bit
  565. return p_str == String::utf16((const char16_t *)p_chr);
  566. #else
  567. // wchar_t is 32-bi
  568. return p_str == String((const char32_t *)p_chr);
  569. #endif
  570. }
  571. bool operator!=(const char *p_chr, const String &p_str) {
  572. return !(p_str == p_chr);
  573. }
  574. bool operator!=(const wchar_t *p_chr, const String &p_str) {
  575. #ifdef WINDOWS_ENABLED
  576. // wchar_t is 16-bit
  577. return !(p_str == String::utf16((const char16_t *)p_chr));
  578. #else
  579. // wchar_t is 32-bi
  580. return !(p_str == String((const char32_t *)p_chr));
  581. #endif
  582. }
  583. bool String::operator!=(const char *p_str) const {
  584. return (!(*this == p_str));
  585. }
  586. bool String::operator!=(const wchar_t *p_str) const {
  587. return (!(*this == p_str));
  588. }
  589. bool String::operator!=(const char32_t *p_str) const {
  590. return (!(*this == p_str));
  591. }
  592. bool String::operator!=(const String &p_str) const {
  593. return !((*this == p_str));
  594. }
  595. bool String::operator<=(const String &p_str) const {
  596. return !(p_str < *this);
  597. }
  598. bool String::operator>(const String &p_str) const {
  599. return p_str < *this;
  600. }
  601. bool String::operator>=(const String &p_str) const {
  602. return !(*this < p_str);
  603. }
  604. bool String::operator<(const char *p_str) const {
  605. if (is_empty() && p_str[0] == 0) {
  606. return false;
  607. }
  608. if (is_empty()) {
  609. return true;
  610. }
  611. return is_str_less(get_data(), p_str);
  612. }
  613. bool String::operator<(const wchar_t *p_str) const {
  614. if (is_empty() && p_str[0] == 0) {
  615. return false;
  616. }
  617. if (is_empty()) {
  618. return true;
  619. }
  620. #ifdef WINDOWS_ENABLED
  621. // wchar_t is 16-bit
  622. return is_str_less(get_data(), String::utf16((const char16_t *)p_str).get_data());
  623. #else
  624. // wchar_t is 32-bit
  625. return is_str_less(get_data(), (const char32_t *)p_str);
  626. #endif
  627. }
  628. bool String::operator<(const char32_t *p_str) const {
  629. if (is_empty() && p_str[0] == 0) {
  630. return false;
  631. }
  632. if (is_empty()) {
  633. return true;
  634. }
  635. return is_str_less(get_data(), p_str);
  636. }
  637. bool String::operator<(const String &p_str) const {
  638. return operator<(p_str.get_data());
  639. }
  640. signed char String::nocasecmp_to(const String &p_str) const {
  641. if (is_empty() && p_str.is_empty()) {
  642. return 0;
  643. }
  644. if (is_empty()) {
  645. return -1;
  646. }
  647. if (p_str.is_empty()) {
  648. return 1;
  649. }
  650. const char32_t *that_str = p_str.get_data();
  651. const char32_t *this_str = get_data();
  652. while (true) {
  653. if (*that_str == 0 && *this_str == 0) {
  654. return 0; //we're equal
  655. } else if (*this_str == 0) {
  656. return -1; //if this is empty, and the other one is not, then we're less.. I think?
  657. } else if (*that_str == 0) {
  658. return 1; //otherwise the other one is smaller..
  659. } else if (_find_upper(*this_str) < _find_upper(*that_str)) { //more than
  660. return -1;
  661. } else if (_find_upper(*this_str) > _find_upper(*that_str)) { //less than
  662. return 1;
  663. }
  664. this_str++;
  665. that_str++;
  666. }
  667. }
  668. signed char String::casecmp_to(const String &p_str) const {
  669. if (is_empty() && p_str.is_empty()) {
  670. return 0;
  671. }
  672. if (is_empty()) {
  673. return -1;
  674. }
  675. if (p_str.is_empty()) {
  676. return 1;
  677. }
  678. const char32_t *that_str = p_str.get_data();
  679. const char32_t *this_str = get_data();
  680. while (true) {
  681. if (*that_str == 0 && *this_str == 0) {
  682. return 0; //we're equal
  683. } else if (*this_str == 0) {
  684. return -1; //if this is empty, and the other one is not, then we're less.. I think?
  685. } else if (*that_str == 0) {
  686. return 1; //otherwise the other one is smaller..
  687. } else if (*this_str < *that_str) { //more than
  688. return -1;
  689. } else if (*this_str > *that_str) { //less than
  690. return 1;
  691. }
  692. this_str++;
  693. that_str++;
  694. }
  695. }
  696. signed char String::naturalnocasecmp_to(const String &p_str) const {
  697. const char32_t *this_str = get_data();
  698. const char32_t *that_str = p_str.get_data();
  699. if (this_str && that_str) {
  700. while (*this_str == '.' || *that_str == '.') {
  701. if (*this_str++ != '.') {
  702. return 1;
  703. }
  704. if (*that_str++ != '.') {
  705. return -1;
  706. }
  707. if (!*that_str) {
  708. return 1;
  709. }
  710. if (!*this_str) {
  711. return -1;
  712. }
  713. }
  714. while (*this_str) {
  715. if (!*that_str) {
  716. return 1;
  717. } else if (is_digit(*this_str)) {
  718. if (!is_digit(*that_str)) {
  719. return -1;
  720. }
  721. // Keep ptrs to start of numerical sequences
  722. const char32_t *this_substr = this_str;
  723. const char32_t *that_substr = that_str;
  724. // Compare lengths of both numerical sequences, ignoring leading zeros
  725. while (is_digit(*this_str)) {
  726. this_str++;
  727. }
  728. while (is_digit(*that_str)) {
  729. that_str++;
  730. }
  731. while (*this_substr == '0') {
  732. this_substr++;
  733. }
  734. while (*that_substr == '0') {
  735. that_substr++;
  736. }
  737. int this_len = this_str - this_substr;
  738. int that_len = that_str - that_substr;
  739. if (this_len < that_len) {
  740. return -1;
  741. } else if (this_len > that_len) {
  742. return 1;
  743. }
  744. // If lengths equal, compare lexicographically
  745. while (this_substr != this_str && that_substr != that_str) {
  746. if (*this_substr < *that_substr) {
  747. return -1;
  748. } else if (*this_substr > *that_substr) {
  749. return 1;
  750. }
  751. this_substr++;
  752. that_substr++;
  753. }
  754. } else if (is_digit(*that_str)) {
  755. return 1;
  756. } else {
  757. if (_find_upper(*this_str) < _find_upper(*that_str)) { //more than
  758. return -1;
  759. } else if (_find_upper(*this_str) > _find_upper(*that_str)) { //less than
  760. return 1;
  761. }
  762. this_str++;
  763. that_str++;
  764. }
  765. }
  766. if (*that_str) {
  767. return -1;
  768. }
  769. }
  770. return 0;
  771. }
  772. const char32_t *String::get_data() const {
  773. static const char32_t zero = 0;
  774. return size() ? &operator[](0) : &zero;
  775. }
  776. String String::capitalize() const {
  777. String aux = this->camelcase_to_underscore(true).replace("_", " ").strip_edges();
  778. String cap;
  779. for (int i = 0; i < aux.get_slice_count(" "); i++) {
  780. String slice = aux.get_slicec(' ', i);
  781. if (slice.length() > 0) {
  782. slice[0] = _find_upper(slice[0]);
  783. if (i > 0) {
  784. cap += " ";
  785. }
  786. cap += slice;
  787. }
  788. }
  789. return cap;
  790. }
  791. String String::camelcase_to_underscore(bool lowercase) const {
  792. const char32_t *cstr = get_data();
  793. String new_string;
  794. int start_index = 0;
  795. for (int i = 1; i < this->size(); i++) {
  796. bool is_upper = is_ascii_upper_case(cstr[i]);
  797. bool is_number = is_digit(cstr[i]);
  798. bool are_next_2_lower = false;
  799. bool is_next_lower = false;
  800. bool is_next_number = false;
  801. bool was_precedent_upper = is_ascii_upper_case(cstr[i - 1]);
  802. bool was_precedent_number = is_digit(cstr[i - 1]);
  803. if (i + 2 < this->size()) {
  804. are_next_2_lower = is_ascii_lower_case(cstr[i + 1]) && is_ascii_lower_case(cstr[i + 2]);
  805. }
  806. if (i + 1 < this->size()) {
  807. is_next_lower = is_ascii_lower_case(cstr[i + 1]);
  808. is_next_number = is_digit(cstr[i + 1]);
  809. }
  810. const bool cond_a = is_upper && !was_precedent_upper && !was_precedent_number;
  811. const bool cond_b = was_precedent_upper && is_upper && are_next_2_lower;
  812. const bool cond_c = is_number && !was_precedent_number;
  813. const bool can_break_number_letter = is_number && !was_precedent_number && is_next_lower;
  814. const bool can_break_letter_number = !is_number && was_precedent_number && (is_next_lower || is_next_number);
  815. bool should_split = cond_a || cond_b || cond_c || can_break_number_letter || can_break_letter_number;
  816. if (should_split) {
  817. new_string += this->substr(start_index, i - start_index) + "_";
  818. start_index = i;
  819. }
  820. }
  821. new_string += this->substr(start_index, this->size() - start_index);
  822. return lowercase ? new_string.to_lower() : new_string;
  823. }
  824. String String::get_with_code_lines() const {
  825. const Vector<String> lines = split("\n");
  826. String ret;
  827. for (int i = 0; i < lines.size(); i++) {
  828. if (i > 0) {
  829. ret += "\n";
  830. }
  831. ret += vformat("%4d | %s", i + 1, lines[i]);
  832. }
  833. return ret;
  834. }
  835. int String::get_slice_count(String p_splitter) const {
  836. if (is_empty()) {
  837. return 0;
  838. }
  839. if (p_splitter.is_empty()) {
  840. return 0;
  841. }
  842. int pos = 0;
  843. int slices = 1;
  844. while ((pos = find(p_splitter, pos)) >= 0) {
  845. slices++;
  846. pos += p_splitter.length();
  847. }
  848. return slices;
  849. }
  850. String String::get_slice(String p_splitter, int p_slice) const {
  851. if (is_empty() || p_splitter.is_empty()) {
  852. return "";
  853. }
  854. int pos = 0;
  855. int prev_pos = 0;
  856. //int slices=1;
  857. if (p_slice < 0) {
  858. return "";
  859. }
  860. if (find(p_splitter) == -1) {
  861. return *this;
  862. }
  863. int i = 0;
  864. while (true) {
  865. pos = find(p_splitter, pos);
  866. if (pos == -1) {
  867. pos = length(); //reached end
  868. }
  869. int from = prev_pos;
  870. //int to=pos;
  871. if (p_slice == i) {
  872. return substr(from, pos - from);
  873. }
  874. if (pos == length()) { //reached end and no find
  875. break;
  876. }
  877. pos += p_splitter.length();
  878. prev_pos = pos;
  879. i++;
  880. }
  881. return ""; //no find!
  882. }
  883. String String::get_slicec(char32_t p_splitter, int p_slice) const {
  884. if (is_empty()) {
  885. return String();
  886. }
  887. if (p_slice < 0) {
  888. return String();
  889. }
  890. const char32_t *c = this->ptr();
  891. int i = 0;
  892. int prev = 0;
  893. int count = 0;
  894. while (true) {
  895. if (c[i] == 0 || c[i] == p_splitter) {
  896. if (p_slice == count) {
  897. return substr(prev, i - prev);
  898. } else if (c[i] == 0) {
  899. return String();
  900. } else {
  901. count++;
  902. prev = i + 1;
  903. }
  904. }
  905. i++;
  906. }
  907. }
  908. Vector<String> String::split_spaces() const {
  909. Vector<String> ret;
  910. int from = 0;
  911. int i = 0;
  912. int len = length();
  913. if (len == 0) {
  914. return ret;
  915. }
  916. bool inside = false;
  917. while (true) {
  918. bool empty = operator[](i) < 33;
  919. if (i == 0) {
  920. inside = !empty;
  921. }
  922. if (!empty && !inside) {
  923. inside = true;
  924. from = i;
  925. }
  926. if (empty && inside) {
  927. ret.push_back(substr(from, i - from));
  928. inside = false;
  929. }
  930. if (i == len) {
  931. break;
  932. }
  933. i++;
  934. }
  935. return ret;
  936. }
  937. Vector<String> String::split(const String &p_splitter, bool p_allow_empty, int p_maxsplit) const {
  938. Vector<String> ret;
  939. int from = 0;
  940. int len = length();
  941. while (true) {
  942. int end = find(p_splitter, from);
  943. if (end < 0) {
  944. end = len;
  945. }
  946. if (p_allow_empty || (end > from)) {
  947. if (p_maxsplit <= 0) {
  948. ret.push_back(substr(from, end - from));
  949. } else {
  950. // Put rest of the string and leave cycle.
  951. if (p_maxsplit == ret.size()) {
  952. ret.push_back(substr(from, len));
  953. break;
  954. }
  955. // Otherwise, push items until positive limit is reached.
  956. ret.push_back(substr(from, end - from));
  957. }
  958. }
  959. if (end == len) {
  960. break;
  961. }
  962. from = end + p_splitter.length();
  963. }
  964. return ret;
  965. }
  966. Vector<String> String::rsplit(const String &p_splitter, bool p_allow_empty, int p_maxsplit) const {
  967. Vector<String> ret;
  968. const int len = length();
  969. int remaining_len = len;
  970. while (true) {
  971. if (remaining_len < p_splitter.length() || (p_maxsplit > 0 && p_maxsplit == ret.size())) {
  972. // no room for another splitter or hit max splits, push what's left and we're done
  973. if (p_allow_empty || remaining_len > 0) {
  974. ret.push_back(substr(0, remaining_len));
  975. }
  976. break;
  977. }
  978. int left_edge = rfind(p_splitter, remaining_len - p_splitter.length());
  979. if (left_edge < 0) {
  980. // no more splitters, we're done
  981. ret.push_back(substr(0, remaining_len));
  982. break;
  983. }
  984. int substr_start = left_edge + p_splitter.length();
  985. if (p_allow_empty || substr_start < remaining_len) {
  986. ret.push_back(substr(substr_start, remaining_len - substr_start));
  987. }
  988. remaining_len = left_edge;
  989. }
  990. ret.reverse();
  991. return ret;
  992. }
  993. Vector<float> String::split_floats(const String &p_splitter, bool p_allow_empty) const {
  994. Vector<float> ret;
  995. int from = 0;
  996. int len = length();
  997. while (true) {
  998. int end = find(p_splitter, from);
  999. if (end < 0) {
  1000. end = len;
  1001. }
  1002. if (p_allow_empty || (end > from)) {
  1003. ret.push_back(String::to_float(&get_data()[from]));
  1004. }
  1005. if (end == len) {
  1006. break;
  1007. }
  1008. from = end + p_splitter.length();
  1009. }
  1010. return ret;
  1011. }
  1012. Vector<float> String::split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
  1013. Vector<float> ret;
  1014. int from = 0;
  1015. int len = length();
  1016. while (true) {
  1017. int idx;
  1018. int end = findmk(p_splitters, from, &idx);
  1019. int spl_len = 1;
  1020. if (end < 0) {
  1021. end = len;
  1022. } else {
  1023. spl_len = p_splitters[idx].length();
  1024. }
  1025. if (p_allow_empty || (end > from)) {
  1026. ret.push_back(String::to_float(&get_data()[from]));
  1027. }
  1028. if (end == len) {
  1029. break;
  1030. }
  1031. from = end + spl_len;
  1032. }
  1033. return ret;
  1034. }
  1035. Vector<int> String::split_ints(const String &p_splitter, bool p_allow_empty) const {
  1036. Vector<int> ret;
  1037. int from = 0;
  1038. int len = length();
  1039. while (true) {
  1040. int end = find(p_splitter, from);
  1041. if (end < 0) {
  1042. end = len;
  1043. }
  1044. if (p_allow_empty || (end > from)) {
  1045. ret.push_back(String::to_int(&get_data()[from], end - from));
  1046. }
  1047. if (end == len) {
  1048. break;
  1049. }
  1050. from = end + p_splitter.length();
  1051. }
  1052. return ret;
  1053. }
  1054. Vector<int> String::split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
  1055. Vector<int> ret;
  1056. int from = 0;
  1057. int len = length();
  1058. while (true) {
  1059. int idx;
  1060. int end = findmk(p_splitters, from, &idx);
  1061. int spl_len = 1;
  1062. if (end < 0) {
  1063. end = len;
  1064. } else {
  1065. spl_len = p_splitters[idx].length();
  1066. }
  1067. if (p_allow_empty || (end > from)) {
  1068. ret.push_back(String::to_int(&get_data()[from], end - from));
  1069. }
  1070. if (end == len) {
  1071. break;
  1072. }
  1073. from = end + spl_len;
  1074. }
  1075. return ret;
  1076. }
  1077. String String::join(Vector<String> parts) const {
  1078. String ret;
  1079. for (int i = 0; i < parts.size(); ++i) {
  1080. if (i > 0) {
  1081. ret += *this;
  1082. }
  1083. ret += parts[i];
  1084. }
  1085. return ret;
  1086. }
  1087. char32_t String::char_uppercase(char32_t p_char) {
  1088. return _find_upper(p_char);
  1089. }
  1090. char32_t String::char_lowercase(char32_t p_char) {
  1091. return _find_lower(p_char);
  1092. }
  1093. String String::to_upper() const {
  1094. String upper = *this;
  1095. for (int i = 0; i < upper.size(); i++) {
  1096. const char32_t s = upper[i];
  1097. const char32_t t = _find_upper(s);
  1098. if (s != t) { // avoid copy on write
  1099. upper[i] = t;
  1100. }
  1101. }
  1102. return upper;
  1103. }
  1104. String String::to_lower() const {
  1105. String lower = *this;
  1106. for (int i = 0; i < lower.size(); i++) {
  1107. const char32_t s = lower[i];
  1108. const char32_t t = _find_lower(s);
  1109. if (s != t) { // avoid copy on write
  1110. lower[i] = t;
  1111. }
  1112. }
  1113. return lower;
  1114. }
  1115. String String::chr(char32_t p_char) {
  1116. char32_t c[2] = { p_char, 0 };
  1117. return String(c);
  1118. }
  1119. String String::num(double p_num, int p_decimals) {
  1120. if (Math::is_nan(p_num)) {
  1121. return "nan";
  1122. }
  1123. if (Math::is_inf(p_num)) {
  1124. if (signbit(p_num)) {
  1125. return "-inf";
  1126. } else {
  1127. return "inf";
  1128. }
  1129. }
  1130. if (p_decimals < 0) {
  1131. p_decimals = 14;
  1132. const double abs_num = ABS(p_num);
  1133. if (abs_num > 10) {
  1134. // We want to align the digits to the above sane default, so we only
  1135. // need to subtract log10 for numbers with a positive power of ten.
  1136. p_decimals -= (int)floor(log10(abs_num));
  1137. }
  1138. }
  1139. if (p_decimals > MAX_DECIMALS) {
  1140. p_decimals = MAX_DECIMALS;
  1141. }
  1142. char fmt[7];
  1143. fmt[0] = '%';
  1144. fmt[1] = '.';
  1145. if (p_decimals < 0) {
  1146. fmt[1] = 'l';
  1147. fmt[2] = 'f';
  1148. fmt[3] = 0;
  1149. } else if (p_decimals < 10) {
  1150. fmt[2] = '0' + p_decimals;
  1151. fmt[3] = 'l';
  1152. fmt[4] = 'f';
  1153. fmt[5] = 0;
  1154. } else {
  1155. fmt[2] = '0' + (p_decimals / 10);
  1156. fmt[3] = '0' + (p_decimals % 10);
  1157. fmt[4] = 'l';
  1158. fmt[5] = 'f';
  1159. fmt[6] = 0;
  1160. }
  1161. char buf[256];
  1162. #if defined(__GNUC__) || defined(_MSC_VER)
  1163. snprintf(buf, 256, fmt, p_num);
  1164. #else
  1165. sprintf(buf, fmt, p_num);
  1166. #endif
  1167. buf[255] = 0;
  1168. //destroy trailing zeroes
  1169. {
  1170. bool period = false;
  1171. int z = 0;
  1172. while (buf[z]) {
  1173. if (buf[z] == '.') {
  1174. period = true;
  1175. }
  1176. z++;
  1177. }
  1178. if (period) {
  1179. z--;
  1180. while (z > 0) {
  1181. if (buf[z] == '0') {
  1182. buf[z] = 0;
  1183. } else if (buf[z] == '.') {
  1184. buf[z] = 0;
  1185. break;
  1186. } else {
  1187. break;
  1188. }
  1189. z--;
  1190. }
  1191. }
  1192. }
  1193. return buf;
  1194. }
  1195. String String::num_int64(int64_t p_num, int base, bool capitalize_hex) {
  1196. bool sign = p_num < 0;
  1197. int64_t n = p_num;
  1198. int chars = 0;
  1199. do {
  1200. n /= base;
  1201. chars++;
  1202. } while (n);
  1203. if (sign) {
  1204. chars++;
  1205. }
  1206. String s;
  1207. s.resize(chars + 1);
  1208. char32_t *c = s.ptrw();
  1209. c[chars] = 0;
  1210. n = p_num;
  1211. do {
  1212. int mod = ABS(n % base);
  1213. if (mod >= 10) {
  1214. char a = (capitalize_hex ? 'A' : 'a');
  1215. c[--chars] = a + (mod - 10);
  1216. } else {
  1217. c[--chars] = '0' + mod;
  1218. }
  1219. n /= base;
  1220. } while (n);
  1221. if (sign) {
  1222. c[0] = '-';
  1223. }
  1224. return s;
  1225. }
  1226. String String::num_uint64(uint64_t p_num, int base, bool capitalize_hex) {
  1227. uint64_t n = p_num;
  1228. int chars = 0;
  1229. do {
  1230. n /= base;
  1231. chars++;
  1232. } while (n);
  1233. String s;
  1234. s.resize(chars + 1);
  1235. char32_t *c = s.ptrw();
  1236. c[chars] = 0;
  1237. n = p_num;
  1238. do {
  1239. int mod = n % base;
  1240. if (mod >= 10) {
  1241. char a = (capitalize_hex ? 'A' : 'a');
  1242. c[--chars] = a + (mod - 10);
  1243. } else {
  1244. c[--chars] = '0' + mod;
  1245. }
  1246. n /= base;
  1247. } while (n);
  1248. return s;
  1249. }
  1250. String String::num_real(double p_num, bool p_trailing) {
  1251. if (p_num == (double)(int64_t)p_num) {
  1252. if (p_trailing) {
  1253. return num_int64((int64_t)p_num) + ".0";
  1254. } else {
  1255. return num_int64((int64_t)p_num);
  1256. }
  1257. }
  1258. #ifdef REAL_T_IS_DOUBLE
  1259. int decimals = 14;
  1260. #else
  1261. int decimals = 6;
  1262. #endif
  1263. // We want to align the digits to the above sane default, so we only
  1264. // need to subtract log10 for numbers with a positive power of ten.
  1265. if (p_num > 10) {
  1266. decimals -= (int)floor(log10(p_num));
  1267. }
  1268. return num(p_num, decimals);
  1269. }
  1270. String String::num_scientific(double p_num) {
  1271. if (Math::is_nan(p_num)) {
  1272. return "nan";
  1273. }
  1274. if (Math::is_inf(p_num)) {
  1275. if (signbit(p_num)) {
  1276. return "-inf";
  1277. } else {
  1278. return "inf";
  1279. }
  1280. }
  1281. char buf[256];
  1282. #if defined(__GNUC__) || defined(_MSC_VER)
  1283. #if defined(__MINGW32__) && defined(_TWO_DIGIT_EXPONENT) && !defined(_UCRT)
  1284. // MinGW requires _set_output_format() to conform to C99 output for printf
  1285. unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
  1286. #endif
  1287. snprintf(buf, 256, "%lg", p_num);
  1288. #if defined(__MINGW32__) && defined(_TWO_DIGIT_EXPONENT) && !defined(_UCRT)
  1289. _set_output_format(old_exponent_format);
  1290. #endif
  1291. #else
  1292. sprintf(buf, "%.16lg", p_num);
  1293. #endif
  1294. buf[255] = 0;
  1295. return buf;
  1296. }
  1297. String String::md5(const uint8_t *p_md5) {
  1298. return String::hex_encode_buffer(p_md5, 16);
  1299. }
  1300. String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
  1301. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  1302. String ret;
  1303. char v[2] = { 0, 0 };
  1304. for (int i = 0; i < p_len; i++) {
  1305. v[0] = hex[p_buffer[i] >> 4];
  1306. ret += v;
  1307. v[0] = hex[p_buffer[i] & 0xF];
  1308. ret += v;
  1309. }
  1310. return ret;
  1311. }
  1312. CharString String::ascii(bool p_allow_extended) const {
  1313. if (!length()) {
  1314. return CharString();
  1315. }
  1316. CharString cs;
  1317. cs.resize(size());
  1318. for (int i = 0; i < size(); i++) {
  1319. char32_t c = operator[](i);
  1320. if ((c <= 0x7f) || (c <= 0xff && p_allow_extended)) {
  1321. cs[i] = c;
  1322. } else {
  1323. print_error("Unicode parsing error: Cannot represent " + num_int64(c, 16) + " as ASCII/Latin-1 character.");
  1324. cs[i] = 0x20;
  1325. }
  1326. }
  1327. return cs;
  1328. }
  1329. String String::utf8(const char *p_utf8, int p_len) {
  1330. String ret;
  1331. ret.parse_utf8(p_utf8, p_len);
  1332. return ret;
  1333. }
  1334. bool String::parse_utf8(const char *p_utf8, int p_len) {
  1335. #define UNICERROR(m_err) print_error("Unicode parsing error: " + String(m_err) + ". Is the string valid UTF-8?");
  1336. if (!p_utf8) {
  1337. return true;
  1338. }
  1339. String aux;
  1340. int cstr_size = 0;
  1341. int str_size = 0;
  1342. /* HANDLE BOM (Byte Order Mark) */
  1343. if (p_len < 0 || p_len >= 3) {
  1344. bool has_bom = uint8_t(p_utf8[0]) == 0xef && uint8_t(p_utf8[1]) == 0xbb && uint8_t(p_utf8[2]) == 0xbf;
  1345. if (has_bom) {
  1346. //8-bit encoding, byte order has no meaning in UTF-8, just skip it
  1347. if (p_len >= 0) {
  1348. p_len -= 3;
  1349. }
  1350. p_utf8 += 3;
  1351. }
  1352. }
  1353. {
  1354. const char *ptrtmp = p_utf8;
  1355. const char *ptrtmp_limit = &p_utf8[p_len];
  1356. int skip = 0;
  1357. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  1358. if (skip == 0) {
  1359. uint8_t c = *ptrtmp >= 0 ? *ptrtmp : uint8_t(256 + *ptrtmp);
  1360. /* Determine the number of characters in sequence */
  1361. if ((c & 0x80) == 0) {
  1362. skip = 0;
  1363. } else if ((c & 0xe0) == 0xc0) {
  1364. skip = 1;
  1365. } else if ((c & 0xf0) == 0xe0) {
  1366. skip = 2;
  1367. } else if ((c & 0xf8) == 0xf0) {
  1368. skip = 3;
  1369. } else {
  1370. UNICERROR("invalid skip at " + num_int64(cstr_size));
  1371. return true; //invalid utf8
  1372. }
  1373. if (skip == 1 && (c & 0x1e) == 0) {
  1374. UNICERROR("overlong rejected at " + num_int64(cstr_size));
  1375. return true; //reject overlong
  1376. }
  1377. str_size++;
  1378. } else {
  1379. --skip;
  1380. }
  1381. cstr_size++;
  1382. ptrtmp++;
  1383. }
  1384. if (skip) {
  1385. UNICERROR("no space left");
  1386. return true; //not enough space
  1387. }
  1388. }
  1389. if (str_size == 0) {
  1390. clear();
  1391. return false;
  1392. }
  1393. resize(str_size + 1);
  1394. char32_t *dst = ptrw();
  1395. dst[str_size] = 0;
  1396. while (cstr_size) {
  1397. int len = 0;
  1398. /* Determine the number of characters in sequence */
  1399. if ((*p_utf8 & 0x80) == 0) {
  1400. len = 1;
  1401. } else if ((*p_utf8 & 0xe0) == 0xc0) {
  1402. len = 2;
  1403. } else if ((*p_utf8 & 0xf0) == 0xe0) {
  1404. len = 3;
  1405. } else if ((*p_utf8 & 0xf8) == 0xf0) {
  1406. len = 4;
  1407. } else {
  1408. UNICERROR("invalid len");
  1409. return true; //invalid UTF8
  1410. }
  1411. if (len > cstr_size) {
  1412. UNICERROR("no space left");
  1413. return true; //not enough space
  1414. }
  1415. if (len == 2 && (*p_utf8 & 0x1E) == 0) {
  1416. UNICERROR("no space left");
  1417. return true; //reject overlong
  1418. }
  1419. /* Convert the first character */
  1420. uint32_t unichar = 0;
  1421. if (len == 1) {
  1422. unichar = *p_utf8;
  1423. } else {
  1424. unichar = (0xff >> (len + 1)) & *p_utf8;
  1425. for (int i = 1; i < len; i++) {
  1426. if ((p_utf8[i] & 0xc0) != 0x80) {
  1427. UNICERROR("invalid utf8");
  1428. return true; //invalid utf8
  1429. }
  1430. if (unichar == 0 && i == 2 && ((p_utf8[i] & 0x7f) >> (7 - len)) == 0) {
  1431. UNICERROR("invalid utf8 overlong");
  1432. return true; //no overlong
  1433. }
  1434. unichar = (unichar << 6) | (p_utf8[i] & 0x3f);
  1435. }
  1436. }
  1437. if (unichar >= 0xd800 && unichar <= 0xdfff) {
  1438. UNICERROR("invalid code point");
  1439. return CharString();
  1440. }
  1441. *(dst++) = unichar;
  1442. cstr_size -= len;
  1443. p_utf8 += len;
  1444. }
  1445. return false;
  1446. #undef UNICERROR
  1447. }
  1448. CharString String::utf8() const {
  1449. int l = length();
  1450. if (!l) {
  1451. return CharString();
  1452. }
  1453. const char32_t *d = &operator[](0);
  1454. int fl = 0;
  1455. for (int i = 0; i < l; i++) {
  1456. uint32_t c = d[i];
  1457. if (c <= 0x7f) { // 7 bits.
  1458. fl += 1;
  1459. } else if (c <= 0x7ff) { // 11 bits
  1460. fl += 2;
  1461. } else if (c <= 0xffff) { // 16 bits
  1462. fl += 3;
  1463. } else if (c <= 0x0010ffff) { // 21 bits
  1464. fl += 4;
  1465. } else {
  1466. print_error("Unicode parsing error: Invalid unicode codepoint " + num_int64(c, 16) + ".");
  1467. return CharString();
  1468. }
  1469. if (c >= 0xd800 && c <= 0xdfff) {
  1470. print_error("Unicode parsing error: Invalid unicode codepoint " + num_int64(c, 16) + ".");
  1471. return CharString();
  1472. }
  1473. }
  1474. CharString utf8s;
  1475. if (fl == 0) {
  1476. return utf8s;
  1477. }
  1478. utf8s.resize(fl + 1);
  1479. uint8_t *cdst = (uint8_t *)utf8s.get_data();
  1480. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1481. for (int i = 0; i < l; i++) {
  1482. uint32_t c = d[i];
  1483. if (c <= 0x7f) { // 7 bits.
  1484. APPEND_CHAR(c);
  1485. } else if (c <= 0x7ff) { // 11 bits
  1486. APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits.
  1487. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1488. } else if (c <= 0xffff) { // 16 bits
  1489. APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits.
  1490. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits.
  1491. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1492. } else { // 21 bits
  1493. APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits.
  1494. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits.
  1495. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1496. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1497. }
  1498. }
  1499. #undef APPEND_CHAR
  1500. *cdst = 0; //trailing zero
  1501. return utf8s;
  1502. }
  1503. String String::utf16(const char16_t *p_utf16, int p_len) {
  1504. String ret;
  1505. ret.parse_utf16(p_utf16, p_len);
  1506. return ret;
  1507. }
  1508. bool String::parse_utf16(const char16_t *p_utf16, int p_len) {
  1509. #define UNICERROR(m_err) print_error("Unicode parsing error: " + String(m_err) + ". Is the string valid UTF-16?");
  1510. if (!p_utf16) {
  1511. return true;
  1512. }
  1513. String aux;
  1514. int cstr_size = 0;
  1515. int str_size = 0;
  1516. /* HANDLE BOM (Byte Order Mark) */
  1517. bool byteswap = false; // assume correct endianness if no BOM found
  1518. if (p_len < 0 || p_len >= 1) {
  1519. bool has_bom = false;
  1520. if (uint16_t(p_utf16[0]) == 0xfeff) { // correct BOM, read as is
  1521. has_bom = true;
  1522. byteswap = false;
  1523. } else if (uint16_t(p_utf16[0]) == 0xfffe) { // backwards BOM, swap bytes
  1524. has_bom = true;
  1525. byteswap = true;
  1526. }
  1527. if (has_bom) {
  1528. if (p_len >= 0) {
  1529. p_len -= 1;
  1530. }
  1531. p_utf16 += 1;
  1532. }
  1533. }
  1534. {
  1535. const char16_t *ptrtmp = p_utf16;
  1536. const char16_t *ptrtmp_limit = &p_utf16[p_len];
  1537. int skip = 0;
  1538. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  1539. uint32_t c = (byteswap) ? BSWAP16(*ptrtmp) : *ptrtmp;
  1540. if (skip == 0) {
  1541. if ((c & 0xfffffc00) == 0xd800) {
  1542. skip = 1; // lead surrogate
  1543. } else if ((c & 0xfffffc00) == 0xdc00) {
  1544. UNICERROR("invalid utf16 surrogate at " + num_int64(cstr_size));
  1545. return true; // invalid UTF16
  1546. } else {
  1547. skip = 0;
  1548. }
  1549. str_size++;
  1550. } else {
  1551. if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
  1552. --skip;
  1553. } else {
  1554. UNICERROR("invalid utf16 surrogate at " + num_int64(cstr_size));
  1555. return true; // invalid UTF16
  1556. }
  1557. }
  1558. cstr_size++;
  1559. ptrtmp++;
  1560. }
  1561. if (skip) {
  1562. UNICERROR("no space left");
  1563. return true; // not enough space
  1564. }
  1565. }
  1566. if (str_size == 0) {
  1567. clear();
  1568. return false;
  1569. }
  1570. resize(str_size + 1);
  1571. char32_t *dst = ptrw();
  1572. dst[str_size] = 0;
  1573. while (cstr_size) {
  1574. int len = 0;
  1575. uint32_t c = (byteswap) ? BSWAP16(*p_utf16) : *p_utf16;
  1576. if ((c & 0xfffffc00) == 0xd800) {
  1577. len = 2;
  1578. } else {
  1579. len = 1;
  1580. }
  1581. if (len > cstr_size) {
  1582. UNICERROR("no space left");
  1583. return true; //not enough space
  1584. }
  1585. uint32_t unichar = 0;
  1586. if (len == 1) {
  1587. unichar = c;
  1588. } else {
  1589. uint32_t c2 = (byteswap) ? BSWAP16(p_utf16[1]) : p_utf16[1];
  1590. unichar = (c << 10UL) + c2 - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  1591. }
  1592. *(dst++) = unichar;
  1593. cstr_size -= len;
  1594. p_utf16 += len;
  1595. }
  1596. return false;
  1597. #undef UNICERROR
  1598. }
  1599. Char16String String::utf16() const {
  1600. int l = length();
  1601. if (!l) {
  1602. return Char16String();
  1603. }
  1604. const char32_t *d = &operator[](0);
  1605. int fl = 0;
  1606. for (int i = 0; i < l; i++) {
  1607. uint32_t c = d[i];
  1608. if (c <= 0xffff) { // 16 bits.
  1609. fl += 1;
  1610. } else if (c <= 0x10ffff) { // 32 bits.
  1611. fl += 2;
  1612. } else {
  1613. print_error("Unicode parsing error: Invalid unicode codepoint " + num_int64(c, 16) + ".");
  1614. return Char16String();
  1615. }
  1616. if (c >= 0xd800 && c <= 0xdfff) {
  1617. print_error("Unicode parsing error: Invalid unicode codepoint " + num_int64(c, 16) + ".");
  1618. return Char16String();
  1619. }
  1620. }
  1621. Char16String utf16s;
  1622. if (fl == 0) {
  1623. return utf16s;
  1624. }
  1625. utf16s.resize(fl + 1);
  1626. uint16_t *cdst = (uint16_t *)utf16s.get_data();
  1627. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1628. for (int i = 0; i < l; i++) {
  1629. uint32_t c = d[i];
  1630. if (c <= 0xffff) { // 16 bits.
  1631. APPEND_CHAR(c);
  1632. } else { // 32 bits.
  1633. APPEND_CHAR(uint32_t((c >> 10) + 0xd7c0)); // lead surrogate.
  1634. APPEND_CHAR(uint32_t((c & 0x3ff) | 0xdc00)); // trail surrogate.
  1635. }
  1636. }
  1637. #undef APPEND_CHAR
  1638. *cdst = 0; //trailing zero
  1639. return utf16s;
  1640. }
  1641. String::String(const char *p_str) {
  1642. copy_from(p_str);
  1643. }
  1644. String::String(const wchar_t *p_str) {
  1645. copy_from(p_str);
  1646. }
  1647. String::String(const char32_t *p_str) {
  1648. copy_from(p_str);
  1649. }
  1650. String::String(const char *p_str, int p_clip_to_len) {
  1651. copy_from(p_str, p_clip_to_len);
  1652. }
  1653. String::String(const wchar_t *p_str, int p_clip_to_len) {
  1654. copy_from(p_str, p_clip_to_len);
  1655. }
  1656. String::String(const char32_t *p_str, int p_clip_to_len) {
  1657. copy_from(p_str, p_clip_to_len);
  1658. }
  1659. String::String(const StrRange &p_range) {
  1660. if (!p_range.c_str) {
  1661. return;
  1662. }
  1663. copy_from(p_range.c_str, p_range.len);
  1664. }
  1665. int64_t String::hex_to_int() const {
  1666. int len = length();
  1667. if (len == 0) {
  1668. return 0;
  1669. }
  1670. const char32_t *s = ptr();
  1671. int64_t sign = s[0] == '-' ? -1 : 1;
  1672. if (sign < 0) {
  1673. s++;
  1674. }
  1675. if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'x') {
  1676. s += 2;
  1677. }
  1678. int64_t hex = 0;
  1679. while (*s) {
  1680. char32_t c = lower_case(*s);
  1681. int64_t n;
  1682. if (is_digit(c)) {
  1683. n = c - '0';
  1684. } else if (c >= 'a' && c <= 'f') {
  1685. n = (c - 'a') + 10;
  1686. } else {
  1687. ERR_FAIL_COND_V_MSG(true, 0, "Invalid hexadecimal notation character \"" + chr(*s) + "\" in string \"" + *this + "\".");
  1688. }
  1689. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  1690. bool overflow = ((hex > INT64_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT64_MAX >> 4) + 1))) || (sign == -1 && hex == (INT64_MAX >> 4) + 1 && c > '0');
  1691. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as 64-bit integer, provided value is " + (sign == 1 ? "too big." : "too small."));
  1692. hex *= 16;
  1693. hex += n;
  1694. s++;
  1695. }
  1696. return hex * sign;
  1697. }
  1698. int64_t String::bin_to_int() const {
  1699. int len = length();
  1700. if (len == 0) {
  1701. return 0;
  1702. }
  1703. const char32_t *s = ptr();
  1704. int64_t sign = s[0] == '-' ? -1 : 1;
  1705. if (sign < 0) {
  1706. s++;
  1707. }
  1708. if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'b') {
  1709. s += 2;
  1710. }
  1711. int64_t binary = 0;
  1712. while (*s) {
  1713. char32_t c = lower_case(*s);
  1714. int64_t n;
  1715. if (c == '0' || c == '1') {
  1716. n = c - '0';
  1717. } else {
  1718. return 0;
  1719. }
  1720. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  1721. bool overflow = ((binary > INT64_MAX / 2) && (sign == 1 || (sign == -1 && binary != (INT64_MAX >> 1) + 1))) || (sign == -1 && binary == (INT64_MAX >> 1) + 1 && c > '0');
  1722. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as 64-bit integer, provided value is " + (sign == 1 ? "too big." : "too small."));
  1723. binary *= 2;
  1724. binary += n;
  1725. s++;
  1726. }
  1727. return binary * sign;
  1728. }
  1729. int64_t String::to_int() const {
  1730. if (length() == 0) {
  1731. return 0;
  1732. }
  1733. int to = (find(".") >= 0) ? find(".") : length();
  1734. int64_t integer = 0;
  1735. int64_t sign = 1;
  1736. for (int i = 0; i < to; i++) {
  1737. char32_t c = operator[](i);
  1738. if (is_digit(c)) {
  1739. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  1740. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as 64-bit integer, provided value is " + (sign == 1 ? "too big." : "too small."));
  1741. integer *= 10;
  1742. integer += c - '0';
  1743. } else if (integer == 0 && c == '-') {
  1744. sign = -sign;
  1745. }
  1746. }
  1747. return integer * sign;
  1748. }
  1749. int64_t String::to_int(const char *p_str, int p_len) {
  1750. int to = 0;
  1751. if (p_len >= 0) {
  1752. to = p_len;
  1753. } else {
  1754. while (p_str[to] != 0 && p_str[to] != '.') {
  1755. to++;
  1756. }
  1757. }
  1758. int64_t integer = 0;
  1759. int64_t sign = 1;
  1760. for (int i = 0; i < to; i++) {
  1761. char c = p_str[i];
  1762. if (is_digit(c)) {
  1763. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  1764. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + String(p_str).substr(0, to) + " as integer, provided value is " + (sign == 1 ? "too big." : "too small."));
  1765. integer *= 10;
  1766. integer += c - '0';
  1767. } else if (c == '-' && integer == 0) {
  1768. sign = -sign;
  1769. } else if (c != ' ') {
  1770. break;
  1771. }
  1772. }
  1773. return integer * sign;
  1774. }
  1775. int64_t String::to_int(const wchar_t *p_str, int p_len) {
  1776. int to = 0;
  1777. if (p_len >= 0) {
  1778. to = p_len;
  1779. } else {
  1780. while (p_str[to] != 0 && p_str[to] != '.') {
  1781. to++;
  1782. }
  1783. }
  1784. int64_t integer = 0;
  1785. int64_t sign = 1;
  1786. for (int i = 0; i < to; i++) {
  1787. wchar_t c = p_str[i];
  1788. if (is_digit(c)) {
  1789. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  1790. ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + String(p_str).substr(0, to) + " as integer, provided value is " + (sign == 1 ? "too big." : "too small."));
  1791. integer *= 10;
  1792. integer += c - '0';
  1793. } else if (c == '-' && integer == 0) {
  1794. sign = -sign;
  1795. } else if (c != ' ') {
  1796. break;
  1797. }
  1798. }
  1799. return integer * sign;
  1800. }
  1801. bool String::is_numeric() const {
  1802. if (length() == 0) {
  1803. return false;
  1804. }
  1805. int s = 0;
  1806. if (operator[](0) == '-') {
  1807. ++s;
  1808. }
  1809. bool dot = false;
  1810. for (int i = s; i < length(); i++) {
  1811. char32_t c = operator[](i);
  1812. if (c == '.') {
  1813. if (dot) {
  1814. return false;
  1815. }
  1816. dot = true;
  1817. } else if (!is_digit(c)) {
  1818. return false;
  1819. }
  1820. }
  1821. return true; // TODO: Use the parser below for this instead
  1822. }
  1823. template <class C>
  1824. static double built_in_strtod(
  1825. /* A decimal ASCII floating-point number,
  1826. * optionally preceded by white space. Must
  1827. * have form "-I.FE-X", where I is the integer
  1828. * part of the mantissa, F is the fractional
  1829. * part of the mantissa, and X is the
  1830. * exponent. Either of the signs may be "+",
  1831. * "-", or omitted. Either I or F may be
  1832. * omitted, or both. The decimal point isn't
  1833. * necessary unless F is present. The "E" may
  1834. * actually be an "e". E and X may both be
  1835. * omitted (but not just one). */
  1836. const C *string,
  1837. /* If non-nullptr, store terminating Cacter's
  1838. * address here. */
  1839. C **endPtr = nullptr) {
  1840. /* Largest possible base 10 exponent. Any
  1841. * exponent larger than this will already
  1842. * produce underflow or overflow, so there's
  1843. * no need to worry about additional digits. */
  1844. static const int maxExponent = 511;
  1845. /* Table giving binary powers of 10. Entry
  1846. * is 10^2^i. Used to convert decimal
  1847. * exponents into floating-point numbers. */
  1848. static const double powersOf10[] = {
  1849. 10.,
  1850. 100.,
  1851. 1.0e4,
  1852. 1.0e8,
  1853. 1.0e16,
  1854. 1.0e32,
  1855. 1.0e64,
  1856. 1.0e128,
  1857. 1.0e256
  1858. };
  1859. bool sign, expSign = false;
  1860. double fraction, dblExp;
  1861. const double *d;
  1862. const C *p;
  1863. int c;
  1864. /* Exponent read from "EX" field. */
  1865. int exp = 0;
  1866. /* Exponent that derives from the fractional
  1867. * part. Under normal circumstances, it is
  1868. * the negative of the number of digits in F.
  1869. * However, if I is very long, the last digits
  1870. * of I get dropped (otherwise a long I with a
  1871. * large negative exponent could cause an
  1872. * unnecessary overflow on I alone). In this
  1873. * case, fracExp is incremented one for each
  1874. * dropped digit. */
  1875. int fracExp = 0;
  1876. /* Number of digits in mantissa. */
  1877. int mantSize;
  1878. /* Number of mantissa digits BEFORE decimal point. */
  1879. int decPt;
  1880. /* Temporarily holds location of exponent in string. */
  1881. const C *pExp;
  1882. /*
  1883. * Strip off leading blanks and check for a sign.
  1884. */
  1885. p = string;
  1886. while (*p == ' ' || *p == '\t' || *p == '\n') {
  1887. p += 1;
  1888. }
  1889. if (*p == '-') {
  1890. sign = true;
  1891. p += 1;
  1892. } else {
  1893. if (*p == '+') {
  1894. p += 1;
  1895. }
  1896. sign = false;
  1897. }
  1898. /*
  1899. * Count the number of digits in the mantissa (including the decimal
  1900. * point), and also locate the decimal point.
  1901. */
  1902. decPt = -1;
  1903. for (mantSize = 0;; mantSize += 1) {
  1904. c = *p;
  1905. if (!is_digit(c)) {
  1906. if ((c != '.') || (decPt >= 0)) {
  1907. break;
  1908. }
  1909. decPt = mantSize;
  1910. }
  1911. p += 1;
  1912. }
  1913. /*
  1914. * Now suck up the digits in the mantissa. Use two integers to collect 9
  1915. * digits each (this is faster than using floating-point). If the mantissa
  1916. * has more than 18 digits, ignore the extras, since they can't affect the
  1917. * value anyway.
  1918. */
  1919. pExp = p;
  1920. p -= mantSize;
  1921. if (decPt < 0) {
  1922. decPt = mantSize;
  1923. } else {
  1924. mantSize -= 1; /* One of the digits was the point. */
  1925. }
  1926. if (mantSize > 18) {
  1927. fracExp = decPt - 18;
  1928. mantSize = 18;
  1929. } else {
  1930. fracExp = decPt - mantSize;
  1931. }
  1932. if (mantSize == 0) {
  1933. fraction = 0.0;
  1934. p = string;
  1935. goto done;
  1936. } else {
  1937. int frac1, frac2;
  1938. frac1 = 0;
  1939. for (; mantSize > 9; mantSize -= 1) {
  1940. c = *p;
  1941. p += 1;
  1942. if (c == '.') {
  1943. c = *p;
  1944. p += 1;
  1945. }
  1946. frac1 = 10 * frac1 + (c - '0');
  1947. }
  1948. frac2 = 0;
  1949. for (; mantSize > 0; mantSize -= 1) {
  1950. c = *p;
  1951. p += 1;
  1952. if (c == '.') {
  1953. c = *p;
  1954. p += 1;
  1955. }
  1956. frac2 = 10 * frac2 + (c - '0');
  1957. }
  1958. fraction = (1.0e9 * frac1) + frac2;
  1959. }
  1960. /*
  1961. * Skim off the exponent.
  1962. */
  1963. p = pExp;
  1964. if ((*p == 'E') || (*p == 'e')) {
  1965. p += 1;
  1966. if (*p == '-') {
  1967. expSign = true;
  1968. p += 1;
  1969. } else {
  1970. if (*p == '+') {
  1971. p += 1;
  1972. }
  1973. expSign = false;
  1974. }
  1975. if (!is_digit(char32_t(*p))) {
  1976. p = pExp;
  1977. goto done;
  1978. }
  1979. while (is_digit(char32_t(*p))) {
  1980. exp = exp * 10 + (*p - '0');
  1981. p += 1;
  1982. }
  1983. }
  1984. if (expSign) {
  1985. exp = fracExp - exp;
  1986. } else {
  1987. exp = fracExp + exp;
  1988. }
  1989. /*
  1990. * Generate a floating-point number that represents the exponent. Do this
  1991. * by processing the exponent one bit at a time to combine many powers of
  1992. * 2 of 10. Then combine the exponent with the fraction.
  1993. */
  1994. if (exp < 0) {
  1995. expSign = true;
  1996. exp = -exp;
  1997. } else {
  1998. expSign = false;
  1999. }
  2000. if (exp > maxExponent) {
  2001. exp = maxExponent;
  2002. WARN_PRINT("Exponent too high");
  2003. }
  2004. dblExp = 1.0;
  2005. for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
  2006. if (exp & 01) {
  2007. dblExp *= *d;
  2008. }
  2009. }
  2010. if (expSign) {
  2011. fraction /= dblExp;
  2012. } else {
  2013. fraction *= dblExp;
  2014. }
  2015. done:
  2016. if (endPtr != nullptr) {
  2017. *endPtr = (C *)p;
  2018. }
  2019. if (sign) {
  2020. return -fraction;
  2021. }
  2022. return fraction;
  2023. }
  2024. #define READING_SIGN 0
  2025. #define READING_INT 1
  2026. #define READING_DEC 2
  2027. #define READING_EXP 3
  2028. #define READING_DONE 4
  2029. double String::to_float(const char *p_str) {
  2030. return built_in_strtod<char>(p_str);
  2031. }
  2032. double String::to_float(const char32_t *p_str, const char32_t **r_end) {
  2033. return built_in_strtod<char32_t>(p_str, (char32_t **)r_end);
  2034. }
  2035. double String::to_float(const wchar_t *p_str, const wchar_t **r_end) {
  2036. return built_in_strtod<wchar_t>(p_str, (wchar_t **)r_end);
  2037. }
  2038. int64_t String::to_int(const char32_t *p_str, int p_len, bool p_clamp) {
  2039. if (p_len == 0 || !p_str[0]) {
  2040. return 0;
  2041. }
  2042. ///@todo make more exact so saving and loading does not lose precision
  2043. int64_t integer = 0;
  2044. int64_t sign = 1;
  2045. int reading = READING_SIGN;
  2046. const char32_t *str = p_str;
  2047. const char32_t *limit = &p_str[p_len];
  2048. while (*str && reading != READING_DONE && str != limit) {
  2049. char32_t c = *(str++);
  2050. switch (reading) {
  2051. case READING_SIGN: {
  2052. if (is_digit(c)) {
  2053. reading = READING_INT;
  2054. // let it fallthrough
  2055. } else if (c == '-') {
  2056. sign = -1;
  2057. reading = READING_INT;
  2058. break;
  2059. } else if (c == '+') {
  2060. sign = 1;
  2061. reading = READING_INT;
  2062. break;
  2063. } else {
  2064. break;
  2065. }
  2066. [[fallthrough]];
  2067. }
  2068. case READING_INT: {
  2069. if (is_digit(c)) {
  2070. if (integer > INT64_MAX / 10) {
  2071. String number("");
  2072. str = p_str;
  2073. while (*str && str != limit) {
  2074. number += *(str++);
  2075. }
  2076. if (p_clamp) {
  2077. if (sign == 1) {
  2078. return INT64_MAX;
  2079. } else {
  2080. return INT64_MIN;
  2081. }
  2082. } else {
  2083. ERR_FAIL_V_MSG(sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + number + " as integer, provided value is " + (sign == 1 ? "too big." : "too small."));
  2084. }
  2085. }
  2086. integer *= 10;
  2087. integer += c - '0';
  2088. } else {
  2089. reading = READING_DONE;
  2090. }
  2091. } break;
  2092. }
  2093. }
  2094. return sign * integer;
  2095. }
  2096. double String::to_float() const {
  2097. if (is_empty()) {
  2098. return 0;
  2099. }
  2100. return built_in_strtod<char32_t>(get_data());
  2101. }
  2102. uint32_t String::hash(const char *p_cstr) {
  2103. uint32_t hashv = 5381;
  2104. uint32_t c;
  2105. while ((c = *p_cstr++)) {
  2106. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2107. }
  2108. return hashv;
  2109. }
  2110. uint32_t String::hash(const char *p_cstr, int p_len) {
  2111. uint32_t hashv = 5381;
  2112. for (int i = 0; i < p_len; i++) {
  2113. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  2114. }
  2115. return hashv;
  2116. }
  2117. uint32_t String::hash(const wchar_t *p_cstr, int p_len) {
  2118. uint32_t hashv = 5381;
  2119. for (int i = 0; i < p_len; i++) {
  2120. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  2121. }
  2122. return hashv;
  2123. }
  2124. uint32_t String::hash(const wchar_t *p_cstr) {
  2125. uint32_t hashv = 5381;
  2126. uint32_t c;
  2127. while ((c = *p_cstr++)) {
  2128. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2129. }
  2130. return hashv;
  2131. }
  2132. uint32_t String::hash(const char32_t *p_cstr, int p_len) {
  2133. uint32_t hashv = 5381;
  2134. for (int i = 0; i < p_len; i++) {
  2135. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  2136. }
  2137. return hashv;
  2138. }
  2139. uint32_t String::hash(const char32_t *p_cstr) {
  2140. uint32_t hashv = 5381;
  2141. uint32_t c;
  2142. while ((c = *p_cstr++)) {
  2143. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2144. }
  2145. return hashv;
  2146. }
  2147. uint32_t String::hash() const {
  2148. /* simple djb2 hashing */
  2149. const char32_t *chr = get_data();
  2150. uint32_t hashv = 5381;
  2151. uint32_t c;
  2152. while ((c = *chr++)) {
  2153. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2154. }
  2155. return hashv;
  2156. }
  2157. uint64_t String::hash64() const {
  2158. /* simple djb2 hashing */
  2159. const char32_t *chr = get_data();
  2160. uint64_t hashv = 5381;
  2161. uint64_t c;
  2162. while ((c = *chr++)) {
  2163. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2164. }
  2165. return hashv;
  2166. }
  2167. String String::md5_text() const {
  2168. CharString cs = utf8();
  2169. unsigned char hash[16];
  2170. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  2171. return String::hex_encode_buffer(hash, 16);
  2172. }
  2173. String String::sha1_text() const {
  2174. CharString cs = utf8();
  2175. unsigned char hash[20];
  2176. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  2177. return String::hex_encode_buffer(hash, 20);
  2178. }
  2179. String String::sha256_text() const {
  2180. CharString cs = utf8();
  2181. unsigned char hash[32];
  2182. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  2183. return String::hex_encode_buffer(hash, 32);
  2184. }
  2185. Vector<uint8_t> String::md5_buffer() const {
  2186. CharString cs = utf8();
  2187. unsigned char hash[16];
  2188. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  2189. Vector<uint8_t> ret;
  2190. ret.resize(16);
  2191. for (int i = 0; i < 16; i++) {
  2192. ret.write[i] = hash[i];
  2193. }
  2194. return ret;
  2195. }
  2196. Vector<uint8_t> String::sha1_buffer() const {
  2197. CharString cs = utf8();
  2198. unsigned char hash[20];
  2199. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  2200. Vector<uint8_t> ret;
  2201. ret.resize(20);
  2202. for (int i = 0; i < 20; i++) {
  2203. ret.write[i] = hash[i];
  2204. }
  2205. return ret;
  2206. }
  2207. Vector<uint8_t> String::sha256_buffer() const {
  2208. CharString cs = utf8();
  2209. unsigned char hash[32];
  2210. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  2211. Vector<uint8_t> ret;
  2212. ret.resize(32);
  2213. for (int i = 0; i < 32; i++) {
  2214. ret.write[i] = hash[i];
  2215. }
  2216. return ret;
  2217. }
  2218. String String::insert(int p_at_pos, const String &p_string) const {
  2219. if (p_at_pos < 0) {
  2220. return *this;
  2221. }
  2222. if (p_at_pos > length()) {
  2223. p_at_pos = length();
  2224. }
  2225. String pre;
  2226. if (p_at_pos > 0) {
  2227. pre = substr(0, p_at_pos);
  2228. }
  2229. String post;
  2230. if (p_at_pos < length()) {
  2231. post = substr(p_at_pos, length() - p_at_pos);
  2232. }
  2233. return pre + p_string + post;
  2234. }
  2235. String String::substr(int p_from, int p_chars) const {
  2236. if (p_chars == -1) {
  2237. p_chars = length() - p_from;
  2238. }
  2239. if (is_empty() || p_from < 0 || p_from >= length() || p_chars <= 0) {
  2240. return "";
  2241. }
  2242. if ((p_from + p_chars) > length()) {
  2243. p_chars = length() - p_from;
  2244. }
  2245. if (p_from == 0 && p_chars >= length()) {
  2246. return String(*this);
  2247. }
  2248. String s = String();
  2249. s.copy_from_unchecked(&get_data()[p_from], p_chars);
  2250. return s;
  2251. }
  2252. int String::find(const String &p_str, int p_from) const {
  2253. if (p_from < 0) {
  2254. return -1;
  2255. }
  2256. const int src_len = p_str.length();
  2257. const int len = length();
  2258. if (src_len == 0 || len == 0) {
  2259. return -1; // won't find anything!
  2260. }
  2261. const char32_t *src = get_data();
  2262. const char32_t *str = p_str.get_data();
  2263. for (int i = p_from; i <= (len - src_len); i++) {
  2264. bool found = true;
  2265. for (int j = 0; j < src_len; j++) {
  2266. int read_pos = i + j;
  2267. if (read_pos >= len) {
  2268. ERR_PRINT("read_pos>=len");
  2269. return -1;
  2270. }
  2271. if (src[read_pos] != str[j]) {
  2272. found = false;
  2273. break;
  2274. }
  2275. }
  2276. if (found) {
  2277. return i;
  2278. }
  2279. }
  2280. return -1;
  2281. }
  2282. int String::find(const char *p_str, int p_from) const {
  2283. if (p_from < 0) {
  2284. return -1;
  2285. }
  2286. const int len = length();
  2287. if (len == 0) {
  2288. return -1; // won't find anything!
  2289. }
  2290. const char32_t *src = get_data();
  2291. int src_len = 0;
  2292. while (p_str[src_len] != '\0') {
  2293. src_len++;
  2294. }
  2295. if (src_len == 1) {
  2296. const char32_t needle = p_str[0];
  2297. for (int i = p_from; i < len; i++) {
  2298. if (src[i] == needle) {
  2299. return i;
  2300. }
  2301. }
  2302. } else {
  2303. for (int i = p_from; i <= (len - src_len); i++) {
  2304. bool found = true;
  2305. for (int j = 0; j < src_len; j++) {
  2306. int read_pos = i + j;
  2307. if (read_pos >= len) {
  2308. ERR_PRINT("read_pos>=len");
  2309. return -1;
  2310. }
  2311. if (src[read_pos] != (char32_t)p_str[j]) {
  2312. found = false;
  2313. break;
  2314. }
  2315. }
  2316. if (found) {
  2317. return i;
  2318. }
  2319. }
  2320. }
  2321. return -1;
  2322. }
  2323. int String::find_char(const char32_t &p_char, int p_from) const {
  2324. return _cowdata.find(p_char, p_from);
  2325. }
  2326. int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
  2327. if (p_from < 0) {
  2328. return -1;
  2329. }
  2330. if (p_keys.size() == 0) {
  2331. return -1;
  2332. }
  2333. //int src_len=p_str.length();
  2334. const String *keys = &p_keys[0];
  2335. int key_count = p_keys.size();
  2336. int len = length();
  2337. if (len == 0) {
  2338. return -1; // won't find anything!
  2339. }
  2340. const char32_t *src = get_data();
  2341. for (int i = p_from; i < len; i++) {
  2342. bool found = true;
  2343. for (int k = 0; k < key_count; k++) {
  2344. found = true;
  2345. if (r_key) {
  2346. *r_key = k;
  2347. }
  2348. const char32_t *cmp = keys[k].get_data();
  2349. int l = keys[k].length();
  2350. for (int j = 0; j < l; j++) {
  2351. int read_pos = i + j;
  2352. if (read_pos >= len) {
  2353. found = false;
  2354. break;
  2355. }
  2356. if (src[read_pos] != cmp[j]) {
  2357. found = false;
  2358. break;
  2359. }
  2360. }
  2361. if (found) {
  2362. break;
  2363. }
  2364. }
  2365. if (found) {
  2366. return i;
  2367. }
  2368. }
  2369. return -1;
  2370. }
  2371. int String::findn(const String &p_str, int p_from) const {
  2372. if (p_from < 0) {
  2373. return -1;
  2374. }
  2375. int src_len = p_str.length();
  2376. if (src_len == 0 || length() == 0) {
  2377. return -1; // won't find anything!
  2378. }
  2379. const char32_t *srcd = get_data();
  2380. for (int i = p_from; i <= (length() - src_len); i++) {
  2381. bool found = true;
  2382. for (int j = 0; j < src_len; j++) {
  2383. int read_pos = i + j;
  2384. if (read_pos >= length()) {
  2385. ERR_PRINT("read_pos>=length()");
  2386. return -1;
  2387. }
  2388. char32_t src = _find_lower(srcd[read_pos]);
  2389. char32_t dst = _find_lower(p_str[j]);
  2390. if (src != dst) {
  2391. found = false;
  2392. break;
  2393. }
  2394. }
  2395. if (found) {
  2396. return i;
  2397. }
  2398. }
  2399. return -1;
  2400. }
  2401. int String::rfind(const String &p_str, int p_from) const {
  2402. // establish a limit
  2403. int limit = length() - p_str.length();
  2404. if (limit < 0) {
  2405. return -1;
  2406. }
  2407. // establish a starting point
  2408. if (p_from < 0) {
  2409. p_from = limit;
  2410. } else if (p_from > limit) {
  2411. p_from = limit;
  2412. }
  2413. int src_len = p_str.length();
  2414. int len = length();
  2415. if (src_len == 0 || len == 0) {
  2416. return -1; // won't find anything!
  2417. }
  2418. const char32_t *src = get_data();
  2419. for (int i = p_from; i >= 0; i--) {
  2420. bool found = true;
  2421. for (int j = 0; j < src_len; j++) {
  2422. int read_pos = i + j;
  2423. if (read_pos >= len) {
  2424. ERR_PRINT("read_pos>=len");
  2425. return -1;
  2426. }
  2427. if (src[read_pos] != p_str[j]) {
  2428. found = false;
  2429. break;
  2430. }
  2431. }
  2432. if (found) {
  2433. return i;
  2434. }
  2435. }
  2436. return -1;
  2437. }
  2438. int String::rfindn(const String &p_str, int p_from) const {
  2439. // establish a limit
  2440. int limit = length() - p_str.length();
  2441. if (limit < 0) {
  2442. return -1;
  2443. }
  2444. // establish a starting point
  2445. if (p_from < 0) {
  2446. p_from = limit;
  2447. } else if (p_from > limit) {
  2448. p_from = limit;
  2449. }
  2450. int src_len = p_str.length();
  2451. int len = length();
  2452. if (src_len == 0 || len == 0) {
  2453. return -1; // won't find anything!
  2454. }
  2455. const char32_t *src = get_data();
  2456. for (int i = p_from; i >= 0; i--) {
  2457. bool found = true;
  2458. for (int j = 0; j < src_len; j++) {
  2459. int read_pos = i + j;
  2460. if (read_pos >= len) {
  2461. ERR_PRINT("read_pos>=len");
  2462. return -1;
  2463. }
  2464. char32_t srcc = _find_lower(src[read_pos]);
  2465. char32_t dstc = _find_lower(p_str[j]);
  2466. if (srcc != dstc) {
  2467. found = false;
  2468. break;
  2469. }
  2470. }
  2471. if (found) {
  2472. return i;
  2473. }
  2474. }
  2475. return -1;
  2476. }
  2477. bool String::ends_with(const String &p_string) const {
  2478. int l = p_string.length();
  2479. if (l > length()) {
  2480. return false;
  2481. }
  2482. if (l == 0) {
  2483. return true;
  2484. }
  2485. const char32_t *p = &p_string[0];
  2486. const char32_t *s = &operator[](length() - l);
  2487. for (int i = 0; i < l; i++) {
  2488. if (p[i] != s[i]) {
  2489. return false;
  2490. }
  2491. }
  2492. return true;
  2493. }
  2494. bool String::begins_with(const String &p_string) const {
  2495. int l = p_string.length();
  2496. if (l > length()) {
  2497. return false;
  2498. }
  2499. if (l == 0) {
  2500. return true;
  2501. }
  2502. const char32_t *p = &p_string[0];
  2503. const char32_t *s = &operator[](0);
  2504. for (int i = 0; i < l; i++) {
  2505. if (p[i] != s[i]) {
  2506. return false;
  2507. }
  2508. }
  2509. return true;
  2510. }
  2511. bool String::begins_with(const char *p_string) const {
  2512. int l = length();
  2513. if (l == 0 || !p_string) {
  2514. return false;
  2515. }
  2516. const char32_t *str = &operator[](0);
  2517. int i = 0;
  2518. while (*p_string && i < l) {
  2519. if ((char32_t)*p_string != str[i]) {
  2520. return false;
  2521. }
  2522. i++;
  2523. p_string++;
  2524. }
  2525. return *p_string == 0;
  2526. }
  2527. bool String::is_enclosed_in(const String &p_string) const {
  2528. return begins_with(p_string) && ends_with(p_string);
  2529. }
  2530. bool String::is_subsequence_of(const String &p_string) const {
  2531. return _base_is_subsequence_of(p_string, false);
  2532. }
  2533. bool String::is_subsequence_ofn(const String &p_string) const {
  2534. return _base_is_subsequence_of(p_string, true);
  2535. }
  2536. bool String::is_quoted() const {
  2537. return is_enclosed_in("\"") || is_enclosed_in("'");
  2538. }
  2539. int String::_count(const String &p_string, int p_from, int p_to, bool p_case_insensitive) const {
  2540. if (p_string.is_empty()) {
  2541. return 0;
  2542. }
  2543. int len = length();
  2544. int slen = p_string.length();
  2545. if (len < slen) {
  2546. return 0;
  2547. }
  2548. String str;
  2549. if (p_from >= 0 && p_to >= 0) {
  2550. if (p_to == 0) {
  2551. p_to = len;
  2552. } else if (p_from >= p_to) {
  2553. return 0;
  2554. }
  2555. if (p_from == 0 && p_to == len) {
  2556. str = String();
  2557. str.copy_from_unchecked(&get_data()[0], len);
  2558. } else {
  2559. str = substr(p_from, p_to - p_from);
  2560. }
  2561. } else {
  2562. return 0;
  2563. }
  2564. int c = 0;
  2565. int idx = -1;
  2566. do {
  2567. idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
  2568. if (idx != -1) {
  2569. str = str.substr(idx + slen, str.length() - slen);
  2570. ++c;
  2571. }
  2572. } while (idx != -1);
  2573. return c;
  2574. }
  2575. int String::count(const String &p_string, int p_from, int p_to) const {
  2576. return _count(p_string, p_from, p_to, false);
  2577. }
  2578. int String::countn(const String &p_string, int p_from, int p_to) const {
  2579. return _count(p_string, p_from, p_to, true);
  2580. }
  2581. bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const {
  2582. int len = length();
  2583. if (len == 0) {
  2584. // Technically an empty string is subsequence of any string
  2585. return true;
  2586. }
  2587. if (len > p_string.length()) {
  2588. return false;
  2589. }
  2590. const char32_t *src = &operator[](0);
  2591. const char32_t *tgt = &p_string[0];
  2592. for (; *src && *tgt; tgt++) {
  2593. bool match = false;
  2594. if (case_insensitive) {
  2595. char32_t srcc = _find_lower(*src);
  2596. char32_t tgtc = _find_lower(*tgt);
  2597. match = srcc == tgtc;
  2598. } else {
  2599. match = *src == *tgt;
  2600. }
  2601. if (match) {
  2602. src++;
  2603. if (!*src) {
  2604. return true;
  2605. }
  2606. }
  2607. }
  2608. return false;
  2609. }
  2610. Vector<String> String::bigrams() const {
  2611. int n_pairs = length() - 1;
  2612. Vector<String> b;
  2613. if (n_pairs <= 0) {
  2614. return b;
  2615. }
  2616. b.resize(n_pairs);
  2617. for (int i = 0; i < n_pairs; i++) {
  2618. b.write[i] = substr(i, 2);
  2619. }
  2620. return b;
  2621. }
  2622. // Similarity according to Sorensen-Dice coefficient
  2623. float String::similarity(const String &p_string) const {
  2624. if (operator==(p_string)) {
  2625. // Equal strings are totally similar
  2626. return 1.0f;
  2627. }
  2628. if (length() < 2 || p_string.length() < 2) {
  2629. // No way to calculate similarity without a single bigram
  2630. return 0.0f;
  2631. }
  2632. Vector<String> src_bigrams = bigrams();
  2633. Vector<String> tgt_bigrams = p_string.bigrams();
  2634. int src_size = src_bigrams.size();
  2635. int tgt_size = tgt_bigrams.size();
  2636. int sum = src_size + tgt_size;
  2637. int inter = 0;
  2638. for (int i = 0; i < src_size; i++) {
  2639. for (int j = 0; j < tgt_size; j++) {
  2640. if (src_bigrams[i] == tgt_bigrams[j]) {
  2641. inter++;
  2642. break;
  2643. }
  2644. }
  2645. }
  2646. return (2.0f * inter) / sum;
  2647. }
  2648. static bool _wildcard_match(const char32_t *p_pattern, const char32_t *p_string, bool p_case_sensitive) {
  2649. switch (*p_pattern) {
  2650. case '\0':
  2651. return !*p_string;
  2652. case '*':
  2653. return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive));
  2654. case '?':
  2655. return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
  2656. default:
  2657. return (p_case_sensitive ? (*p_string == *p_pattern) : (_find_upper(*p_string) == _find_upper(*p_pattern))) && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
  2658. }
  2659. }
  2660. bool String::match(const String &p_wildcard) const {
  2661. if (!p_wildcard.length() || !length()) {
  2662. return false;
  2663. }
  2664. return _wildcard_match(p_wildcard.get_data(), get_data(), true);
  2665. }
  2666. bool String::matchn(const String &p_wildcard) const {
  2667. if (!p_wildcard.length() || !length()) {
  2668. return false;
  2669. }
  2670. return _wildcard_match(p_wildcard.get_data(), get_data(), false);
  2671. }
  2672. String String::format(const Variant &values, String placeholder) const {
  2673. String new_string = String(this->ptr());
  2674. if (values.get_type() == Variant::ARRAY) {
  2675. Array values_arr = values;
  2676. for (int i = 0; i < values_arr.size(); i++) {
  2677. String i_as_str = String::num_int64(i);
  2678. if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
  2679. Array value_arr = values_arr[i];
  2680. if (value_arr.size() == 2) {
  2681. Variant v_key = value_arr[0];
  2682. String key = v_key;
  2683. Variant v_val = value_arr[1];
  2684. String val = v_val;
  2685. new_string = new_string.replace(placeholder.replace("_", key), val);
  2686. } else {
  2687. ERR_PRINT(String("STRING.format Inner Array size != 2 ").ascii().get_data());
  2688. }
  2689. } else { //Array structure ["RobotGuy","Logis","rookie"]
  2690. Variant v_val = values_arr[i];
  2691. String val = v_val;
  2692. if (placeholder.find("_") > -1) {
  2693. new_string = new_string.replace(placeholder.replace("_", i_as_str), val);
  2694. } else {
  2695. new_string = new_string.replace_first(placeholder, val);
  2696. }
  2697. }
  2698. }
  2699. } else if (values.get_type() == Variant::DICTIONARY) {
  2700. Dictionary d = values;
  2701. List<Variant> keys;
  2702. d.get_key_list(&keys);
  2703. for (const Variant &key : keys) {
  2704. new_string = new_string.replace(placeholder.replace("_", key), d[key]);
  2705. }
  2706. } else {
  2707. ERR_PRINT(String("Invalid type: use Array or Dictionary.").ascii().get_data());
  2708. }
  2709. return new_string;
  2710. }
  2711. String String::replace(const String &p_key, const String &p_with) const {
  2712. String new_string;
  2713. int search_from = 0;
  2714. int result = 0;
  2715. while ((result = find(p_key, search_from)) >= 0) {
  2716. new_string += substr(search_from, result - search_from);
  2717. new_string += p_with;
  2718. search_from = result + p_key.length();
  2719. }
  2720. if (search_from == 0) {
  2721. return *this;
  2722. }
  2723. new_string += substr(search_from, length() - search_from);
  2724. return new_string;
  2725. }
  2726. String String::replace(const char *p_key, const char *p_with) const {
  2727. String new_string;
  2728. int search_from = 0;
  2729. int result = 0;
  2730. while ((result = find(p_key, search_from)) >= 0) {
  2731. new_string += substr(search_from, result - search_from);
  2732. new_string += p_with;
  2733. int k = 0;
  2734. while (p_key[k] != '\0') {
  2735. k++;
  2736. }
  2737. search_from = result + k;
  2738. }
  2739. if (search_from == 0) {
  2740. return *this;
  2741. }
  2742. new_string += substr(search_from, length() - search_from);
  2743. return new_string;
  2744. }
  2745. String String::replace_first(const String &p_key, const String &p_with) const {
  2746. int pos = find(p_key);
  2747. if (pos >= 0) {
  2748. return substr(0, pos) + p_with + substr(pos + p_key.length(), length());
  2749. }
  2750. return *this;
  2751. }
  2752. String String::replacen(const String &p_key, const String &p_with) const {
  2753. String new_string;
  2754. int search_from = 0;
  2755. int result = 0;
  2756. while ((result = findn(p_key, search_from)) >= 0) {
  2757. new_string += substr(search_from, result - search_from);
  2758. new_string += p_with;
  2759. search_from = result + p_key.length();
  2760. }
  2761. if (search_from == 0) {
  2762. return *this;
  2763. }
  2764. new_string += substr(search_from, length() - search_from);
  2765. return new_string;
  2766. }
  2767. String String::repeat(int p_count) const {
  2768. ERR_FAIL_COND_V_MSG(p_count < 0, "", "Parameter count should be a positive number.");
  2769. String new_string;
  2770. const char32_t *src = this->get_data();
  2771. new_string.resize(length() * p_count + 1);
  2772. new_string[length() * p_count] = 0;
  2773. for (int i = 0; i < p_count; i++) {
  2774. for (int j = 0; j < length(); j++) {
  2775. new_string[i * length() + j] = src[j];
  2776. }
  2777. }
  2778. return new_string;
  2779. }
  2780. String String::left(int p_pos) const {
  2781. if (p_pos < 0) {
  2782. p_pos = length() + p_pos;
  2783. }
  2784. if (p_pos <= 0) {
  2785. return "";
  2786. }
  2787. if (p_pos >= length()) {
  2788. return *this;
  2789. }
  2790. return substr(0, p_pos);
  2791. }
  2792. String String::right(int p_pos) const {
  2793. if (p_pos < 0) {
  2794. p_pos = length() + p_pos;
  2795. }
  2796. if (p_pos <= 0) {
  2797. return "";
  2798. }
  2799. if (p_pos >= length()) {
  2800. return *this;
  2801. }
  2802. return substr(length() - p_pos);
  2803. }
  2804. char32_t String::unicode_at(int p_idx) const {
  2805. ERR_FAIL_INDEX_V(p_idx, length(), 0);
  2806. return operator[](p_idx);
  2807. }
  2808. String String::indent(const String &p_prefix) const {
  2809. String new_string;
  2810. int line_start = 0;
  2811. for (int i = 0; i < length(); i++) {
  2812. const char32_t c = operator[](i);
  2813. if (c == '\n') {
  2814. if (i == line_start) {
  2815. new_string += c; // Leave empty lines empty.
  2816. } else {
  2817. new_string += p_prefix + substr(line_start, i - line_start + 1);
  2818. }
  2819. line_start = i + 1;
  2820. }
  2821. }
  2822. if (line_start != length()) {
  2823. new_string += p_prefix + substr(line_start);
  2824. }
  2825. return new_string;
  2826. }
  2827. String String::dedent() const {
  2828. String new_string;
  2829. String indent;
  2830. bool has_indent = false;
  2831. bool has_text = false;
  2832. int line_start = 0;
  2833. int indent_stop = -1;
  2834. for (int i = 0; i < length(); i++) {
  2835. char32_t c = operator[](i);
  2836. if (c == '\n') {
  2837. if (has_text) {
  2838. new_string += substr(indent_stop, i - indent_stop);
  2839. }
  2840. new_string += "\n";
  2841. has_text = false;
  2842. line_start = i + 1;
  2843. indent_stop = -1;
  2844. } else if (!has_text) {
  2845. if (c > 32) {
  2846. has_text = true;
  2847. if (!has_indent) {
  2848. has_indent = true;
  2849. indent = substr(line_start, i - line_start);
  2850. indent_stop = i;
  2851. }
  2852. }
  2853. if (has_indent && indent_stop < 0) {
  2854. int j = i - line_start;
  2855. if (j >= indent.length() || c != indent[j]) {
  2856. indent_stop = i;
  2857. }
  2858. }
  2859. }
  2860. }
  2861. if (has_text) {
  2862. new_string += substr(indent_stop, length() - indent_stop);
  2863. }
  2864. return new_string;
  2865. }
  2866. String String::strip_edges(bool left, bool right) const {
  2867. int len = length();
  2868. int beg = 0, end = len;
  2869. if (left) {
  2870. for (int i = 0; i < len; i++) {
  2871. if (operator[](i) <= 32) {
  2872. beg++;
  2873. } else {
  2874. break;
  2875. }
  2876. }
  2877. }
  2878. if (right) {
  2879. for (int i = len - 1; i >= 0; i--) {
  2880. if (operator[](i) <= 32) {
  2881. end--;
  2882. } else {
  2883. break;
  2884. }
  2885. }
  2886. }
  2887. if (beg == 0 && end == len) {
  2888. return *this;
  2889. }
  2890. return substr(beg, end - beg);
  2891. }
  2892. String String::strip_escapes() const {
  2893. String new_string;
  2894. for (int i = 0; i < length(); i++) {
  2895. // Escape characters on first page of the ASCII table, before 32 (Space).
  2896. if (operator[](i) < 32) {
  2897. continue;
  2898. }
  2899. new_string += operator[](i);
  2900. }
  2901. return new_string;
  2902. }
  2903. String String::lstrip(const String &p_chars) const {
  2904. int len = length();
  2905. int beg;
  2906. for (beg = 0; beg < len; beg++) {
  2907. if (p_chars.find_char(get(beg)) == -1) {
  2908. break;
  2909. }
  2910. }
  2911. if (beg == 0) {
  2912. return *this;
  2913. }
  2914. return substr(beg, len - beg);
  2915. }
  2916. String String::rstrip(const String &p_chars) const {
  2917. int len = length();
  2918. int end;
  2919. for (end = len - 1; end >= 0; end--) {
  2920. if (p_chars.find_char(get(end)) == -1) {
  2921. break;
  2922. }
  2923. }
  2924. if (end == len - 1) {
  2925. return *this;
  2926. }
  2927. return substr(0, end + 1);
  2928. }
  2929. bool String::is_network_share_path() const {
  2930. return begins_with("//") || begins_with("\\\\");
  2931. }
  2932. String String::simplify_path() const {
  2933. String s = *this;
  2934. String drive;
  2935. if (s.begins_with("local://")) {
  2936. drive = "local://";
  2937. s = s.substr(8, s.length());
  2938. } else if (s.begins_with("res://")) {
  2939. drive = "res://";
  2940. s = s.substr(6, s.length());
  2941. } else if (s.begins_with("user://")) {
  2942. drive = "user://";
  2943. s = s.substr(7, s.length());
  2944. } else if (is_network_share_path()) {
  2945. drive = s.substr(0, 2);
  2946. s = s.substr(2, s.length() - 2);
  2947. } else if (s.begins_with("/") || s.begins_with("\\")) {
  2948. drive = s.substr(0, 1);
  2949. s = s.substr(1, s.length() - 1);
  2950. } else {
  2951. int p = s.find(":/");
  2952. if (p == -1) {
  2953. p = s.find(":\\");
  2954. }
  2955. if (p != -1 && p < s.find("/")) {
  2956. drive = s.substr(0, p + 2);
  2957. s = s.substr(p + 2, s.length());
  2958. }
  2959. }
  2960. s = s.replace("\\", "/");
  2961. while (true) { // in case of using 2 or more slash
  2962. String compare = s.replace("//", "/");
  2963. if (s == compare) {
  2964. break;
  2965. } else {
  2966. s = compare;
  2967. }
  2968. }
  2969. Vector<String> dirs = s.split("/", false);
  2970. for (int i = 0; i < dirs.size(); i++) {
  2971. String d = dirs[i];
  2972. if (d == ".") {
  2973. dirs.remove_at(i);
  2974. i--;
  2975. } else if (d == "..") {
  2976. if (i == 0) {
  2977. dirs.remove_at(i);
  2978. i--;
  2979. } else {
  2980. dirs.remove_at(i);
  2981. dirs.remove_at(i - 1);
  2982. i -= 2;
  2983. }
  2984. }
  2985. }
  2986. s = "";
  2987. for (int i = 0; i < dirs.size(); i++) {
  2988. if (i > 0) {
  2989. s += "/";
  2990. }
  2991. s += dirs[i];
  2992. }
  2993. return drive + s;
  2994. }
  2995. static int _humanize_digits(int p_num) {
  2996. if (p_num < 100) {
  2997. return 2;
  2998. } else if (p_num < 1024) {
  2999. return 1;
  3000. } else {
  3001. return 0;
  3002. }
  3003. }
  3004. String String::humanize_size(uint64_t p_size) {
  3005. uint64_t _div = 1;
  3006. Vector<String> prefixes;
  3007. prefixes.push_back(RTR("B"));
  3008. prefixes.push_back(RTR("KiB"));
  3009. prefixes.push_back(RTR("MiB"));
  3010. prefixes.push_back(RTR("GiB"));
  3011. prefixes.push_back(RTR("TiB"));
  3012. prefixes.push_back(RTR("PiB"));
  3013. prefixes.push_back(RTR("EiB"));
  3014. int prefix_idx = 0;
  3015. while (prefix_idx < prefixes.size() - 1 && p_size > (_div * 1024)) {
  3016. _div *= 1024;
  3017. prefix_idx++;
  3018. }
  3019. const int digits = prefix_idx > 0 ? _humanize_digits(p_size / _div) : 0;
  3020. const double divisor = prefix_idx > 0 ? _div : 1;
  3021. return String::num(p_size / divisor).pad_decimals(digits) + " " + prefixes[prefix_idx];
  3022. }
  3023. bool String::is_absolute_path() const {
  3024. if (length() > 1) {
  3025. return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
  3026. } else if ((length()) == 1) {
  3027. return (operator[](0) == '/' || operator[](0) == '\\');
  3028. } else {
  3029. return false;
  3030. }
  3031. }
  3032. bool String::is_valid_identifier() const {
  3033. int len = length();
  3034. if (len == 0) {
  3035. return false;
  3036. }
  3037. const char32_t *str = &operator[](0);
  3038. for (int i = 0; i < len; i++) {
  3039. if (i == 0) {
  3040. if (is_digit(str[0])) {
  3041. return false; // no start with number plz
  3042. }
  3043. }
  3044. bool valid_char = is_ascii_identifier_char(str[i]);
  3045. if (!valid_char) {
  3046. return false;
  3047. }
  3048. }
  3049. return true;
  3050. }
  3051. bool String::is_valid_string() const {
  3052. int l = length();
  3053. const char32_t *src = get_data();
  3054. bool valid = true;
  3055. for (int i = 0; i < l; i++) {
  3056. valid = valid && (src[i] < 0xd800 || (src[i] > 0xdfff && src[i] <= 0x10ffff));
  3057. }
  3058. return valid;
  3059. }
  3060. String String::uri_encode() const {
  3061. const CharString temp = utf8();
  3062. String res;
  3063. for (int i = 0; i < temp.length(); ++i) {
  3064. char ord = temp[i];
  3065. if (ord == '.' || ord == '-' || ord == '~' || is_ascii_identifier_char(ord)) {
  3066. res += ord;
  3067. } else {
  3068. char h_Val[3];
  3069. #if defined(__GNUC__) || defined(_MSC_VER)
  3070. snprintf(h_Val, 3, "%02hhX", ord);
  3071. #else
  3072. sprintf(h_Val, "%02hhX", ord);
  3073. #endif
  3074. res += "%";
  3075. res += h_Val;
  3076. }
  3077. }
  3078. return res;
  3079. }
  3080. String String::uri_decode() const {
  3081. CharString src = utf8();
  3082. CharString res;
  3083. for (int i = 0; i < src.length(); ++i) {
  3084. if (src[i] == '%' && i + 2 < src.length()) {
  3085. char ord1 = src[i + 1];
  3086. if (is_digit(ord1) || is_ascii_upper_case(ord1)) {
  3087. char ord2 = src[i + 2];
  3088. if (is_digit(ord2) || is_ascii_upper_case(ord2)) {
  3089. char bytes[3] = { (char)ord1, (char)ord2, 0 };
  3090. res += (char)strtol(bytes, nullptr, 16);
  3091. i += 2;
  3092. }
  3093. } else {
  3094. res += src[i];
  3095. }
  3096. } else if (src[i] == '+') {
  3097. res += ' ';
  3098. } else {
  3099. res += src[i];
  3100. }
  3101. }
  3102. return String::utf8(res);
  3103. }
  3104. String String::c_unescape() const {
  3105. String escaped = *this;
  3106. escaped = escaped.replace("\\a", "\a");
  3107. escaped = escaped.replace("\\b", "\b");
  3108. escaped = escaped.replace("\\f", "\f");
  3109. escaped = escaped.replace("\\n", "\n");
  3110. escaped = escaped.replace("\\r", "\r");
  3111. escaped = escaped.replace("\\t", "\t");
  3112. escaped = escaped.replace("\\v", "\v");
  3113. escaped = escaped.replace("\\'", "\'");
  3114. escaped = escaped.replace("\\\"", "\"");
  3115. escaped = escaped.replace("\\?", "\?");
  3116. escaped = escaped.replace("\\\\", "\\");
  3117. return escaped;
  3118. }
  3119. String String::c_escape() const {
  3120. String escaped = *this;
  3121. escaped = escaped.replace("\\", "\\\\");
  3122. escaped = escaped.replace("\a", "\\a");
  3123. escaped = escaped.replace("\b", "\\b");
  3124. escaped = escaped.replace("\f", "\\f");
  3125. escaped = escaped.replace("\n", "\\n");
  3126. escaped = escaped.replace("\r", "\\r");
  3127. escaped = escaped.replace("\t", "\\t");
  3128. escaped = escaped.replace("\v", "\\v");
  3129. escaped = escaped.replace("\'", "\\'");
  3130. escaped = escaped.replace("\?", "\\?");
  3131. escaped = escaped.replace("\"", "\\\"");
  3132. return escaped;
  3133. }
  3134. String String::c_escape_multiline() const {
  3135. String escaped = *this;
  3136. escaped = escaped.replace("\\", "\\\\");
  3137. escaped = escaped.replace("\"", "\\\"");
  3138. return escaped;
  3139. }
  3140. String String::json_escape() const {
  3141. String escaped = *this;
  3142. escaped = escaped.replace("\\", "\\\\");
  3143. escaped = escaped.replace("\b", "\\b");
  3144. escaped = escaped.replace("\f", "\\f");
  3145. escaped = escaped.replace("\n", "\\n");
  3146. escaped = escaped.replace("\r", "\\r");
  3147. escaped = escaped.replace("\t", "\\t");
  3148. escaped = escaped.replace("\v", "\\v");
  3149. escaped = escaped.replace("\"", "\\\"");
  3150. return escaped;
  3151. }
  3152. String String::xml_escape(bool p_escape_quotes) const {
  3153. String str = *this;
  3154. str = str.replace("&", "&amp;");
  3155. str = str.replace("<", "&lt;");
  3156. str = str.replace(">", "&gt;");
  3157. if (p_escape_quotes) {
  3158. str = str.replace("'", "&apos;");
  3159. str = str.replace("\"", "&quot;");
  3160. }
  3161. /*
  3162. for (int i=1;i<32;i++) {
  3163. char chr[2]={i,0};
  3164. str=str.replace(chr,"&#"+String::num(i)+";");
  3165. }*/
  3166. return str;
  3167. }
  3168. static _FORCE_INLINE_ int _xml_unescape(const char32_t *p_src, int p_src_len, char32_t *p_dst) {
  3169. int len = 0;
  3170. while (p_src_len) {
  3171. if (*p_src == '&') {
  3172. int eat = 0;
  3173. if (p_src_len >= 4 && p_src[1] == '#') {
  3174. char32_t c = 0;
  3175. bool overflow = false;
  3176. if (p_src[2] == 'x') {
  3177. // Hex entity &#x<num>;
  3178. for (int i = 3; i < p_src_len; i++) {
  3179. eat = i + 1;
  3180. char32_t ct = p_src[i];
  3181. if (ct == ';') {
  3182. break;
  3183. } else if (is_digit(ct)) {
  3184. ct = ct - '0';
  3185. } else if (ct >= 'a' && ct <= 'f') {
  3186. ct = (ct - 'a') + 10;
  3187. } else if (ct >= 'A' && ct <= 'F') {
  3188. ct = (ct - 'A') + 10;
  3189. } else {
  3190. break;
  3191. }
  3192. if (c > (UINT32_MAX >> 4)) {
  3193. overflow = true;
  3194. break;
  3195. }
  3196. c <<= 4;
  3197. c |= ct;
  3198. }
  3199. } else {
  3200. // Decimal entity &#<num>;
  3201. for (int i = 2; i < p_src_len; i++) {
  3202. eat = i + 1;
  3203. char32_t ct = p_src[i];
  3204. if (ct == ';' || !is_digit(ct)) {
  3205. break;
  3206. }
  3207. }
  3208. if (p_src[eat - 1] == ';') {
  3209. int64_t val = String::to_int(p_src + 2, eat - 3);
  3210. if (val > 0 && val <= UINT32_MAX) {
  3211. c = (char32_t)val;
  3212. } else {
  3213. overflow = true;
  3214. }
  3215. }
  3216. }
  3217. // Value must be non-zero, in the range of char32_t,
  3218. // actually end with ';'. If invalid, leave the entity as-is
  3219. if (c == '\0' || overflow || p_src[eat - 1] != ';') {
  3220. eat = 1;
  3221. c = *p_src;
  3222. }
  3223. if (p_dst) {
  3224. *p_dst = c;
  3225. }
  3226. } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') {
  3227. if (p_dst) {
  3228. *p_dst = '>';
  3229. }
  3230. eat = 4;
  3231. } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') {
  3232. if (p_dst) {
  3233. *p_dst = '<';
  3234. }
  3235. eat = 4;
  3236. } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') {
  3237. if (p_dst) {
  3238. *p_dst = '&';
  3239. }
  3240. eat = 5;
  3241. } else if (p_src_len >= 6 && p_src[1] == 'q' && p_src[2] == 'u' && p_src[3] == 'o' && p_src[4] == 't' && p_src[5] == ';') {
  3242. if (p_dst) {
  3243. *p_dst = '"';
  3244. }
  3245. eat = 6;
  3246. } else if (p_src_len >= 6 && p_src[1] == 'a' && p_src[2] == 'p' && p_src[3] == 'o' && p_src[4] == 's' && p_src[5] == ';') {
  3247. if (p_dst) {
  3248. *p_dst = '\'';
  3249. }
  3250. eat = 6;
  3251. } else {
  3252. if (p_dst) {
  3253. *p_dst = *p_src;
  3254. }
  3255. eat = 1;
  3256. }
  3257. if (p_dst) {
  3258. p_dst++;
  3259. }
  3260. len++;
  3261. p_src += eat;
  3262. p_src_len -= eat;
  3263. } else {
  3264. if (p_dst) {
  3265. *p_dst = *p_src;
  3266. p_dst++;
  3267. }
  3268. len++;
  3269. p_src++;
  3270. p_src_len--;
  3271. }
  3272. }
  3273. return len;
  3274. }
  3275. String String::xml_unescape() const {
  3276. String str;
  3277. int l = length();
  3278. int len = _xml_unescape(get_data(), l, nullptr);
  3279. if (len == 0) {
  3280. return String();
  3281. }
  3282. str.resize(len + 1);
  3283. _xml_unescape(get_data(), l, str.ptrw());
  3284. str[len] = 0;
  3285. return str;
  3286. }
  3287. String String::pad_decimals(int p_digits) const {
  3288. String s = *this;
  3289. int c = s.find(".");
  3290. if (c == -1) {
  3291. if (p_digits <= 0) {
  3292. return s;
  3293. }
  3294. s += ".";
  3295. c = s.length() - 1;
  3296. } else {
  3297. if (p_digits <= 0) {
  3298. return s.substr(0, c);
  3299. }
  3300. }
  3301. if (s.length() - (c + 1) > p_digits) {
  3302. s = s.substr(0, c + p_digits + 1);
  3303. } else {
  3304. while (s.length() - (c + 1) < p_digits) {
  3305. s += "0";
  3306. }
  3307. }
  3308. return s;
  3309. }
  3310. String String::pad_zeros(int p_digits) const {
  3311. String s = *this;
  3312. int end = s.find(".");
  3313. if (end == -1) {
  3314. end = s.length();
  3315. }
  3316. if (end == 0) {
  3317. return s;
  3318. }
  3319. int begin = 0;
  3320. while (begin < end && !is_digit(s[begin])) {
  3321. begin++;
  3322. }
  3323. if (begin >= end) {
  3324. return s;
  3325. }
  3326. while (end - begin < p_digits) {
  3327. s = s.insert(begin, "0");
  3328. end++;
  3329. }
  3330. return s;
  3331. }
  3332. String String::trim_prefix(const String &p_prefix) const {
  3333. String s = *this;
  3334. if (s.begins_with(p_prefix)) {
  3335. return s.substr(p_prefix.length(), s.length() - p_prefix.length());
  3336. }
  3337. return s;
  3338. }
  3339. String String::trim_suffix(const String &p_suffix) const {
  3340. String s = *this;
  3341. if (s.ends_with(p_suffix)) {
  3342. return s.substr(0, s.length() - p_suffix.length());
  3343. }
  3344. return s;
  3345. }
  3346. bool String::is_valid_int() const {
  3347. int len = length();
  3348. if (len == 0) {
  3349. return false;
  3350. }
  3351. int from = 0;
  3352. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  3353. from++;
  3354. }
  3355. for (int i = from; i < len; i++) {
  3356. if (!is_digit(operator[](i))) {
  3357. return false; // no start with number plz
  3358. }
  3359. }
  3360. return true;
  3361. }
  3362. bool String::is_valid_hex_number(bool p_with_prefix) const {
  3363. int len = length();
  3364. if (len == 0) {
  3365. return false;
  3366. }
  3367. int from = 0;
  3368. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  3369. from++;
  3370. }
  3371. if (p_with_prefix) {
  3372. if (len < 3) {
  3373. return false;
  3374. }
  3375. if (operator[](from) != '0' || operator[](from + 1) != 'x') {
  3376. return false;
  3377. }
  3378. from += 2;
  3379. }
  3380. for (int i = from; i < len; i++) {
  3381. char32_t c = operator[](i);
  3382. if (is_hex_digit(c)) {
  3383. continue;
  3384. }
  3385. return false;
  3386. }
  3387. return true;
  3388. }
  3389. bool String::is_valid_float() const {
  3390. int len = length();
  3391. if (len == 0) {
  3392. return false;
  3393. }
  3394. int from = 0;
  3395. if (operator[](0) == '+' || operator[](0) == '-') {
  3396. from++;
  3397. }
  3398. bool exponent_found = false;
  3399. bool period_found = false;
  3400. bool sign_found = false;
  3401. bool exponent_values_found = false;
  3402. bool numbers_found = false;
  3403. for (int i = from; i < len; i++) {
  3404. if (is_digit(operator[](i))) {
  3405. if (exponent_found) {
  3406. exponent_values_found = true;
  3407. } else {
  3408. numbers_found = true;
  3409. }
  3410. } else if (numbers_found && !exponent_found && operator[](i) == 'e') {
  3411. exponent_found = true;
  3412. } else if (!period_found && !exponent_found && operator[](i) == '.') {
  3413. period_found = true;
  3414. } else if ((operator[](i) == '-' || operator[](i) == '+') && exponent_found && !exponent_values_found && !sign_found) {
  3415. sign_found = true;
  3416. } else {
  3417. return false; // no start with number plz
  3418. }
  3419. }
  3420. return numbers_found;
  3421. }
  3422. String String::path_to_file(const String &p_path) const {
  3423. // Don't get base dir for src, this is expected to be a dir already.
  3424. String src = this->replace("\\", "/");
  3425. String dst = p_path.replace("\\", "/").get_base_dir();
  3426. String rel = src.path_to(dst);
  3427. if (rel == dst) { // failed
  3428. return p_path;
  3429. } else {
  3430. return rel + p_path.get_file();
  3431. }
  3432. }
  3433. String String::path_to(const String &p_path) const {
  3434. String src = this->replace("\\", "/");
  3435. String dst = p_path.replace("\\", "/");
  3436. if (!src.ends_with("/")) {
  3437. src += "/";
  3438. }
  3439. if (!dst.ends_with("/")) {
  3440. dst += "/";
  3441. }
  3442. if (src.begins_with("res://") && dst.begins_with("res://")) {
  3443. src = src.replace("res://", "/");
  3444. dst = dst.replace("res://", "/");
  3445. } else if (src.begins_with("user://") && dst.begins_with("user://")) {
  3446. src = src.replace("user://", "/");
  3447. dst = dst.replace("user://", "/");
  3448. } else if (src.begins_with("/") && dst.begins_with("/")) {
  3449. //nothing
  3450. } else {
  3451. //dos style
  3452. String src_begin = src.get_slicec('/', 0);
  3453. String dst_begin = dst.get_slicec('/', 0);
  3454. if (src_begin != dst_begin) {
  3455. return p_path; //impossible to do this
  3456. }
  3457. src = src.substr(src_begin.length(), src.length());
  3458. dst = dst.substr(dst_begin.length(), dst.length());
  3459. }
  3460. //remove leading and trailing slash and split
  3461. Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/");
  3462. Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/");
  3463. //find common parent
  3464. int common_parent = 0;
  3465. while (true) {
  3466. if (src_dirs.size() == common_parent) {
  3467. break;
  3468. }
  3469. if (dst_dirs.size() == common_parent) {
  3470. break;
  3471. }
  3472. if (src_dirs[common_parent] != dst_dirs[common_parent]) {
  3473. break;
  3474. }
  3475. common_parent++;
  3476. }
  3477. common_parent--;
  3478. String dir;
  3479. for (int i = src_dirs.size() - 1; i > common_parent; i--) {
  3480. dir += "../";
  3481. }
  3482. for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
  3483. dir += dst_dirs[i] + "/";
  3484. }
  3485. if (dir.length() == 0) {
  3486. dir = "./";
  3487. }
  3488. return dir;
  3489. }
  3490. bool String::is_valid_html_color() const {
  3491. return Color::html_is_valid(*this);
  3492. }
  3493. bool String::is_valid_filename() const {
  3494. String stripped = strip_edges();
  3495. if (*this != stripped) {
  3496. return false;
  3497. }
  3498. if (stripped.is_empty()) {
  3499. return false;
  3500. }
  3501. return !(find(":") != -1 || find("/") != -1 || find("\\") != -1 || find("?") != -1 || find("*") != -1 || find("\"") != -1 || find("|") != -1 || find("%") != -1 || find("<") != -1 || find(">") != -1);
  3502. }
  3503. bool String::is_valid_ip_address() const {
  3504. if (find(":") >= 0) {
  3505. Vector<String> ip = split(":");
  3506. for (int i = 0; i < ip.size(); i++) {
  3507. String n = ip[i];
  3508. if (n.is_empty()) {
  3509. continue;
  3510. }
  3511. if (n.is_valid_hex_number(false)) {
  3512. int64_t nint = n.hex_to_int();
  3513. if (nint < 0 || nint > 0xffff) {
  3514. return false;
  3515. }
  3516. continue;
  3517. }
  3518. if (!n.is_valid_ip_address()) {
  3519. return false;
  3520. }
  3521. }
  3522. } else {
  3523. Vector<String> ip = split(".");
  3524. if (ip.size() != 4) {
  3525. return false;
  3526. }
  3527. for (int i = 0; i < ip.size(); i++) {
  3528. String n = ip[i];
  3529. if (!n.is_valid_int()) {
  3530. return false;
  3531. }
  3532. int val = n.to_int();
  3533. if (val < 0 || val > 255) {
  3534. return false;
  3535. }
  3536. }
  3537. }
  3538. return true;
  3539. }
  3540. bool String::is_resource_file() const {
  3541. return begins_with("res://") && find("::") == -1;
  3542. }
  3543. bool String::is_relative_path() const {
  3544. return !is_absolute_path();
  3545. }
  3546. String String::get_base_dir() const {
  3547. int end = 0;
  3548. // URL scheme style base.
  3549. int basepos = find("://");
  3550. if (basepos != -1) {
  3551. end = basepos + 3;
  3552. }
  3553. // Windows top level directory base.
  3554. if (end == 0) {
  3555. basepos = find(":/");
  3556. if (basepos == -1) {
  3557. basepos = find(":\\");
  3558. }
  3559. if (basepos != -1) {
  3560. end = basepos + 2;
  3561. }
  3562. }
  3563. // Windows UNC network share path.
  3564. if (end == 0) {
  3565. if (is_network_share_path()) {
  3566. basepos = find("/", 2);
  3567. if (basepos == -1) {
  3568. basepos = find("\\", 2);
  3569. }
  3570. int servpos = find("/", basepos + 1);
  3571. if (servpos == -1) {
  3572. servpos = find("\\", basepos + 1);
  3573. }
  3574. if (servpos != -1) {
  3575. end = servpos + 1;
  3576. }
  3577. }
  3578. }
  3579. // Unix root directory base.
  3580. if (end == 0) {
  3581. if (begins_with("/")) {
  3582. end = 1;
  3583. }
  3584. }
  3585. String rs;
  3586. String base;
  3587. if (end != 0) {
  3588. rs = substr(end, length());
  3589. base = substr(0, end);
  3590. } else {
  3591. rs = *this;
  3592. }
  3593. int sep = MAX(rs.rfind("/"), rs.rfind("\\"));
  3594. if (sep == -1) {
  3595. return base;
  3596. }
  3597. return base + rs.substr(0, sep);
  3598. }
  3599. String String::get_file() const {
  3600. int sep = MAX(rfind("/"), rfind("\\"));
  3601. if (sep == -1) {
  3602. return *this;
  3603. }
  3604. return substr(sep + 1, length());
  3605. }
  3606. String String::get_extension() const {
  3607. int pos = rfind(".");
  3608. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  3609. return "";
  3610. }
  3611. return substr(pos + 1, length());
  3612. }
  3613. String String::plus_file(const String &p_file) const {
  3614. if (is_empty()) {
  3615. return p_file;
  3616. }
  3617. if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/')) {
  3618. return *this + p_file;
  3619. }
  3620. return *this + "/" + p_file;
  3621. }
  3622. String String::property_name_encode() const {
  3623. // Escape and quote strings with extended ASCII or further Unicode characters
  3624. // as well as '"', '=' or ' ' (32)
  3625. const char32_t *cstr = get_data();
  3626. for (int i = 0; cstr[i]; i++) {
  3627. if (cstr[i] == '=' || cstr[i] == '"' || cstr[i] == ';' || cstr[i] == '[' || cstr[i] == ']' || cstr[i] < 33 || cstr[i] > 126) {
  3628. return "\"" + c_escape_multiline() + "\"";
  3629. }
  3630. }
  3631. // Keep as is
  3632. return *this;
  3633. }
  3634. // Changes made to the set of invalid characters must also be reflected in the String documentation.
  3635. const String String::invalid_node_name_characters = ". : @ / \"";
  3636. String String::validate_node_name() const {
  3637. Vector<String> chars = String::invalid_node_name_characters.split(" ");
  3638. String name = this->replace(chars[0], "");
  3639. for (int i = 1; i < chars.size(); i++) {
  3640. name = name.replace(chars[i], "");
  3641. }
  3642. return name;
  3643. }
  3644. String String::get_basename() const {
  3645. int pos = rfind(".");
  3646. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  3647. return *this;
  3648. }
  3649. return substr(0, pos);
  3650. }
  3651. String itos(int64_t p_val) {
  3652. return String::num_int64(p_val);
  3653. }
  3654. String uitos(uint64_t p_val) {
  3655. return String::num_uint64(p_val);
  3656. }
  3657. String rtos(double p_val) {
  3658. return String::num(p_val);
  3659. }
  3660. String rtoss(double p_val) {
  3661. return String::num_scientific(p_val);
  3662. }
  3663. // Right-pad with a character.
  3664. String String::rpad(int min_length, const String &character) const {
  3665. String s = *this;
  3666. int padding = min_length - s.length();
  3667. if (padding > 0) {
  3668. for (int i = 0; i < padding; i++) {
  3669. s = s + character;
  3670. }
  3671. }
  3672. return s;
  3673. }
  3674. // Left-pad with a character.
  3675. String String::lpad(int min_length, const String &character) const {
  3676. String s = *this;
  3677. int padding = min_length - s.length();
  3678. if (padding > 0) {
  3679. for (int i = 0; i < padding; i++) {
  3680. s = character + s;
  3681. }
  3682. }
  3683. return s;
  3684. }
  3685. // sprintf is implemented in GDScript via:
  3686. // "fish %s pie" % "frog"
  3687. // "fish %s %d pie" % ["frog", 12]
  3688. // In case of an error, the string returned is the error description and "error" is true.
  3689. String String::sprintf(const Array &values, bool *error) const {
  3690. String formatted;
  3691. char32_t *self = (char32_t *)get_data();
  3692. bool in_format = false;
  3693. int value_index = 0;
  3694. int min_chars = 0;
  3695. int min_decimals = 0;
  3696. bool in_decimals = false;
  3697. bool pad_with_zeroes = false;
  3698. bool left_justified = false;
  3699. bool show_sign = false;
  3700. if (error) {
  3701. *error = true;
  3702. }
  3703. for (; *self; self++) {
  3704. const char32_t c = *self;
  3705. if (in_format) { // We have % - let's see what else we get.
  3706. switch (c) {
  3707. case '%': { // Replace %% with %
  3708. formatted += chr(c);
  3709. in_format = false;
  3710. break;
  3711. }
  3712. case 'd': // Integer (signed)
  3713. case 'o': // Octal
  3714. case 'x': // Hexadecimal (lowercase)
  3715. case 'X': { // Hexadecimal (uppercase)
  3716. if (value_index >= values.size()) {
  3717. return "not enough arguments for format string";
  3718. }
  3719. if (!values[value_index].is_num()) {
  3720. return "a number is required";
  3721. }
  3722. int64_t value = values[value_index];
  3723. int base = 16;
  3724. bool capitalize = false;
  3725. switch (c) {
  3726. case 'd':
  3727. base = 10;
  3728. break;
  3729. case 'o':
  3730. base = 8;
  3731. break;
  3732. case 'x':
  3733. break;
  3734. case 'X':
  3735. base = 16;
  3736. capitalize = true;
  3737. break;
  3738. }
  3739. // Get basic number.
  3740. String str = String::num_int64(ABS(value), base, capitalize);
  3741. int number_len = str.length();
  3742. // Padding.
  3743. int pad_chars_count = (value < 0 || show_sign) ? min_chars - 1 : min_chars;
  3744. String pad_char = pad_with_zeroes ? String("0") : String(" ");
  3745. if (left_justified) {
  3746. str = str.rpad(pad_chars_count, pad_char);
  3747. } else {
  3748. str = str.lpad(pad_chars_count, pad_char);
  3749. }
  3750. // Sign.
  3751. if (show_sign && value >= 0) {
  3752. str = str.insert(pad_with_zeroes ? 0 : str.length() - number_len, "+");
  3753. } else if (value < 0) {
  3754. str = str.insert(pad_with_zeroes ? 0 : str.length() - number_len, "-");
  3755. }
  3756. formatted += str;
  3757. ++value_index;
  3758. in_format = false;
  3759. break;
  3760. }
  3761. case 'f': { // Float
  3762. if (value_index >= values.size()) {
  3763. return "not enough arguments for format string";
  3764. }
  3765. if (!values[value_index].is_num()) {
  3766. return "a number is required";
  3767. }
  3768. double value = values[value_index];
  3769. bool is_negative = (value < 0);
  3770. String str = String::num(ABS(value), min_decimals);
  3771. // Pad decimals out.
  3772. str = str.pad_decimals(min_decimals);
  3773. int initial_len = str.length();
  3774. // Padding. Leave room for sign later if required.
  3775. int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars;
  3776. String pad_char = pad_with_zeroes ? String("0") : String(" ");
  3777. if (left_justified) {
  3778. if (pad_with_zeroes) {
  3779. return "left justification cannot be used with zeros as the padding";
  3780. } else {
  3781. str = str.rpad(pad_chars_count, pad_char);
  3782. }
  3783. } else {
  3784. str = str.lpad(pad_chars_count, pad_char);
  3785. }
  3786. // Add sign if needed.
  3787. if (show_sign || is_negative) {
  3788. String sign_char = is_negative ? "-" : "+";
  3789. if (left_justified) {
  3790. str = str.insert(0, sign_char);
  3791. } else {
  3792. str = str.insert(pad_with_zeroes ? 0 : str.length() - initial_len, sign_char);
  3793. }
  3794. }
  3795. formatted += str;
  3796. ++value_index;
  3797. in_format = false;
  3798. break;
  3799. }
  3800. case 's': { // String
  3801. if (value_index >= values.size()) {
  3802. return "not enough arguments for format string";
  3803. }
  3804. String str = values[value_index];
  3805. // Padding.
  3806. if (left_justified) {
  3807. str = str.rpad(min_chars);
  3808. } else {
  3809. str = str.lpad(min_chars);
  3810. }
  3811. formatted += str;
  3812. ++value_index;
  3813. in_format = false;
  3814. break;
  3815. }
  3816. case 'c': {
  3817. if (value_index >= values.size()) {
  3818. return "not enough arguments for format string";
  3819. }
  3820. // Convert to character.
  3821. String str;
  3822. if (values[value_index].is_num()) {
  3823. int value = values[value_index];
  3824. if (value < 0) {
  3825. return "unsigned integer is lower than minimum";
  3826. } else if (value >= 0xd800 && value <= 0xdfff) {
  3827. return "unsigned integer is invalid Unicode character";
  3828. } else if (value > 0x10ffff) {
  3829. return "unsigned integer is greater than maximum";
  3830. }
  3831. str = chr(values[value_index]);
  3832. } else if (values[value_index].get_type() == Variant::STRING) {
  3833. str = values[value_index];
  3834. if (str.length() != 1) {
  3835. return "%c requires number or single-character string";
  3836. }
  3837. } else {
  3838. return "%c requires number or single-character string";
  3839. }
  3840. // Padding.
  3841. if (left_justified) {
  3842. str = str.rpad(min_chars);
  3843. } else {
  3844. str = str.lpad(min_chars);
  3845. }
  3846. formatted += str;
  3847. ++value_index;
  3848. in_format = false;
  3849. break;
  3850. }
  3851. case '-': { // Left justify
  3852. left_justified = true;
  3853. break;
  3854. }
  3855. case '+': { // Show + if positive.
  3856. show_sign = true;
  3857. break;
  3858. }
  3859. case '0':
  3860. case '1':
  3861. case '2':
  3862. case '3':
  3863. case '4':
  3864. case '5':
  3865. case '6':
  3866. case '7':
  3867. case '8':
  3868. case '9': {
  3869. int n = c - '0';
  3870. if (in_decimals) {
  3871. min_decimals *= 10;
  3872. min_decimals += n;
  3873. } else {
  3874. if (c == '0' && min_chars == 0) {
  3875. pad_with_zeroes = true;
  3876. } else {
  3877. min_chars *= 10;
  3878. min_chars += n;
  3879. }
  3880. }
  3881. break;
  3882. }
  3883. case '.': { // Float separator.
  3884. if (in_decimals) {
  3885. return "too many decimal points in format";
  3886. }
  3887. in_decimals = true;
  3888. min_decimals = 0; // We want to add the value manually.
  3889. break;
  3890. }
  3891. case '*': { // Dynamic width, based on value.
  3892. if (value_index >= values.size()) {
  3893. return "not enough arguments for format string";
  3894. }
  3895. if (!values[value_index].is_num()) {
  3896. return "* wants number";
  3897. }
  3898. int size = values[value_index];
  3899. if (in_decimals) {
  3900. min_decimals = size;
  3901. } else {
  3902. min_chars = size;
  3903. }
  3904. ++value_index;
  3905. break;
  3906. }
  3907. default: {
  3908. return "unsupported format character";
  3909. }
  3910. }
  3911. } else { // Not in format string.
  3912. switch (c) {
  3913. case '%':
  3914. in_format = true;
  3915. // Back to defaults:
  3916. min_chars = 0;
  3917. min_decimals = 6;
  3918. pad_with_zeroes = false;
  3919. left_justified = false;
  3920. show_sign = false;
  3921. in_decimals = false;
  3922. break;
  3923. default:
  3924. formatted += chr(c);
  3925. }
  3926. }
  3927. }
  3928. if (in_format) {
  3929. return "incomplete format";
  3930. }
  3931. if (value_index != values.size()) {
  3932. return "not all arguments converted during string formatting";
  3933. }
  3934. if (error) {
  3935. *error = false;
  3936. }
  3937. return formatted;
  3938. }
  3939. String String::quote(String quotechar) const {
  3940. return quotechar + *this + quotechar;
  3941. }
  3942. String String::unquote() const {
  3943. if (!is_quoted()) {
  3944. return *this;
  3945. }
  3946. return substr(1, length() - 2);
  3947. }
  3948. Vector<uint8_t> String::to_ascii_buffer() const {
  3949. const String *s = this;
  3950. if (s->is_empty()) {
  3951. return Vector<uint8_t>();
  3952. }
  3953. CharString charstr = s->ascii();
  3954. Vector<uint8_t> retval;
  3955. size_t len = charstr.length();
  3956. retval.resize(len);
  3957. uint8_t *w = retval.ptrw();
  3958. memcpy(w, charstr.ptr(), len);
  3959. return retval;
  3960. }
  3961. Vector<uint8_t> String::to_utf8_buffer() const {
  3962. const String *s = this;
  3963. if (s->is_empty()) {
  3964. return Vector<uint8_t>();
  3965. }
  3966. CharString charstr = s->utf8();
  3967. Vector<uint8_t> retval;
  3968. size_t len = charstr.length();
  3969. retval.resize(len);
  3970. uint8_t *w = retval.ptrw();
  3971. memcpy(w, charstr.ptr(), len);
  3972. return retval;
  3973. }
  3974. Vector<uint8_t> String::to_utf16_buffer() const {
  3975. const String *s = this;
  3976. if (s->is_empty()) {
  3977. return Vector<uint8_t>();
  3978. }
  3979. Char16String charstr = s->utf16();
  3980. Vector<uint8_t> retval;
  3981. size_t len = charstr.length() * sizeof(char16_t);
  3982. retval.resize(len);
  3983. uint8_t *w = retval.ptrw();
  3984. memcpy(w, (const void *)charstr.ptr(), len);
  3985. return retval;
  3986. }
  3987. Vector<uint8_t> String::to_utf32_buffer() const {
  3988. const String *s = this;
  3989. if (s->is_empty()) {
  3990. return Vector<uint8_t>();
  3991. }
  3992. Vector<uint8_t> retval;
  3993. size_t len = s->length() * sizeof(char32_t);
  3994. retval.resize(len);
  3995. uint8_t *w = retval.ptrw();
  3996. memcpy(w, (const void *)s->ptr(), len);
  3997. return retval;
  3998. }
  3999. #ifdef TOOLS_ENABLED
  4000. String TTR(const String &p_text, const String &p_context) {
  4001. if (TranslationServer::get_singleton()) {
  4002. return TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  4003. }
  4004. return p_text;
  4005. }
  4006. String TTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4007. if (TranslationServer::get_singleton()) {
  4008. return TranslationServer::get_singleton()->tool_translate_plural(p_text, p_text_plural, p_n, p_context);
  4009. }
  4010. // Return message based on English plural rule if translation is not possible.
  4011. if (p_n == 1) {
  4012. return p_text;
  4013. }
  4014. return p_text_plural;
  4015. }
  4016. /* DTR and DTRN are used for the documentation, handling descriptions extracted
  4017. * from the XML.
  4018. * They also replace `$DOCS_URL` with the actual URL to the documentation's branch,
  4019. * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
  4020. */
  4021. String DTR(const String &p_text, const String &p_context) {
  4022. // Comes straight from the XML, so remove indentation and any trailing whitespace.
  4023. const String text = p_text.dedent().strip_edges();
  4024. if (TranslationServer::get_singleton()) {
  4025. return String(TranslationServer::get_singleton()->doc_translate(text, p_context)).replace("$DOCS_URL", VERSION_DOCS_URL);
  4026. }
  4027. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  4028. }
  4029. String DTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4030. const String text = p_text.dedent().strip_edges();
  4031. const String text_plural = p_text_plural.dedent().strip_edges();
  4032. if (TranslationServer::get_singleton()) {
  4033. return String(TranslationServer::get_singleton()->doc_translate_plural(text, text_plural, p_n, p_context)).replace("$DOCS_URL", VERSION_DOCS_URL);
  4034. }
  4035. // Return message based on English plural rule if translation is not possible.
  4036. if (p_n == 1) {
  4037. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  4038. }
  4039. return text_plural.replace("$DOCS_URL", VERSION_DOCS_URL);
  4040. }
  4041. #endif
  4042. String RTR(const String &p_text, const String &p_context) {
  4043. if (TranslationServer::get_singleton()) {
  4044. String rtr = TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  4045. if (rtr.is_empty() || rtr == p_text) {
  4046. return TranslationServer::get_singleton()->translate(p_text, p_context);
  4047. } else {
  4048. return rtr;
  4049. }
  4050. }
  4051. return p_text;
  4052. }
  4053. String RTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4054. if (TranslationServer::get_singleton()) {
  4055. String rtr = TranslationServer::get_singleton()->tool_translate_plural(p_text, p_text_plural, p_n, p_context);
  4056. if (rtr.is_empty() || rtr == p_text || rtr == p_text_plural) {
  4057. return TranslationServer::get_singleton()->translate_plural(p_text, p_text_plural, p_n, p_context);
  4058. } else {
  4059. return rtr;
  4060. }
  4061. }
  4062. // Return message based on English plural rule if translation is not possible.
  4063. if (p_n == 1) {
  4064. return p_text;
  4065. }
  4066. return p_text_plural;
  4067. }