ustring.cpp 101 KB

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