ustring.cpp 109 KB

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