ustring.cpp 89 KB

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