ustring.cpp 103 KB

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