ustring.cpp 113 KB

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