ustring.cpp 136 KB

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