ustring.cpp 104 KB

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