ustring.cpp 103 KB

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