ustring.cpp 130 KB

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