ustring.cpp 139 KB

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