ustring.cpp 138 KB

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