ustring.cpp 120 KB

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