ustring.cpp 137 KB

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