ustring.cpp 135 KB

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