ustring.cpp 102 KB

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