ustring.cpp 134 KB

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