ustring.cpp 137 KB

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