ustring.cpp 87 KB

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