ustring.cpp 137 KB

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