ustring.cpp 102 KB

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