ustring.cpp 136 KB

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