ustring.cpp 137 KB

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