ustring.cpp 97 KB

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