ustring.cpp 104 KB

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