ustring.cpp 138 KB

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