ustring.cpp 103 KB

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