ustring.cpp 103 KB

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