ustring.cpp 103 KB

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