ustring.cpp 136 KB

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