ustring.cpp 134 KB

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