ustring.cpp 102 KB

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