ustring.cpp 112 KB

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