ustring.cpp 139 KB

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