ustring.cpp 102 KB

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