ustring.cpp 102 KB

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