ustring.cpp 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933
  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. if (is_empty()) {
  1379. return *this;
  1380. }
  1381. String upper;
  1382. upper.resize(size());
  1383. const char32_t *old_ptr = ptr();
  1384. char32_t *upper_ptrw = upper.ptrw();
  1385. while (*old_ptr) {
  1386. *upper_ptrw++ = _find_upper(*old_ptr++);
  1387. }
  1388. *upper_ptrw = 0;
  1389. return upper;
  1390. }
  1391. String String::to_lower() const {
  1392. if (is_empty()) {
  1393. return *this;
  1394. }
  1395. String lower;
  1396. lower.resize(size());
  1397. const char32_t *old_ptr = ptr();
  1398. char32_t *lower_ptrw = lower.ptrw();
  1399. while (*old_ptr) {
  1400. *lower_ptrw++ = _find_lower(*old_ptr++);
  1401. }
  1402. *lower_ptrw = 0;
  1403. return lower;
  1404. }
  1405. String String::chr(char32_t p_char) {
  1406. char32_t c[2] = { p_char, 0 };
  1407. return String(c);
  1408. }
  1409. String String::num(double p_num, int p_decimals) {
  1410. if (Math::is_nan(p_num)) {
  1411. return "nan";
  1412. }
  1413. if (Math::is_inf(p_num)) {
  1414. if (signbit(p_num)) {
  1415. return "-inf";
  1416. } else {
  1417. return "inf";
  1418. }
  1419. }
  1420. if (p_decimals < 0) {
  1421. p_decimals = 14;
  1422. const double abs_num = Math::abs(p_num);
  1423. if (abs_num > 10) {
  1424. // We want to align the digits to the above reasonable default, so we only
  1425. // need to subtract log10 for numbers with a positive power of ten.
  1426. p_decimals -= (int)floor(log10(abs_num));
  1427. }
  1428. }
  1429. if (p_decimals > MAX_DECIMALS) {
  1430. p_decimals = MAX_DECIMALS;
  1431. }
  1432. char fmt[7];
  1433. fmt[0] = '%';
  1434. fmt[1] = '.';
  1435. if (p_decimals < 0) {
  1436. fmt[1] = 'l';
  1437. fmt[2] = 'f';
  1438. fmt[3] = 0;
  1439. } else if (p_decimals < 10) {
  1440. fmt[2] = '0' + p_decimals;
  1441. fmt[3] = 'l';
  1442. fmt[4] = 'f';
  1443. fmt[5] = 0;
  1444. } else {
  1445. fmt[2] = '0' + (p_decimals / 10);
  1446. fmt[3] = '0' + (p_decimals % 10);
  1447. fmt[4] = 'l';
  1448. fmt[5] = 'f';
  1449. fmt[6] = 0;
  1450. }
  1451. // if we want to convert a double with as much decimal places as
  1452. // DBL_MAX or DBL_MIN then we would theoretically need a buffer of at least
  1453. // DBL_MAX_10_EXP + 2 for DBL_MAX and DBL_MAX_10_EXP + 4 for DBL_MIN.
  1454. // BUT those values where still giving me exceptions, so I tested from
  1455. // DBL_MAX_10_EXP + 10 incrementing one by one and DBL_MAX_10_EXP + 17 (325)
  1456. // was the first buffer size not to throw an exception
  1457. char buf[325];
  1458. #if defined(__GNUC__) || defined(_MSC_VER)
  1459. // PLEASE NOTE that, albeit vcrt online reference states that snprintf
  1460. // should safely truncate the output to the given buffer size, we have
  1461. // found a case where this is not true, so we should create a buffer
  1462. // as big as needed
  1463. snprintf(buf, 325, fmt, p_num);
  1464. #else
  1465. sprintf(buf, fmt, p_num);
  1466. #endif
  1467. buf[324] = 0;
  1468. //destroy trailing zeroes
  1469. {
  1470. bool period = false;
  1471. int z = 0;
  1472. while (buf[z]) {
  1473. if (buf[z] == '.') {
  1474. period = true;
  1475. }
  1476. z++;
  1477. }
  1478. if (period) {
  1479. z--;
  1480. while (z > 0) {
  1481. if (buf[z] == '0') {
  1482. buf[z] = 0;
  1483. } else if (buf[z] == '.') {
  1484. buf[z] = 0;
  1485. break;
  1486. } else {
  1487. break;
  1488. }
  1489. z--;
  1490. }
  1491. }
  1492. }
  1493. return buf;
  1494. }
  1495. String String::num_int64(int64_t p_num, int base, bool capitalize_hex) {
  1496. bool sign = p_num < 0;
  1497. int64_t n = p_num;
  1498. int chars = 0;
  1499. do {
  1500. n /= base;
  1501. chars++;
  1502. } while (n);
  1503. if (sign) {
  1504. chars++;
  1505. }
  1506. String s;
  1507. s.resize(chars + 1);
  1508. char32_t *c = s.ptrw();
  1509. c[chars] = 0;
  1510. n = p_num;
  1511. do {
  1512. int mod = ABS(n % base);
  1513. if (mod >= 10) {
  1514. char a = (capitalize_hex ? 'A' : 'a');
  1515. c[--chars] = a + (mod - 10);
  1516. } else {
  1517. c[--chars] = '0' + mod;
  1518. }
  1519. n /= base;
  1520. } while (n);
  1521. if (sign) {
  1522. c[0] = '-';
  1523. }
  1524. return s;
  1525. }
  1526. String String::num_uint64(uint64_t p_num, int base, bool capitalize_hex) {
  1527. uint64_t n = p_num;
  1528. int chars = 0;
  1529. do {
  1530. n /= base;
  1531. chars++;
  1532. } while (n);
  1533. String s;
  1534. s.resize(chars + 1);
  1535. char32_t *c = s.ptrw();
  1536. c[chars] = 0;
  1537. n = p_num;
  1538. do {
  1539. int mod = n % base;
  1540. if (mod >= 10) {
  1541. char a = (capitalize_hex ? 'A' : 'a');
  1542. c[--chars] = a + (mod - 10);
  1543. } else {
  1544. c[--chars] = '0' + mod;
  1545. }
  1546. n /= base;
  1547. } while (n);
  1548. return s;
  1549. }
  1550. String String::num_real(double p_num, bool p_trailing) {
  1551. if (p_num == (double)(int64_t)p_num) {
  1552. if (p_trailing) {
  1553. return num_int64((int64_t)p_num) + ".0";
  1554. } else {
  1555. return num_int64((int64_t)p_num);
  1556. }
  1557. }
  1558. #ifdef REAL_T_IS_DOUBLE
  1559. int decimals = 14;
  1560. #else
  1561. int decimals = 6;
  1562. #endif
  1563. // We want to align the digits to the above sane default, so we only need
  1564. // to subtract log10 for numbers with a positive power of ten magnitude.
  1565. double abs_num = Math::abs(p_num);
  1566. if (abs_num > 10) {
  1567. decimals -= (int)floor(log10(abs_num));
  1568. }
  1569. return num(p_num, decimals);
  1570. }
  1571. String String::num_scientific(double p_num) {
  1572. if (Math::is_nan(p_num)) {
  1573. return "nan";
  1574. }
  1575. if (Math::is_inf(p_num)) {
  1576. if (signbit(p_num)) {
  1577. return "-inf";
  1578. } else {
  1579. return "inf";
  1580. }
  1581. }
  1582. char buf[256];
  1583. #if defined(__GNUC__) || defined(_MSC_VER)
  1584. #if defined(__MINGW32__) && defined(_TWO_DIGIT_EXPONENT) && !defined(_UCRT)
  1585. // MinGW requires _set_output_format() to conform to C99 output for printf
  1586. unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
  1587. #endif
  1588. snprintf(buf, 256, "%lg", p_num);
  1589. #if defined(__MINGW32__) && defined(_TWO_DIGIT_EXPONENT) && !defined(_UCRT)
  1590. _set_output_format(old_exponent_format);
  1591. #endif
  1592. #else
  1593. sprintf(buf, "%.16lg", p_num);
  1594. #endif
  1595. buf[255] = 0;
  1596. return buf;
  1597. }
  1598. String String::md5(const uint8_t *p_md5) {
  1599. return String::hex_encode_buffer(p_md5, 16);
  1600. }
  1601. String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
  1602. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  1603. String ret;
  1604. ret.resize(p_len * 2 + 1);
  1605. char32_t *ret_ptrw = ret.ptrw();
  1606. for (int i = 0; i < p_len; i++) {
  1607. *ret_ptrw++ = hex[p_buffer[i] >> 4];
  1608. *ret_ptrw++ = hex[p_buffer[i] & 0xF];
  1609. }
  1610. *ret_ptrw = 0;
  1611. return ret;
  1612. }
  1613. Vector<uint8_t> String::hex_decode() const {
  1614. ERR_FAIL_COND_V_MSG(length() % 2 != 0, Vector<uint8_t>(), "Hexadecimal string of uneven length.");
  1615. #define HEX_TO_BYTE(m_output, m_index) \
  1616. uint8_t m_output; \
  1617. c = operator[](m_index); \
  1618. if (is_digit(c)) { \
  1619. m_output = c - '0'; \
  1620. } else if (c >= 'a' && c <= 'f') { \
  1621. m_output = c - 'a' + 10; \
  1622. } else if (c >= 'A' && c <= 'F') { \
  1623. m_output = c - 'A' + 10; \
  1624. } else { \
  1625. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Invalid hexadecimal character \"" + chr(c) + "\" at index " + m_index + "."); \
  1626. }
  1627. Vector<uint8_t> out;
  1628. int len = length() / 2;
  1629. out.resize(len);
  1630. uint8_t *out_ptrw = out.ptrw();
  1631. for (int i = 0; i < len; i++) {
  1632. char32_t c;
  1633. HEX_TO_BYTE(first, i * 2);
  1634. HEX_TO_BYTE(second, i * 2 + 1);
  1635. out_ptrw[i] = first * 16 + second;
  1636. }
  1637. return out;
  1638. #undef HEX_TO_BYTE
  1639. }
  1640. void String::print_unicode_error(const String &p_message, bool p_critical) const {
  1641. if (p_critical) {
  1642. print_error(vformat(U"Unicode parsing error, some characters were replaced with � (U+FFFD): %s", p_message));
  1643. } else {
  1644. print_error(vformat("Unicode parsing error: %s", p_message));
  1645. }
  1646. }
  1647. CharString String::ascii(bool p_allow_extended) const {
  1648. if (!length()) {
  1649. return CharString();
  1650. }
  1651. CharString cs;
  1652. cs.resize(size());
  1653. char *cs_ptrw = cs.ptrw();
  1654. const char32_t *this_ptr = ptr();
  1655. for (int i = 0; i < size(); i++) {
  1656. char32_t c = this_ptr[i];
  1657. if ((c <= 0x7f) || (c <= 0xff && p_allow_extended)) {
  1658. cs_ptrw[i] = c;
  1659. } else {
  1660. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as ASCII/Latin-1", (uint32_t)c));
  1661. cs_ptrw[i] = 0x20; // ASCII doesn't have a replacement character like unicode, 0x1a is sometimes used but is kinda arcane.
  1662. }
  1663. }
  1664. return cs;
  1665. }
  1666. String String::utf8(const char *p_utf8, int p_len) {
  1667. String ret;
  1668. ret.parse_utf8(p_utf8, p_len);
  1669. return ret;
  1670. }
  1671. Error String::parse_utf8(const char *p_utf8, int p_len, bool p_skip_cr) {
  1672. if (!p_utf8) {
  1673. return ERR_INVALID_DATA;
  1674. }
  1675. String aux;
  1676. int cstr_size = 0;
  1677. int str_size = 0;
  1678. /* HANDLE BOM (Byte Order Mark) */
  1679. if (p_len < 0 || p_len >= 3) {
  1680. bool has_bom = uint8_t(p_utf8[0]) == 0xef && uint8_t(p_utf8[1]) == 0xbb && uint8_t(p_utf8[2]) == 0xbf;
  1681. if (has_bom) {
  1682. //8-bit encoding, byte order has no meaning in UTF-8, just skip it
  1683. if (p_len >= 0) {
  1684. p_len -= 3;
  1685. }
  1686. p_utf8 += 3;
  1687. }
  1688. }
  1689. bool decode_error = false;
  1690. bool decode_failed = false;
  1691. {
  1692. const char *ptrtmp = p_utf8;
  1693. const char *ptrtmp_limit = p_len >= 0 ? &p_utf8[p_len] : nullptr;
  1694. int skip = 0;
  1695. uint8_t c_start = 0;
  1696. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  1697. #if CHAR_MIN == 0
  1698. uint8_t c = *ptrtmp;
  1699. #else
  1700. uint8_t c = *ptrtmp >= 0 ? *ptrtmp : uint8_t(256 + *ptrtmp);
  1701. #endif
  1702. if (skip == 0) {
  1703. if (p_skip_cr && c == '\r') {
  1704. ptrtmp++;
  1705. continue;
  1706. }
  1707. /* Determine the number of characters in sequence */
  1708. if ((c & 0x80) == 0) {
  1709. skip = 0;
  1710. } else if ((c & 0xe0) == 0xc0) {
  1711. skip = 1;
  1712. } else if ((c & 0xf0) == 0xe0) {
  1713. skip = 2;
  1714. } else if ((c & 0xf8) == 0xf0) {
  1715. skip = 3;
  1716. } else if ((c & 0xfc) == 0xf8) {
  1717. skip = 4;
  1718. } else if ((c & 0xfe) == 0xfc) {
  1719. skip = 5;
  1720. } else {
  1721. skip = 0;
  1722. print_unicode_error(vformat("Invalid UTF-8 leading byte (%x)", c), true);
  1723. decode_failed = true;
  1724. }
  1725. c_start = c;
  1726. if (skip == 1 && (c & 0x1e) == 0) {
  1727. print_unicode_error(vformat("Overlong encoding (%x ...)", c));
  1728. decode_error = true;
  1729. }
  1730. str_size++;
  1731. } else {
  1732. 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)) {
  1733. print_unicode_error(vformat("Overlong encoding (%x %x ...)", c_start, c));
  1734. decode_error = true;
  1735. }
  1736. if (c < 0x80 || c > 0xbf) {
  1737. print_unicode_error(vformat("Invalid UTF-8 continuation byte (%x ... %x ...)", c_start, c), true);
  1738. decode_failed = true;
  1739. skip = 0;
  1740. } else {
  1741. --skip;
  1742. }
  1743. }
  1744. cstr_size++;
  1745. ptrtmp++;
  1746. }
  1747. if (skip) {
  1748. print_unicode_error(vformat("Missing %d UTF-8 continuation byte(s)", skip), true);
  1749. decode_failed = true;
  1750. }
  1751. }
  1752. if (str_size == 0) {
  1753. clear();
  1754. return OK; // empty string
  1755. }
  1756. resize(str_size + 1);
  1757. char32_t *dst = ptrw();
  1758. dst[str_size] = 0;
  1759. int skip = 0;
  1760. uint32_t unichar = 0;
  1761. while (cstr_size) {
  1762. #if CHAR_MIN == 0
  1763. uint8_t c = *p_utf8;
  1764. #else
  1765. uint8_t c = *p_utf8 >= 0 ? *p_utf8 : uint8_t(256 + *p_utf8);
  1766. #endif
  1767. if (skip == 0) {
  1768. if (p_skip_cr && c == '\r') {
  1769. p_utf8++;
  1770. continue;
  1771. }
  1772. /* Determine the number of characters in sequence */
  1773. if ((c & 0x80) == 0) {
  1774. *(dst++) = c;
  1775. unichar = 0;
  1776. skip = 0;
  1777. } else if ((c & 0xe0) == 0xc0) {
  1778. unichar = (0xff >> 3) & c;
  1779. skip = 1;
  1780. } else if ((c & 0xf0) == 0xe0) {
  1781. unichar = (0xff >> 4) & c;
  1782. skip = 2;
  1783. } else if ((c & 0xf8) == 0xf0) {
  1784. unichar = (0xff >> 5) & c;
  1785. skip = 3;
  1786. } else if ((c & 0xfc) == 0xf8) {
  1787. unichar = (0xff >> 6) & c;
  1788. skip = 4;
  1789. } else if ((c & 0xfe) == 0xfc) {
  1790. unichar = (0xff >> 7) & c;
  1791. skip = 5;
  1792. } else {
  1793. *(dst++) = _replacement_char;
  1794. unichar = 0;
  1795. skip = 0;
  1796. }
  1797. } else {
  1798. if (c < 0x80 || c > 0xbf) {
  1799. *(dst++) = _replacement_char;
  1800. skip = 0;
  1801. } else {
  1802. unichar = (unichar << 6) | (c & 0x3f);
  1803. --skip;
  1804. if (skip == 0) {
  1805. if (unichar == 0) {
  1806. print_unicode_error("NUL character", true);
  1807. decode_failed = true;
  1808. unichar = _replacement_char;
  1809. } else if ((unichar & 0xfffff800) == 0xd800) {
  1810. print_unicode_error(vformat("Unpaired surrogate (%x)", unichar), true);
  1811. decode_failed = true;
  1812. unichar = _replacement_char;
  1813. } else if (unichar > 0x10ffff) {
  1814. print_unicode_error(vformat("Invalid unicode codepoint (%x)", unichar), true);
  1815. decode_failed = true;
  1816. unichar = _replacement_char;
  1817. }
  1818. *(dst++) = unichar;
  1819. }
  1820. }
  1821. }
  1822. cstr_size--;
  1823. p_utf8++;
  1824. }
  1825. if (skip) {
  1826. *(dst++) = 0x20;
  1827. }
  1828. if (decode_failed) {
  1829. return ERR_INVALID_DATA;
  1830. } else if (decode_error) {
  1831. return ERR_PARSE_ERROR;
  1832. } else {
  1833. return OK;
  1834. }
  1835. }
  1836. CharString String::utf8() const {
  1837. int l = length();
  1838. if (!l) {
  1839. return CharString();
  1840. }
  1841. const char32_t *d = &operator[](0);
  1842. int fl = 0;
  1843. for (int i = 0; i < l; i++) {
  1844. uint32_t c = d[i];
  1845. if (c <= 0x7f) { // 7 bits.
  1846. fl += 1;
  1847. } else if (c <= 0x7ff) { // 11 bits
  1848. fl += 2;
  1849. } else if (c <= 0xffff) { // 16 bits
  1850. fl += 3;
  1851. } else if (c <= 0x001fffff) { // 21 bits
  1852. fl += 4;
  1853. } else if (c <= 0x03ffffff) { // 26 bits
  1854. fl += 5;
  1855. print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
  1856. } else if (c <= 0x7fffffff) { // 31 bits
  1857. fl += 6;
  1858. print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
  1859. } else {
  1860. fl += 1;
  1861. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-8", c), true);
  1862. }
  1863. }
  1864. CharString utf8s;
  1865. if (fl == 0) {
  1866. return utf8s;
  1867. }
  1868. utf8s.resize(fl + 1);
  1869. uint8_t *cdst = (uint8_t *)utf8s.get_data();
  1870. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1871. for (int i = 0; i < l; i++) {
  1872. uint32_t c = d[i];
  1873. if (c <= 0x7f) { // 7 bits.
  1874. APPEND_CHAR(c);
  1875. } else if (c <= 0x7ff) { // 11 bits
  1876. APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits.
  1877. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1878. } else if (c <= 0xffff) { // 16 bits
  1879. APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits.
  1880. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits.
  1881. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1882. } else if (c <= 0x001fffff) { // 21 bits
  1883. APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits.
  1884. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits.
  1885. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1886. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1887. } else if (c <= 0x03ffffff) { // 26 bits
  1888. APPEND_CHAR(uint32_t(0xf8 | ((c >> 24) & 0x03))); // Top 2 bits.
  1889. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Upper middle 6 bits.
  1890. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // middle 6 bits.
  1891. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1892. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1893. } else if (c <= 0x7fffffff) { // 31 bits
  1894. APPEND_CHAR(uint32_t(0xfc | ((c >> 30) & 0x01))); // Top 1 bit.
  1895. APPEND_CHAR(uint32_t(0x80 | ((c >> 24) & 0x3f))); // Upper upper middle 6 bits.
  1896. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Lower upper middle 6 bits.
  1897. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper lower middle 6 bits.
  1898. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower lower middle 6 bits.
  1899. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1900. } else {
  1901. // the string is a valid UTF32, so it should never happen ...
  1902. print_unicode_error(vformat("Non scalar value (%x)", c), true);
  1903. APPEND_CHAR(uint32_t(0xe0 | ((_replacement_char >> 12) & 0x0f))); // Top 4 bits.
  1904. APPEND_CHAR(uint32_t(0x80 | ((_replacement_char >> 6) & 0x3f))); // Middle 6 bits.
  1905. APPEND_CHAR(uint32_t(0x80 | (_replacement_char & 0x3f))); // Bottom 6 bits.
  1906. }
  1907. }
  1908. #undef APPEND_CHAR
  1909. *cdst = 0; //trailing zero
  1910. return utf8s;
  1911. }
  1912. String String::utf16(const char16_t *p_utf16, int p_len) {
  1913. String ret;
  1914. ret.parse_utf16(p_utf16, p_len, true);
  1915. return ret;
  1916. }
  1917. Error String::parse_utf16(const char16_t *p_utf16, int p_len, bool p_default_little_endian) {
  1918. if (!p_utf16) {
  1919. return ERR_INVALID_DATA;
  1920. }
  1921. String aux;
  1922. int cstr_size = 0;
  1923. int str_size = 0;
  1924. #ifdef BIG_ENDIAN_ENABLED
  1925. bool byteswap = p_default_little_endian;
  1926. #else
  1927. bool byteswap = !p_default_little_endian;
  1928. #endif
  1929. /* HANDLE BOM (Byte Order Mark) */
  1930. if (p_len < 0 || p_len >= 1) {
  1931. bool has_bom = false;
  1932. if (uint16_t(p_utf16[0]) == 0xfeff) { // correct BOM, read as is
  1933. has_bom = true;
  1934. byteswap = false;
  1935. } else if (uint16_t(p_utf16[0]) == 0xfffe) { // backwards BOM, swap bytes
  1936. has_bom = true;
  1937. byteswap = true;
  1938. }
  1939. if (has_bom) {
  1940. if (p_len >= 0) {
  1941. p_len -= 1;
  1942. }
  1943. p_utf16 += 1;
  1944. }
  1945. }
  1946. bool decode_error = false;
  1947. {
  1948. const char16_t *ptrtmp = p_utf16;
  1949. const char16_t *ptrtmp_limit = p_len >= 0 ? &p_utf16[p_len] : nullptr;
  1950. uint32_t c_prev = 0;
  1951. bool skip = false;
  1952. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  1953. uint32_t c = (byteswap) ? BSWAP16(*ptrtmp) : *ptrtmp;
  1954. if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
  1955. if (skip) {
  1956. print_unicode_error(vformat("Unpaired lead surrogate (%x [trail?] %x)", c_prev, c));
  1957. decode_error = true;
  1958. }
  1959. skip = true;
  1960. } else if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
  1961. if (skip) {
  1962. str_size--;
  1963. } else {
  1964. print_unicode_error(vformat("Unpaired trail surrogate (%x [lead?] %x)", c_prev, c));
  1965. decode_error = true;
  1966. }
  1967. skip = false;
  1968. } else {
  1969. skip = false;
  1970. }
  1971. c_prev = c;
  1972. str_size++;
  1973. cstr_size++;
  1974. ptrtmp++;
  1975. }
  1976. if (skip) {
  1977. print_unicode_error(vformat("Unpaired lead surrogate (%x [eol])", c_prev));
  1978. decode_error = true;
  1979. }
  1980. }
  1981. if (str_size == 0) {
  1982. clear();
  1983. return OK; // empty string
  1984. }
  1985. resize(str_size + 1);
  1986. char32_t *dst = ptrw();
  1987. dst[str_size] = 0;
  1988. bool skip = false;
  1989. uint32_t c_prev = 0;
  1990. while (cstr_size) {
  1991. uint32_t c = (byteswap) ? BSWAP16(*p_utf16) : *p_utf16;
  1992. if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
  1993. if (skip) {
  1994. *(dst++) = c_prev; // unpaired, store as is
  1995. }
  1996. skip = true;
  1997. } else if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
  1998. if (skip) {
  1999. *(dst++) = (c_prev << 10UL) + c - ((0xd800 << 10UL) + 0xdc00 - 0x10000); // decode pair
  2000. } else {
  2001. *(dst++) = c; // unpaired, store as is
  2002. }
  2003. skip = false;
  2004. } else {
  2005. *(dst++) = c;
  2006. skip = false;
  2007. }
  2008. cstr_size--;
  2009. p_utf16++;
  2010. c_prev = c;
  2011. }
  2012. if (skip) {
  2013. *(dst++) = c_prev;
  2014. }
  2015. if (decode_error) {
  2016. return ERR_PARSE_ERROR;
  2017. } else {
  2018. return OK;
  2019. }
  2020. }
  2021. Char16String String::utf16() const {
  2022. int l = length();
  2023. if (!l) {
  2024. return Char16String();
  2025. }
  2026. const char32_t *d = &operator[](0);
  2027. int fl = 0;
  2028. for (int i = 0; i < l; i++) {
  2029. uint32_t c = d[i];
  2030. if (c <= 0xffff) { // 16 bits.
  2031. fl += 1;
  2032. if ((c & 0xfffff800) == 0xd800) {
  2033. print_unicode_error(vformat("Unpaired surrogate (%x)", c));
  2034. }
  2035. } else if (c <= 0x10ffff) { // 32 bits.
  2036. fl += 2;
  2037. } else {
  2038. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-16", c), true);
  2039. fl += 1;
  2040. }
  2041. }
  2042. Char16String utf16s;
  2043. if (fl == 0) {
  2044. return utf16s;
  2045. }
  2046. utf16s.resize(fl + 1);
  2047. uint16_t *cdst = (uint16_t *)utf16s.get_data();
  2048. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  2049. for (int i = 0; i < l; i++) {
  2050. uint32_t c = d[i];
  2051. if (c <= 0xffff) { // 16 bits.
  2052. APPEND_CHAR(c);
  2053. } else if (c <= 0x10ffff) { // 32 bits.
  2054. APPEND_CHAR(uint32_t((c >> 10) + 0xd7c0)); // lead surrogate.
  2055. APPEND_CHAR(uint32_t((c & 0x3ff) | 0xdc00)); // trail surrogate.
  2056. } else {
  2057. // the string is a valid UTF32, so it should never happen ...
  2058. APPEND_CHAR(uint32_t((_replacement_char >> 10) + 0xd7c0));
  2059. APPEND_CHAR(uint32_t((_replacement_char & 0x3ff) | 0xdc00));
  2060. }
  2061. }
  2062. #undef APPEND_CHAR
  2063. *cdst = 0; //trailing zero
  2064. return utf16s;
  2065. }
  2066. String::String(const char *p_str) {
  2067. copy_from(p_str);
  2068. }
  2069. String::String(const wchar_t *p_str) {
  2070. copy_from(p_str);
  2071. }
  2072. String::String(const char32_t *p_str) {
  2073. copy_from(p_str);
  2074. }
  2075. String::String(const char *p_str, int p_clip_to_len) {
  2076. copy_from(p_str, p_clip_to_len);
  2077. }
  2078. String::String(const wchar_t *p_str, int p_clip_to_len) {
  2079. copy_from(p_str, p_clip_to_len);
  2080. }
  2081. String::String(const char32_t *p_str, int p_clip_to_len) {
  2082. copy_from(p_str, p_clip_to_len);
  2083. }
  2084. String::String(const StrRange &p_range) {
  2085. if (!p_range.c_str) {
  2086. return;
  2087. }
  2088. copy_from(p_range.c_str, p_range.len);
  2089. }
  2090. int64_t String::hex_to_int() const {
  2091. int len = length();
  2092. if (len == 0) {
  2093. return 0;
  2094. }
  2095. const char32_t *s = ptr();
  2096. int64_t sign = s[0] == '-' ? -1 : 1;
  2097. if (sign < 0) {
  2098. s++;
  2099. }
  2100. if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'x') {
  2101. s += 2;
  2102. }
  2103. int64_t hex = 0;
  2104. while (*s) {
  2105. char32_t c = lower_case(*s);
  2106. int64_t n;
  2107. if (is_digit(c)) {
  2108. n = c - '0';
  2109. } else if (c >= 'a' && c <= 'f') {
  2110. n = (c - 'a') + 10;
  2111. } else {
  2112. ERR_FAIL_V_MSG(0, vformat(R"(Invalid hexadecimal notation character "%c" (U+%04X) in string "%s".)", *s, static_cast<int32_t>(*s), *this));
  2113. }
  2114. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  2115. bool overflow = ((hex > INT64_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT64_MAX >> 4) + 1))) || (sign == -1 && hex == (INT64_MAX >> 4) + 1 && c > '0');
  2116. 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."));
  2117. hex *= 16;
  2118. hex += n;
  2119. s++;
  2120. }
  2121. return hex * sign;
  2122. }
  2123. int64_t String::bin_to_int() const {
  2124. int len = length();
  2125. if (len == 0) {
  2126. return 0;
  2127. }
  2128. const char32_t *s = ptr();
  2129. int64_t sign = s[0] == '-' ? -1 : 1;
  2130. if (sign < 0) {
  2131. s++;
  2132. }
  2133. if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'b') {
  2134. s += 2;
  2135. }
  2136. int64_t binary = 0;
  2137. while (*s) {
  2138. char32_t c = lower_case(*s);
  2139. int64_t n;
  2140. if (c == '0' || c == '1') {
  2141. n = c - '0';
  2142. } else {
  2143. return 0;
  2144. }
  2145. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  2146. bool overflow = ((binary > INT64_MAX / 2) && (sign == 1 || (sign == -1 && binary != (INT64_MAX >> 1) + 1))) || (sign == -1 && binary == (INT64_MAX >> 1) + 1 && c > '0');
  2147. 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."));
  2148. binary *= 2;
  2149. binary += n;
  2150. s++;
  2151. }
  2152. return binary * sign;
  2153. }
  2154. int64_t String::to_int() const {
  2155. if (length() == 0) {
  2156. return 0;
  2157. }
  2158. int to = (find(".") >= 0) ? find(".") : length();
  2159. int64_t integer = 0;
  2160. int64_t sign = 1;
  2161. for (int i = 0; i < to; i++) {
  2162. char32_t c = operator[](i);
  2163. if (is_digit(c)) {
  2164. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  2165. 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."));
  2166. integer *= 10;
  2167. integer += c - '0';
  2168. } else if (integer == 0 && c == '-') {
  2169. sign = -sign;
  2170. }
  2171. }
  2172. return integer * sign;
  2173. }
  2174. int64_t String::to_int(const char *p_str, int p_len) {
  2175. int to = 0;
  2176. if (p_len >= 0) {
  2177. to = p_len;
  2178. } else {
  2179. while (p_str[to] != 0 && p_str[to] != '.') {
  2180. to++;
  2181. }
  2182. }
  2183. int64_t integer = 0;
  2184. int64_t sign = 1;
  2185. for (int i = 0; i < to; i++) {
  2186. char c = p_str[i];
  2187. if (is_digit(c)) {
  2188. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  2189. 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."));
  2190. integer *= 10;
  2191. integer += c - '0';
  2192. } else if (c == '-' && integer == 0) {
  2193. sign = -sign;
  2194. } else if (c != ' ') {
  2195. break;
  2196. }
  2197. }
  2198. return integer * sign;
  2199. }
  2200. int64_t String::to_int(const wchar_t *p_str, int p_len) {
  2201. int to = 0;
  2202. if (p_len >= 0) {
  2203. to = p_len;
  2204. } else {
  2205. while (p_str[to] != 0 && p_str[to] != '.') {
  2206. to++;
  2207. }
  2208. }
  2209. int64_t integer = 0;
  2210. int64_t sign = 1;
  2211. for (int i = 0; i < to; i++) {
  2212. wchar_t c = p_str[i];
  2213. if (is_digit(c)) {
  2214. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  2215. 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."));
  2216. integer *= 10;
  2217. integer += c - '0';
  2218. } else if (c == '-' && integer == 0) {
  2219. sign = -sign;
  2220. } else if (c != ' ') {
  2221. break;
  2222. }
  2223. }
  2224. return integer * sign;
  2225. }
  2226. bool String::is_numeric() const {
  2227. if (length() == 0) {
  2228. return false;
  2229. }
  2230. int s = 0;
  2231. if (operator[](0) == '-') {
  2232. ++s;
  2233. }
  2234. bool dot = false;
  2235. for (int i = s; i < length(); i++) {
  2236. char32_t c = operator[](i);
  2237. if (c == '.') {
  2238. if (dot) {
  2239. return false;
  2240. }
  2241. dot = true;
  2242. } else if (!is_digit(c)) {
  2243. return false;
  2244. }
  2245. }
  2246. return true; // TODO: Use the parser below for this instead
  2247. }
  2248. template <typename C>
  2249. static double built_in_strtod(
  2250. /* A decimal ASCII floating-point number,
  2251. * optionally preceded by white space. Must
  2252. * have form "-I.FE-X", where I is the integer
  2253. * part of the mantissa, F is the fractional
  2254. * part of the mantissa, and X is the
  2255. * exponent. Either of the signs may be "+",
  2256. * "-", or omitted. Either I or F may be
  2257. * omitted, or both. The decimal point isn't
  2258. * necessary unless F is present. The "E" may
  2259. * actually be an "e". E and X may both be
  2260. * omitted (but not just one). */
  2261. const C *string,
  2262. /* If non-nullptr, store terminating Cacter's
  2263. * address here. */
  2264. C **endPtr = nullptr) {
  2265. /* Largest possible base 10 exponent. Any
  2266. * exponent larger than this will already
  2267. * produce underflow or overflow, so there's
  2268. * no need to worry about additional digits. */
  2269. static const int maxExponent = 511;
  2270. /* Table giving binary powers of 10. Entry
  2271. * is 10^2^i. Used to convert decimal
  2272. * exponents into floating-point numbers. */
  2273. static const double powersOf10[] = {
  2274. 10.,
  2275. 100.,
  2276. 1.0e4,
  2277. 1.0e8,
  2278. 1.0e16,
  2279. 1.0e32,
  2280. 1.0e64,
  2281. 1.0e128,
  2282. 1.0e256
  2283. };
  2284. bool sign, expSign = false;
  2285. double fraction, dblExp;
  2286. const double *d;
  2287. const C *p;
  2288. int c;
  2289. /* Exponent read from "EX" field. */
  2290. int exp = 0;
  2291. /* Exponent that derives from the fractional
  2292. * part. Under normal circumstances, it is
  2293. * the negative of the number of digits in F.
  2294. * However, if I is very long, the last digits
  2295. * of I get dropped (otherwise a long I with a
  2296. * large negative exponent could cause an
  2297. * unnecessary overflow on I alone). In this
  2298. * case, fracExp is incremented one for each
  2299. * dropped digit. */
  2300. int fracExp = 0;
  2301. /* Number of digits in mantissa. */
  2302. int mantSize;
  2303. /* Number of mantissa digits BEFORE decimal point. */
  2304. int decPt;
  2305. /* Temporarily holds location of exponent in string. */
  2306. const C *pExp;
  2307. /*
  2308. * Strip off leading blanks and check for a sign.
  2309. */
  2310. p = string;
  2311. while (*p == ' ' || *p == '\t' || *p == '\n') {
  2312. p += 1;
  2313. }
  2314. if (*p == '-') {
  2315. sign = true;
  2316. p += 1;
  2317. } else {
  2318. if (*p == '+') {
  2319. p += 1;
  2320. }
  2321. sign = false;
  2322. }
  2323. /*
  2324. * Count the number of digits in the mantissa (including the decimal
  2325. * point), and also locate the decimal point.
  2326. */
  2327. decPt = -1;
  2328. for (mantSize = 0;; mantSize += 1) {
  2329. c = *p;
  2330. if (!is_digit(c)) {
  2331. if ((c != '.') || (decPt >= 0)) {
  2332. break;
  2333. }
  2334. decPt = mantSize;
  2335. }
  2336. p += 1;
  2337. }
  2338. /*
  2339. * Now suck up the digits in the mantissa. Use two integers to collect 9
  2340. * digits each (this is faster than using floating-point). If the mantissa
  2341. * has more than 18 digits, ignore the extras, since they can't affect the
  2342. * value anyway.
  2343. */
  2344. pExp = p;
  2345. p -= mantSize;
  2346. if (decPt < 0) {
  2347. decPt = mantSize;
  2348. } else {
  2349. mantSize -= 1; /* One of the digits was the point. */
  2350. }
  2351. if (mantSize > 18) {
  2352. fracExp = decPt - 18;
  2353. mantSize = 18;
  2354. } else {
  2355. fracExp = decPt - mantSize;
  2356. }
  2357. if (mantSize == 0) {
  2358. fraction = 0.0;
  2359. p = string;
  2360. goto done;
  2361. } else {
  2362. int frac1, frac2;
  2363. frac1 = 0;
  2364. for (; mantSize > 9; mantSize -= 1) {
  2365. c = *p;
  2366. p += 1;
  2367. if (c == '.') {
  2368. c = *p;
  2369. p += 1;
  2370. }
  2371. frac1 = 10 * frac1 + (c - '0');
  2372. }
  2373. frac2 = 0;
  2374. for (; mantSize > 0; mantSize -= 1) {
  2375. c = *p;
  2376. p += 1;
  2377. if (c == '.') {
  2378. c = *p;
  2379. p += 1;
  2380. }
  2381. frac2 = 10 * frac2 + (c - '0');
  2382. }
  2383. fraction = (1.0e9 * frac1) + frac2;
  2384. }
  2385. /*
  2386. * Skim off the exponent.
  2387. */
  2388. p = pExp;
  2389. if ((*p == 'E') || (*p == 'e')) {
  2390. p += 1;
  2391. if (*p == '-') {
  2392. expSign = true;
  2393. p += 1;
  2394. } else {
  2395. if (*p == '+') {
  2396. p += 1;
  2397. }
  2398. expSign = false;
  2399. }
  2400. if (!is_digit(char32_t(*p))) {
  2401. p = pExp;
  2402. goto done;
  2403. }
  2404. while (is_digit(char32_t(*p))) {
  2405. exp = exp * 10 + (*p - '0');
  2406. p += 1;
  2407. }
  2408. }
  2409. if (expSign) {
  2410. exp = fracExp - exp;
  2411. } else {
  2412. exp = fracExp + exp;
  2413. }
  2414. /*
  2415. * Generate a floating-point number that represents the exponent. Do this
  2416. * by processing the exponent one bit at a time to combine many powers of
  2417. * 2 of 10. Then combine the exponent with the fraction.
  2418. */
  2419. if (exp < 0) {
  2420. expSign = true;
  2421. exp = -exp;
  2422. } else {
  2423. expSign = false;
  2424. }
  2425. if (exp > maxExponent) {
  2426. exp = maxExponent;
  2427. WARN_PRINT("Exponent too high");
  2428. }
  2429. dblExp = 1.0;
  2430. for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
  2431. if (exp & 01) {
  2432. dblExp *= *d;
  2433. }
  2434. }
  2435. if (expSign) {
  2436. fraction /= dblExp;
  2437. } else {
  2438. fraction *= dblExp;
  2439. }
  2440. done:
  2441. if (endPtr != nullptr) {
  2442. *endPtr = (C *)p;
  2443. }
  2444. if (sign) {
  2445. return -fraction;
  2446. }
  2447. return fraction;
  2448. }
  2449. #define READING_SIGN 0
  2450. #define READING_INT 1
  2451. #define READING_DEC 2
  2452. #define READING_EXP 3
  2453. #define READING_DONE 4
  2454. double String::to_float(const char *p_str) {
  2455. return built_in_strtod<char>(p_str);
  2456. }
  2457. double String::to_float(const char32_t *p_str, const char32_t **r_end) {
  2458. return built_in_strtod<char32_t>(p_str, (char32_t **)r_end);
  2459. }
  2460. double String::to_float(const wchar_t *p_str, const wchar_t **r_end) {
  2461. return built_in_strtod<wchar_t>(p_str, (wchar_t **)r_end);
  2462. }
  2463. uint32_t String::num_characters(int64_t p_int) {
  2464. int r = 1;
  2465. if (p_int < 0) {
  2466. r += 1;
  2467. if (p_int == INT64_MIN) {
  2468. p_int = INT64_MAX;
  2469. } else {
  2470. p_int = -p_int;
  2471. }
  2472. }
  2473. while (p_int >= 10) {
  2474. p_int /= 10;
  2475. r++;
  2476. }
  2477. return r;
  2478. }
  2479. int64_t String::to_int(const char32_t *p_str, int p_len, bool p_clamp) {
  2480. if (p_len == 0 || !p_str[0]) {
  2481. return 0;
  2482. }
  2483. ///@todo make more exact so saving and loading does not lose precision
  2484. int64_t integer = 0;
  2485. int64_t sign = 1;
  2486. int reading = READING_SIGN;
  2487. const char32_t *str = p_str;
  2488. const char32_t *limit = &p_str[p_len];
  2489. while (*str && reading != READING_DONE && str != limit) {
  2490. char32_t c = *(str++);
  2491. switch (reading) {
  2492. case READING_SIGN: {
  2493. if (is_digit(c)) {
  2494. reading = READING_INT;
  2495. // let it fallthrough
  2496. } else if (c == '-') {
  2497. sign = -1;
  2498. reading = READING_INT;
  2499. break;
  2500. } else if (c == '+') {
  2501. sign = 1;
  2502. reading = READING_INT;
  2503. break;
  2504. } else {
  2505. break;
  2506. }
  2507. [[fallthrough]];
  2508. }
  2509. case READING_INT: {
  2510. if (is_digit(c)) {
  2511. if (integer > INT64_MAX / 10) {
  2512. String number("");
  2513. str = p_str;
  2514. while (*str && str != limit) {
  2515. number += *(str++);
  2516. }
  2517. if (p_clamp) {
  2518. if (sign == 1) {
  2519. return INT64_MAX;
  2520. } else {
  2521. return INT64_MIN;
  2522. }
  2523. } else {
  2524. 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."));
  2525. }
  2526. }
  2527. integer *= 10;
  2528. integer += c - '0';
  2529. } else {
  2530. reading = READING_DONE;
  2531. }
  2532. } break;
  2533. }
  2534. }
  2535. return sign * integer;
  2536. }
  2537. double String::to_float() const {
  2538. if (is_empty()) {
  2539. return 0;
  2540. }
  2541. return built_in_strtod<char32_t>(get_data());
  2542. }
  2543. uint32_t String::hash(const char *p_cstr) {
  2544. // static_cast: avoid negative values on platforms where char is signed.
  2545. uint32_t hashv = 5381;
  2546. uint32_t c = static_cast<uint8_t>(*p_cstr++);
  2547. while (c) {
  2548. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2549. c = static_cast<uint8_t>(*p_cstr++);
  2550. }
  2551. return hashv;
  2552. }
  2553. uint32_t String::hash(const char *p_cstr, int p_len) {
  2554. uint32_t hashv = 5381;
  2555. for (int i = 0; i < p_len; i++) {
  2556. // static_cast: avoid negative values on platforms where char is signed.
  2557. hashv = ((hashv << 5) + hashv) + static_cast<uint8_t>(p_cstr[i]); /* hash * 33 + c */
  2558. }
  2559. return hashv;
  2560. }
  2561. uint32_t String::hash(const wchar_t *p_cstr, int p_len) {
  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. for (int i = 0; i < p_len; i++) {
  2566. hashv = ((hashv << 5) + hashv) + static_cast<wide_unsigned>(p_cstr[i]); /* hash * 33 + c */
  2567. }
  2568. return hashv;
  2569. }
  2570. uint32_t String::hash(const wchar_t *p_cstr) {
  2571. // Avoid negative values on platforms where wchar_t is signed. Account for different sizes.
  2572. using wide_unsigned = std::conditional<sizeof(wchar_t) == 2, uint16_t, uint32_t>::type;
  2573. uint32_t hashv = 5381;
  2574. uint32_t c = static_cast<wide_unsigned>(*p_cstr++);
  2575. while (c) {
  2576. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2577. c = static_cast<wide_unsigned>(*p_cstr++);
  2578. }
  2579. return hashv;
  2580. }
  2581. uint32_t String::hash(const char32_t *p_cstr, int p_len) {
  2582. uint32_t hashv = 5381;
  2583. for (int i = 0; i < p_len; i++) {
  2584. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  2585. }
  2586. return hashv;
  2587. }
  2588. uint32_t String::hash(const char32_t *p_cstr) {
  2589. uint32_t hashv = 5381;
  2590. uint32_t c = *p_cstr++;
  2591. while (c) {
  2592. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2593. c = *p_cstr++;
  2594. }
  2595. return hashv;
  2596. }
  2597. uint32_t String::hash() const {
  2598. /* simple djb2 hashing */
  2599. const char32_t *chr = get_data();
  2600. uint32_t hashv = 5381;
  2601. uint32_t c = *chr++;
  2602. while (c) {
  2603. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2604. c = *chr++;
  2605. }
  2606. return hashv;
  2607. }
  2608. uint64_t String::hash64() const {
  2609. /* simple djb2 hashing */
  2610. const char32_t *chr = get_data();
  2611. uint64_t hashv = 5381;
  2612. uint64_t c = *chr++;
  2613. while (c) {
  2614. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2615. c = *chr++;
  2616. }
  2617. return hashv;
  2618. }
  2619. String String::md5_text() const {
  2620. CharString cs = utf8();
  2621. unsigned char hash[16];
  2622. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  2623. return String::hex_encode_buffer(hash, 16);
  2624. }
  2625. String String::sha1_text() const {
  2626. CharString cs = utf8();
  2627. unsigned char hash[20];
  2628. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  2629. return String::hex_encode_buffer(hash, 20);
  2630. }
  2631. String String::sha256_text() const {
  2632. CharString cs = utf8();
  2633. unsigned char hash[32];
  2634. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  2635. return String::hex_encode_buffer(hash, 32);
  2636. }
  2637. Vector<uint8_t> String::md5_buffer() const {
  2638. CharString cs = utf8();
  2639. unsigned char hash[16];
  2640. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  2641. Vector<uint8_t> ret;
  2642. ret.resize(16);
  2643. uint8_t *ret_ptrw = ret.ptrw();
  2644. for (int i = 0; i < 16; i++) {
  2645. ret_ptrw[i] = hash[i];
  2646. }
  2647. return ret;
  2648. }
  2649. Vector<uint8_t> String::sha1_buffer() const {
  2650. CharString cs = utf8();
  2651. unsigned char hash[20];
  2652. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  2653. Vector<uint8_t> ret;
  2654. ret.resize(20);
  2655. uint8_t *ret_ptrw = ret.ptrw();
  2656. for (int i = 0; i < 20; i++) {
  2657. ret_ptrw[i] = hash[i];
  2658. }
  2659. return ret;
  2660. }
  2661. Vector<uint8_t> String::sha256_buffer() const {
  2662. CharString cs = utf8();
  2663. unsigned char hash[32];
  2664. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  2665. Vector<uint8_t> ret;
  2666. ret.resize(32);
  2667. uint8_t *ret_ptrw = ret.ptrw();
  2668. for (int i = 0; i < 32; i++) {
  2669. ret_ptrw[i] = hash[i];
  2670. }
  2671. return ret;
  2672. }
  2673. String String::insert(int p_at_pos, const String &p_string) const {
  2674. if (p_at_pos < 0) {
  2675. return *this;
  2676. }
  2677. if (p_at_pos > length()) {
  2678. p_at_pos = length();
  2679. }
  2680. String pre;
  2681. if (p_at_pos > 0) {
  2682. pre = substr(0, p_at_pos);
  2683. }
  2684. String post;
  2685. if (p_at_pos < length()) {
  2686. post = substr(p_at_pos, length() - p_at_pos);
  2687. }
  2688. return pre + p_string + post;
  2689. }
  2690. String String::erase(int p_pos, int p_chars) const {
  2691. 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));
  2692. 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));
  2693. return left(p_pos) + substr(p_pos + p_chars);
  2694. }
  2695. String String::substr(int p_from, int p_chars) const {
  2696. if (p_chars == -1) {
  2697. p_chars = length() - p_from;
  2698. }
  2699. if (is_empty() || p_from < 0 || p_from >= length() || p_chars <= 0) {
  2700. return "";
  2701. }
  2702. if ((p_from + p_chars) > length()) {
  2703. p_chars = length() - p_from;
  2704. }
  2705. if (p_from == 0 && p_chars >= length()) {
  2706. return String(*this);
  2707. }
  2708. String s;
  2709. s.copy_from_unchecked(&get_data()[p_from], p_chars);
  2710. return s;
  2711. }
  2712. int String::find(const String &p_str, int p_from) const {
  2713. if (p_from < 0) {
  2714. return -1;
  2715. }
  2716. const int src_len = p_str.length();
  2717. const int len = length();
  2718. if (src_len == 0 || len == 0) {
  2719. return -1; // won't find anything!
  2720. }
  2721. const char32_t *src = get_data();
  2722. const char32_t *str = p_str.get_data();
  2723. for (int i = p_from; i <= (len - src_len); i++) {
  2724. bool found = true;
  2725. for (int j = 0; j < src_len; j++) {
  2726. int read_pos = i + j;
  2727. if (read_pos >= len) {
  2728. ERR_PRINT("read_pos>=len");
  2729. return -1;
  2730. }
  2731. if (src[read_pos] != str[j]) {
  2732. found = false;
  2733. break;
  2734. }
  2735. }
  2736. if (found) {
  2737. return i;
  2738. }
  2739. }
  2740. return -1;
  2741. }
  2742. int String::find(const char *p_str, int p_from) const {
  2743. if (p_from < 0 || !p_str) {
  2744. return -1;
  2745. }
  2746. const int src_len = strlen(p_str);
  2747. const int len = length();
  2748. if (len == 0 || src_len == 0) {
  2749. return -1; // won't find anything!
  2750. }
  2751. const char32_t *src = get_data();
  2752. if (src_len == 1) {
  2753. const char32_t needle = p_str[0];
  2754. for (int i = p_from; i < len; i++) {
  2755. if (src[i] == needle) {
  2756. return i;
  2757. }
  2758. }
  2759. } else {
  2760. for (int i = p_from; i <= (len - src_len); i++) {
  2761. bool found = true;
  2762. for (int j = 0; j < src_len; j++) {
  2763. int read_pos = i + j;
  2764. if (read_pos >= len) {
  2765. ERR_PRINT("read_pos>=len");
  2766. return -1;
  2767. }
  2768. if (src[read_pos] != (char32_t)p_str[j]) {
  2769. found = false;
  2770. break;
  2771. }
  2772. }
  2773. if (found) {
  2774. return i;
  2775. }
  2776. }
  2777. }
  2778. return -1;
  2779. }
  2780. int String::find_char(const char32_t &p_char, int p_from) const {
  2781. return _cowdata.find(p_char, p_from);
  2782. }
  2783. int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
  2784. if (p_from < 0) {
  2785. return -1;
  2786. }
  2787. if (p_keys.size() == 0) {
  2788. return -1;
  2789. }
  2790. //int src_len=p_str.length();
  2791. const String *keys = &p_keys[0];
  2792. int key_count = p_keys.size();
  2793. int len = length();
  2794. if (len == 0) {
  2795. return -1; // won't find anything!
  2796. }
  2797. const char32_t *src = get_data();
  2798. for (int i = p_from; i < len; i++) {
  2799. bool found = true;
  2800. for (int k = 0; k < key_count; k++) {
  2801. found = true;
  2802. if (r_key) {
  2803. *r_key = k;
  2804. }
  2805. const char32_t *cmp = keys[k].get_data();
  2806. int l = keys[k].length();
  2807. for (int j = 0; j < l; j++) {
  2808. int read_pos = i + j;
  2809. if (read_pos >= len) {
  2810. found = false;
  2811. break;
  2812. }
  2813. if (src[read_pos] != cmp[j]) {
  2814. found = false;
  2815. break;
  2816. }
  2817. }
  2818. if (found) {
  2819. break;
  2820. }
  2821. }
  2822. if (found) {
  2823. return i;
  2824. }
  2825. }
  2826. return -1;
  2827. }
  2828. int String::findn(const String &p_str, int p_from) const {
  2829. if (p_from < 0) {
  2830. return -1;
  2831. }
  2832. int src_len = p_str.length();
  2833. if (src_len == 0 || length() == 0) {
  2834. return -1; // won't find anything!
  2835. }
  2836. const char32_t *srcd = get_data();
  2837. for (int i = p_from; i <= (length() - src_len); i++) {
  2838. bool found = true;
  2839. for (int j = 0; j < src_len; j++) {
  2840. int read_pos = i + j;
  2841. if (read_pos >= length()) {
  2842. ERR_PRINT("read_pos>=length()");
  2843. return -1;
  2844. }
  2845. char32_t src = _find_lower(srcd[read_pos]);
  2846. char32_t dst = _find_lower(p_str[j]);
  2847. if (src != dst) {
  2848. found = false;
  2849. break;
  2850. }
  2851. }
  2852. if (found) {
  2853. return i;
  2854. }
  2855. }
  2856. return -1;
  2857. }
  2858. int String::findn(const char *p_str, int p_from) const {
  2859. if (p_from < 0) {
  2860. return -1;
  2861. }
  2862. int src_len = strlen(p_str);
  2863. if (src_len == 0 || length() == 0) {
  2864. return -1; // won't find anything!
  2865. }
  2866. const char32_t *srcd = get_data();
  2867. for (int i = p_from; i <= (length() - src_len); i++) {
  2868. bool found = true;
  2869. for (int j = 0; j < src_len; j++) {
  2870. int read_pos = i + j;
  2871. if (read_pos >= length()) {
  2872. ERR_PRINT("read_pos>=length()");
  2873. return -1;
  2874. }
  2875. char32_t src = _find_lower(srcd[read_pos]);
  2876. char32_t dst = _find_lower(p_str[j]);
  2877. if (src != dst) {
  2878. found = false;
  2879. break;
  2880. }
  2881. }
  2882. if (found) {
  2883. return i;
  2884. }
  2885. }
  2886. return -1;
  2887. }
  2888. int String::rfind(const String &p_str, int p_from) const {
  2889. // establish a limit
  2890. int limit = length() - p_str.length();
  2891. if (limit < 0) {
  2892. return -1;
  2893. }
  2894. // establish a starting point
  2895. if (p_from < 0) {
  2896. p_from = limit;
  2897. } else if (p_from > limit) {
  2898. p_from = limit;
  2899. }
  2900. int src_len = p_str.length();
  2901. int len = length();
  2902. if (src_len == 0 || len == 0) {
  2903. return -1; // won't find anything!
  2904. }
  2905. const char32_t *src = get_data();
  2906. for (int i = p_from; i >= 0; i--) {
  2907. bool found = true;
  2908. for (int j = 0; j < src_len; j++) {
  2909. int read_pos = i + j;
  2910. if (read_pos >= len) {
  2911. ERR_PRINT("read_pos>=len");
  2912. return -1;
  2913. }
  2914. if (src[read_pos] != p_str[j]) {
  2915. found = false;
  2916. break;
  2917. }
  2918. }
  2919. if (found) {
  2920. return i;
  2921. }
  2922. }
  2923. return -1;
  2924. }
  2925. int String::rfind(const char *p_str, int p_from) const {
  2926. const int source_length = length();
  2927. int substring_length = strlen(p_str);
  2928. if (source_length == 0 || substring_length == 0) {
  2929. return -1; // won't find anything!
  2930. }
  2931. // establish a limit
  2932. int limit = length() - substring_length;
  2933. if (limit < 0) {
  2934. return -1;
  2935. }
  2936. // establish a starting point
  2937. int starting_point;
  2938. if (p_from < 0) {
  2939. starting_point = limit;
  2940. } else if (p_from > limit) {
  2941. starting_point = limit;
  2942. } else {
  2943. starting_point = p_from;
  2944. }
  2945. const char32_t *source = get_data();
  2946. for (int i = starting_point; i >= 0; i--) {
  2947. bool found = true;
  2948. for (int j = 0; j < substring_length; j++) {
  2949. int read_pos = i + j;
  2950. if (read_pos >= source_length) {
  2951. ERR_PRINT("read_pos>=source_length");
  2952. return -1;
  2953. }
  2954. const char32_t key_needle = p_str[j];
  2955. if (source[read_pos] != key_needle) {
  2956. found = false;
  2957. break;
  2958. }
  2959. }
  2960. if (found) {
  2961. return i;
  2962. }
  2963. }
  2964. return -1;
  2965. }
  2966. int String::rfindn(const String &p_str, int p_from) const {
  2967. // establish a limit
  2968. int limit = length() - p_str.length();
  2969. if (limit < 0) {
  2970. return -1;
  2971. }
  2972. // establish a starting point
  2973. if (p_from < 0) {
  2974. p_from = limit;
  2975. } else if (p_from > limit) {
  2976. p_from = limit;
  2977. }
  2978. int src_len = p_str.length();
  2979. int len = length();
  2980. if (src_len == 0 || len == 0) {
  2981. return -1; // won't find anything!
  2982. }
  2983. const char32_t *src = get_data();
  2984. for (int i = p_from; i >= 0; i--) {
  2985. bool found = true;
  2986. for (int j = 0; j < src_len; j++) {
  2987. int read_pos = i + j;
  2988. if (read_pos >= len) {
  2989. ERR_PRINT("read_pos>=len");
  2990. return -1;
  2991. }
  2992. char32_t srcc = _find_lower(src[read_pos]);
  2993. char32_t dstc = _find_lower(p_str[j]);
  2994. if (srcc != dstc) {
  2995. found = false;
  2996. break;
  2997. }
  2998. }
  2999. if (found) {
  3000. return i;
  3001. }
  3002. }
  3003. return -1;
  3004. }
  3005. int String::rfindn(const char *p_str, int p_from) const {
  3006. const int source_length = length();
  3007. int substring_length = strlen(p_str);
  3008. if (source_length == 0 || substring_length == 0) {
  3009. return -1; // won't find anything!
  3010. }
  3011. // establish a limit
  3012. int limit = length() - substring_length;
  3013. if (limit < 0) {
  3014. return -1;
  3015. }
  3016. // establish a starting point
  3017. int starting_point;
  3018. if (p_from < 0) {
  3019. starting_point = limit;
  3020. } else if (p_from > limit) {
  3021. starting_point = limit;
  3022. } else {
  3023. starting_point = p_from;
  3024. }
  3025. const char32_t *source = get_data();
  3026. for (int i = starting_point; i >= 0; i--) {
  3027. bool found = true;
  3028. for (int j = 0; j < substring_length; j++) {
  3029. int read_pos = i + j;
  3030. if (read_pos >= source_length) {
  3031. ERR_PRINT("read_pos>=source_length");
  3032. return -1;
  3033. }
  3034. const char32_t key_needle = p_str[j];
  3035. int srcc = _find_lower(source[read_pos]);
  3036. int keyc = _find_lower(key_needle);
  3037. if (srcc != keyc) {
  3038. found = false;
  3039. break;
  3040. }
  3041. }
  3042. if (found) {
  3043. return i;
  3044. }
  3045. }
  3046. return -1;
  3047. }
  3048. bool String::ends_with(const String &p_string) const {
  3049. int l = p_string.length();
  3050. if (l > length()) {
  3051. return false;
  3052. }
  3053. if (l == 0) {
  3054. return true;
  3055. }
  3056. const char32_t *p = &p_string[0];
  3057. const char32_t *s = &operator[](length() - l);
  3058. for (int i = 0; i < l; i++) {
  3059. if (p[i] != s[i]) {
  3060. return false;
  3061. }
  3062. }
  3063. return true;
  3064. }
  3065. bool String::ends_with(const char *p_string) const {
  3066. if (!p_string) {
  3067. return false;
  3068. }
  3069. int l = strlen(p_string);
  3070. if (l > length()) {
  3071. return false;
  3072. }
  3073. if (l == 0) {
  3074. return true;
  3075. }
  3076. const char32_t *s = &operator[](length() - l);
  3077. for (int i = 0; i < l; i++) {
  3078. if (static_cast<char32_t>(p_string[i]) != s[i]) {
  3079. return false;
  3080. }
  3081. }
  3082. return true;
  3083. }
  3084. bool String::begins_with(const String &p_string) const {
  3085. int l = p_string.length();
  3086. if (l > length()) {
  3087. return false;
  3088. }
  3089. if (l == 0) {
  3090. return true;
  3091. }
  3092. const char32_t *p = &p_string[0];
  3093. const char32_t *s = &operator[](0);
  3094. for (int i = 0; i < l; i++) {
  3095. if (p[i] != s[i]) {
  3096. return false;
  3097. }
  3098. }
  3099. return true;
  3100. }
  3101. bool String::begins_with(const char *p_string) const {
  3102. if (!p_string) {
  3103. return false;
  3104. }
  3105. int l = length();
  3106. if (l == 0) {
  3107. return *p_string == 0;
  3108. }
  3109. const char32_t *str = &operator[](0);
  3110. int i = 0;
  3111. while (*p_string && i < l) {
  3112. if ((char32_t)*p_string != str[i]) {
  3113. return false;
  3114. }
  3115. i++;
  3116. p_string++;
  3117. }
  3118. return *p_string == 0;
  3119. }
  3120. bool String::is_enclosed_in(const String &p_string) const {
  3121. return begins_with(p_string) && ends_with(p_string);
  3122. }
  3123. bool String::is_subsequence_of(const String &p_string) const {
  3124. return _base_is_subsequence_of(p_string, false);
  3125. }
  3126. bool String::is_subsequence_ofn(const String &p_string) const {
  3127. return _base_is_subsequence_of(p_string, true);
  3128. }
  3129. bool String::is_quoted() const {
  3130. return is_enclosed_in("\"") || is_enclosed_in("'");
  3131. }
  3132. int String::_count(const String &p_string, int p_from, int p_to, bool p_case_insensitive) const {
  3133. if (p_string.is_empty()) {
  3134. return 0;
  3135. }
  3136. int len = length();
  3137. int slen = p_string.length();
  3138. if (len < slen) {
  3139. return 0;
  3140. }
  3141. String str;
  3142. if (p_from >= 0 && p_to >= 0) {
  3143. if (p_to == 0) {
  3144. p_to = len;
  3145. } else if (p_from >= p_to) {
  3146. return 0;
  3147. }
  3148. if (p_from == 0 && p_to == len) {
  3149. str = String();
  3150. str.copy_from_unchecked(&get_data()[0], len);
  3151. } else {
  3152. str = substr(p_from, p_to - p_from);
  3153. }
  3154. } else {
  3155. return 0;
  3156. }
  3157. int c = 0;
  3158. int idx = -1;
  3159. do {
  3160. idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
  3161. if (idx != -1) {
  3162. str = str.substr(idx + slen, str.length() - slen);
  3163. ++c;
  3164. }
  3165. } while (idx != -1);
  3166. return c;
  3167. }
  3168. int String::_count(const char *p_string, int p_from, int p_to, bool p_case_insensitive) const {
  3169. int substring_length = strlen(p_string);
  3170. if (substring_length == 0) {
  3171. return 0;
  3172. }
  3173. const int source_length = length();
  3174. if (source_length < substring_length) {
  3175. return 0;
  3176. }
  3177. String str;
  3178. int search_limit = p_to;
  3179. if (p_from >= 0 && p_to >= 0) {
  3180. if (p_to == 0) {
  3181. search_limit = source_length;
  3182. } else if (p_from >= p_to) {
  3183. return 0;
  3184. }
  3185. if (p_from == 0 && search_limit == source_length) {
  3186. str = String();
  3187. str.copy_from_unchecked(&get_data()[0], source_length);
  3188. } else {
  3189. str = substr(p_from, search_limit - p_from);
  3190. }
  3191. } else {
  3192. return 0;
  3193. }
  3194. int c = 0;
  3195. int idx = -1;
  3196. do {
  3197. idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
  3198. if (idx != -1) {
  3199. str = str.substr(idx + substring_length, str.length() - substring_length);
  3200. ++c;
  3201. }
  3202. } while (idx != -1);
  3203. return c;
  3204. }
  3205. int String::count(const String &p_string, int p_from, int p_to) const {
  3206. return _count(p_string, p_from, p_to, false);
  3207. }
  3208. int String::count(const char *p_string, int p_from, int p_to) const {
  3209. return _count(p_string, p_from, p_to, false);
  3210. }
  3211. int String::countn(const String &p_string, int p_from, int p_to) const {
  3212. return _count(p_string, p_from, p_to, true);
  3213. }
  3214. int String::countn(const char *p_string, int p_from, int p_to) const {
  3215. return _count(p_string, p_from, p_to, true);
  3216. }
  3217. bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const {
  3218. int len = length();
  3219. if (len == 0) {
  3220. // Technically an empty string is subsequence of any string
  3221. return true;
  3222. }
  3223. if (len > p_string.length()) {
  3224. return false;
  3225. }
  3226. const char32_t *src = &operator[](0);
  3227. const char32_t *tgt = &p_string[0];
  3228. for (; *src && *tgt; tgt++) {
  3229. bool match = false;
  3230. if (case_insensitive) {
  3231. char32_t srcc = _find_lower(*src);
  3232. char32_t tgtc = _find_lower(*tgt);
  3233. match = srcc == tgtc;
  3234. } else {
  3235. match = *src == *tgt;
  3236. }
  3237. if (match) {
  3238. src++;
  3239. if (!*src) {
  3240. return true;
  3241. }
  3242. }
  3243. }
  3244. return false;
  3245. }
  3246. Vector<String> String::bigrams() const {
  3247. int n_pairs = length() - 1;
  3248. Vector<String> b;
  3249. if (n_pairs <= 0) {
  3250. return b;
  3251. }
  3252. b.resize(n_pairs);
  3253. String *b_ptrw = b.ptrw();
  3254. for (int i = 0; i < n_pairs; i++) {
  3255. b_ptrw[i] = substr(i, 2);
  3256. }
  3257. return b;
  3258. }
  3259. // Similarity according to Sorensen-Dice coefficient
  3260. float String::similarity(const String &p_string) const {
  3261. if (operator==(p_string)) {
  3262. // Equal strings are totally similar
  3263. return 1.0f;
  3264. }
  3265. if (length() < 2 || p_string.length() < 2) {
  3266. // No way to calculate similarity without a single bigram
  3267. return 0.0f;
  3268. }
  3269. Vector<String> src_bigrams = bigrams();
  3270. Vector<String> tgt_bigrams = p_string.bigrams();
  3271. int src_size = src_bigrams.size();
  3272. int tgt_size = tgt_bigrams.size();
  3273. int sum = src_size + tgt_size;
  3274. int inter = 0;
  3275. for (int i = 0; i < src_size; i++) {
  3276. for (int j = 0; j < tgt_size; j++) {
  3277. if (src_bigrams[i] == tgt_bigrams[j]) {
  3278. inter++;
  3279. break;
  3280. }
  3281. }
  3282. }
  3283. return (2.0f * inter) / sum;
  3284. }
  3285. static bool _wildcard_match(const char32_t *p_pattern, const char32_t *p_string, bool p_case_sensitive) {
  3286. switch (*p_pattern) {
  3287. case '\0':
  3288. return !*p_string;
  3289. case '*':
  3290. return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive));
  3291. case '?':
  3292. return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
  3293. default:
  3294. 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);
  3295. }
  3296. }
  3297. bool String::match(const String &p_wildcard) const {
  3298. if (!p_wildcard.length() || !length()) {
  3299. return false;
  3300. }
  3301. return _wildcard_match(p_wildcard.get_data(), get_data(), true);
  3302. }
  3303. bool String::matchn(const String &p_wildcard) const {
  3304. if (!p_wildcard.length() || !length()) {
  3305. return false;
  3306. }
  3307. return _wildcard_match(p_wildcard.get_data(), get_data(), false);
  3308. }
  3309. String String::format(const Variant &values, const String &placeholder) const {
  3310. String new_string = String(ptr());
  3311. if (values.get_type() == Variant::ARRAY) {
  3312. Array values_arr = values;
  3313. for (int i = 0; i < values_arr.size(); i++) {
  3314. String i_as_str = String::num_int64(i);
  3315. if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
  3316. Array value_arr = values_arr[i];
  3317. if (value_arr.size() == 2) {
  3318. Variant v_key = value_arr[0];
  3319. String key = v_key;
  3320. Variant v_val = value_arr[1];
  3321. String val = v_val;
  3322. new_string = new_string.replace(placeholder.replace("_", key), val);
  3323. } else {
  3324. ERR_PRINT(String("STRING.format Inner Array size != 2 ").ascii().get_data());
  3325. }
  3326. } else { //Array structure ["RobotGuy","Logis","rookie"]
  3327. Variant v_val = values_arr[i];
  3328. String val = v_val;
  3329. if (placeholder.contains("_")) {
  3330. new_string = new_string.replace(placeholder.replace("_", i_as_str), val);
  3331. } else {
  3332. new_string = new_string.replace_first(placeholder, val);
  3333. }
  3334. }
  3335. }
  3336. } else if (values.get_type() == Variant::DICTIONARY) {
  3337. Dictionary d = values;
  3338. List<Variant> keys;
  3339. d.get_key_list(&keys);
  3340. for (const Variant &key : keys) {
  3341. new_string = new_string.replace(placeholder.replace("_", key), d[key]);
  3342. }
  3343. } else {
  3344. ERR_PRINT(String("Invalid type: use Array or Dictionary.").ascii().get_data());
  3345. }
  3346. return new_string;
  3347. }
  3348. String String::replace(const String &p_key, const String &p_with) const {
  3349. String new_string;
  3350. int search_from = 0;
  3351. int result = 0;
  3352. while ((result = find(p_key, search_from)) >= 0) {
  3353. new_string += substr(search_from, result - search_from);
  3354. new_string += p_with;
  3355. search_from = result + p_key.length();
  3356. }
  3357. if (search_from == 0) {
  3358. return *this;
  3359. }
  3360. new_string += substr(search_from, length() - search_from);
  3361. return new_string;
  3362. }
  3363. String String::replace(const char *p_key, const char *p_with) const {
  3364. String new_string;
  3365. int search_from = 0;
  3366. int result = 0;
  3367. while ((result = find(p_key, search_from)) >= 0) {
  3368. new_string += substr(search_from, result - search_from);
  3369. new_string += p_with;
  3370. int k = 0;
  3371. while (p_key[k] != '\0') {
  3372. k++;
  3373. }
  3374. search_from = result + k;
  3375. }
  3376. if (search_from == 0) {
  3377. return *this;
  3378. }
  3379. new_string += substr(search_from, length() - search_from);
  3380. return new_string;
  3381. }
  3382. String String::replace_first(const String &p_key, const String &p_with) const {
  3383. int pos = find(p_key);
  3384. if (pos >= 0) {
  3385. return substr(0, pos) + p_with + substr(pos + p_key.length(), length());
  3386. }
  3387. return *this;
  3388. }
  3389. String String::replace_first(const char *p_key, const char *p_with) const {
  3390. int pos = find(p_key);
  3391. if (pos >= 0) {
  3392. int substring_length = strlen(p_key);
  3393. return substr(0, pos) + p_with + substr(pos + substring_length, length());
  3394. }
  3395. return *this;
  3396. }
  3397. String String::replacen(const String &p_key, const String &p_with) const {
  3398. String new_string;
  3399. int search_from = 0;
  3400. int result = 0;
  3401. while ((result = findn(p_key, search_from)) >= 0) {
  3402. new_string += substr(search_from, result - search_from);
  3403. new_string += p_with;
  3404. search_from = result + p_key.length();
  3405. }
  3406. if (search_from == 0) {
  3407. return *this;
  3408. }
  3409. new_string += substr(search_from, length() - search_from);
  3410. return new_string;
  3411. }
  3412. String String::replacen(const char *p_key, const char *p_with) const {
  3413. String new_string;
  3414. int search_from = 0;
  3415. int result = 0;
  3416. int substring_length = strlen(p_key);
  3417. if (substring_length == 0) {
  3418. return *this; // there's nothing to match or substitute
  3419. }
  3420. while ((result = findn(p_key, search_from)) >= 0) {
  3421. new_string += substr(search_from, result - search_from);
  3422. new_string += p_with;
  3423. search_from = result + substring_length;
  3424. }
  3425. if (search_from == 0) {
  3426. return *this;
  3427. }
  3428. new_string += substr(search_from, length() - search_from);
  3429. return new_string;
  3430. }
  3431. String String::repeat(int p_count) const {
  3432. ERR_FAIL_COND_V_MSG(p_count < 0, "", "Parameter count should be a positive number.");
  3433. if (p_count == 0) {
  3434. return "";
  3435. }
  3436. if (p_count == 1) {
  3437. return *this;
  3438. }
  3439. int len = length();
  3440. String new_string = *this;
  3441. new_string.resize(p_count * len + 1);
  3442. char32_t *dst = new_string.ptrw();
  3443. int offset = 1;
  3444. int stride = 1;
  3445. while (offset < p_count) {
  3446. memcpy(dst + offset * len, dst, stride * len * sizeof(char32_t));
  3447. offset += stride;
  3448. stride = MIN(stride * 2, p_count - offset);
  3449. }
  3450. dst[p_count * len] = _null;
  3451. return new_string;
  3452. }
  3453. String String::reverse() const {
  3454. int len = length();
  3455. if (len <= 1) {
  3456. return *this;
  3457. }
  3458. String new_string;
  3459. new_string.resize(len + 1);
  3460. const char32_t *src = ptr();
  3461. char32_t *dst = new_string.ptrw();
  3462. for (int i = 0; i < len; i++) {
  3463. dst[i] = src[len - i - 1];
  3464. }
  3465. dst[len] = _null;
  3466. return new_string;
  3467. }
  3468. String String::left(int p_len) const {
  3469. if (p_len < 0) {
  3470. p_len = length() + p_len;
  3471. }
  3472. if (p_len <= 0) {
  3473. return "";
  3474. }
  3475. if (p_len >= length()) {
  3476. return *this;
  3477. }
  3478. String s;
  3479. s.copy_from_unchecked(&get_data()[0], p_len);
  3480. return s;
  3481. }
  3482. String String::right(int p_len) const {
  3483. if (p_len < 0) {
  3484. p_len = length() + p_len;
  3485. }
  3486. if (p_len <= 0) {
  3487. return "";
  3488. }
  3489. if (p_len >= length()) {
  3490. return *this;
  3491. }
  3492. String s;
  3493. s.copy_from_unchecked(&get_data()[length() - p_len], p_len);
  3494. return s;
  3495. }
  3496. char32_t String::unicode_at(int p_idx) const {
  3497. ERR_FAIL_INDEX_V(p_idx, length(), 0);
  3498. return operator[](p_idx);
  3499. }
  3500. String String::indent(const String &p_prefix) const {
  3501. String new_string;
  3502. int line_start = 0;
  3503. for (int i = 0; i < length(); i++) {
  3504. const char32_t c = operator[](i);
  3505. if (c == '\n') {
  3506. if (i == line_start) {
  3507. new_string += c; // Leave empty lines empty.
  3508. } else {
  3509. new_string += p_prefix + substr(line_start, i - line_start + 1);
  3510. }
  3511. line_start = i + 1;
  3512. }
  3513. }
  3514. if (line_start != length()) {
  3515. new_string += p_prefix + substr(line_start);
  3516. }
  3517. return new_string;
  3518. }
  3519. String String::dedent() const {
  3520. String new_string;
  3521. String indent;
  3522. bool has_indent = false;
  3523. bool has_text = false;
  3524. int line_start = 0;
  3525. int indent_stop = -1;
  3526. for (int i = 0; i < length(); i++) {
  3527. char32_t c = operator[](i);
  3528. if (c == '\n') {
  3529. if (has_text) {
  3530. new_string += substr(indent_stop, i - indent_stop);
  3531. }
  3532. new_string += "\n";
  3533. has_text = false;
  3534. line_start = i + 1;
  3535. indent_stop = -1;
  3536. } else if (!has_text) {
  3537. if (c > 32) {
  3538. has_text = true;
  3539. if (!has_indent) {
  3540. has_indent = true;
  3541. indent = substr(line_start, i - line_start);
  3542. indent_stop = i;
  3543. }
  3544. }
  3545. if (has_indent && indent_stop < 0) {
  3546. int j = i - line_start;
  3547. if (j >= indent.length() || c != indent[j]) {
  3548. indent_stop = i;
  3549. }
  3550. }
  3551. }
  3552. }
  3553. if (has_text) {
  3554. new_string += substr(indent_stop, length() - indent_stop);
  3555. }
  3556. return new_string;
  3557. }
  3558. String String::strip_edges(bool left, bool right) const {
  3559. int len = length();
  3560. int beg = 0, end = len;
  3561. if (left) {
  3562. for (int i = 0; i < len; i++) {
  3563. if (operator[](i) <= 32) {
  3564. beg++;
  3565. } else {
  3566. break;
  3567. }
  3568. }
  3569. }
  3570. if (right) {
  3571. for (int i = len - 1; i >= 0; i--) {
  3572. if (operator[](i) <= 32) {
  3573. end--;
  3574. } else {
  3575. break;
  3576. }
  3577. }
  3578. }
  3579. if (beg == 0 && end == len) {
  3580. return *this;
  3581. }
  3582. return substr(beg, end - beg);
  3583. }
  3584. String String::strip_escapes() const {
  3585. String new_string;
  3586. for (int i = 0; i < length(); i++) {
  3587. // Escape characters on first page of the ASCII table, before 32 (Space).
  3588. if (operator[](i) < 32) {
  3589. continue;
  3590. }
  3591. new_string += operator[](i);
  3592. }
  3593. return new_string;
  3594. }
  3595. String String::lstrip(const String &p_chars) const {
  3596. int len = length();
  3597. int beg;
  3598. for (beg = 0; beg < len; beg++) {
  3599. if (p_chars.find_char(get(beg)) == -1) {
  3600. break;
  3601. }
  3602. }
  3603. if (beg == 0) {
  3604. return *this;
  3605. }
  3606. return substr(beg, len - beg);
  3607. }
  3608. String String::rstrip(const String &p_chars) const {
  3609. int len = length();
  3610. int end;
  3611. for (end = len - 1; end >= 0; end--) {
  3612. if (p_chars.find_char(get(end)) == -1) {
  3613. break;
  3614. }
  3615. }
  3616. if (end == len - 1) {
  3617. return *this;
  3618. }
  3619. return substr(0, end + 1);
  3620. }
  3621. bool String::is_network_share_path() const {
  3622. return begins_with("//") || begins_with("\\\\");
  3623. }
  3624. String String::simplify_path() const {
  3625. String s = *this;
  3626. String drive;
  3627. // Check if we have a special path (like res://) or a protocol identifier.
  3628. int p = s.find("://");
  3629. bool found = false;
  3630. if (p > 0) {
  3631. bool only_chars = true;
  3632. for (int i = 0; i < p; i++) {
  3633. if (!is_ascii_alphanumeric_char(s[i])) {
  3634. only_chars = false;
  3635. break;
  3636. }
  3637. }
  3638. if (only_chars) {
  3639. found = true;
  3640. drive = s.substr(0, p + 3);
  3641. s = s.substr(p + 3);
  3642. }
  3643. }
  3644. if (!found) {
  3645. if (is_network_share_path()) {
  3646. // Network path, beginning with // or \\.
  3647. drive = s.substr(0, 2);
  3648. s = s.substr(2);
  3649. } else if (s.begins_with("/") || s.begins_with("\\")) {
  3650. // Absolute path.
  3651. drive = s.substr(0, 1);
  3652. s = s.substr(1);
  3653. } else {
  3654. // Windows-style drive path, like C:/ or C:\.
  3655. p = s.find(":/");
  3656. if (p == -1) {
  3657. p = s.find(":\\");
  3658. }
  3659. if (p != -1 && p < s.find("/")) {
  3660. drive = s.substr(0, p + 2);
  3661. s = s.substr(p + 2);
  3662. }
  3663. }
  3664. }
  3665. s = s.replace("\\", "/");
  3666. while (true) { // in case of using 2 or more slash
  3667. String compare = s.replace("//", "/");
  3668. if (s == compare) {
  3669. break;
  3670. } else {
  3671. s = compare;
  3672. }
  3673. }
  3674. Vector<String> dirs = s.split("/", false);
  3675. for (int i = 0; i < dirs.size(); i++) {
  3676. String d = dirs[i];
  3677. if (d == ".") {
  3678. dirs.remove_at(i);
  3679. i--;
  3680. } else if (d == "..") {
  3681. if (i == 0) {
  3682. dirs.remove_at(i);
  3683. i--;
  3684. } else {
  3685. dirs.remove_at(i);
  3686. dirs.remove_at(i - 1);
  3687. i -= 2;
  3688. }
  3689. }
  3690. }
  3691. s = "";
  3692. for (int i = 0; i < dirs.size(); i++) {
  3693. if (i > 0) {
  3694. s += "/";
  3695. }
  3696. s += dirs[i];
  3697. }
  3698. return drive + s;
  3699. }
  3700. static int _humanize_digits(int p_num) {
  3701. if (p_num < 100) {
  3702. return 2;
  3703. } else if (p_num < 1024) {
  3704. return 1;
  3705. } else {
  3706. return 0;
  3707. }
  3708. }
  3709. String String::humanize_size(uint64_t p_size) {
  3710. int magnitude = 0;
  3711. uint64_t _div = 1;
  3712. while (p_size > _div * 1024 && magnitude < 6) {
  3713. _div *= 1024;
  3714. magnitude++;
  3715. }
  3716. if (magnitude == 0) {
  3717. return String::num(p_size) + " " + RTR("B");
  3718. } else {
  3719. String suffix;
  3720. switch (magnitude) {
  3721. case 1:
  3722. suffix = RTR("KiB");
  3723. break;
  3724. case 2:
  3725. suffix = RTR("MiB");
  3726. break;
  3727. case 3:
  3728. suffix = RTR("GiB");
  3729. break;
  3730. case 4:
  3731. suffix = RTR("TiB");
  3732. break;
  3733. case 5:
  3734. suffix = RTR("PiB");
  3735. break;
  3736. case 6:
  3737. suffix = RTR("EiB");
  3738. break;
  3739. }
  3740. const double divisor = _div;
  3741. const int digits = _humanize_digits(p_size / _div);
  3742. return String::num(p_size / divisor).pad_decimals(digits) + " " + suffix;
  3743. }
  3744. }
  3745. bool String::is_absolute_path() const {
  3746. if (length() > 1) {
  3747. return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
  3748. } else if ((length()) == 1) {
  3749. return (operator[](0) == '/' || operator[](0) == '\\');
  3750. } else {
  3751. return false;
  3752. }
  3753. }
  3754. String String::validate_identifier() const {
  3755. if (is_empty()) {
  3756. return "_"; // Empty string is not a valid identifier;
  3757. }
  3758. String result;
  3759. if (is_digit(operator[](0))) {
  3760. result = "_" + *this;
  3761. } else {
  3762. result = *this;
  3763. }
  3764. int len = result.length();
  3765. char32_t *buffer = result.ptrw();
  3766. for (int i = 0; i < len; i++) {
  3767. if (!is_ascii_identifier_char(buffer[i])) {
  3768. buffer[i] = '_';
  3769. }
  3770. }
  3771. return result;
  3772. }
  3773. bool String::is_valid_identifier() const {
  3774. int len = length();
  3775. if (len == 0) {
  3776. return false;
  3777. }
  3778. if (is_digit(operator[](0))) {
  3779. return false;
  3780. }
  3781. const char32_t *str = &operator[](0);
  3782. for (int i = 0; i < len; i++) {
  3783. if (!is_ascii_identifier_char(str[i])) {
  3784. return false;
  3785. }
  3786. }
  3787. return true;
  3788. }
  3789. bool String::is_valid_string() const {
  3790. int l = length();
  3791. const char32_t *src = get_data();
  3792. bool valid = true;
  3793. for (int i = 0; i < l; i++) {
  3794. valid = valid && (src[i] < 0xd800 || (src[i] > 0xdfff && src[i] <= 0x10ffff));
  3795. }
  3796. return valid;
  3797. }
  3798. String String::uri_encode() const {
  3799. const CharString temp = utf8();
  3800. String res;
  3801. for (int i = 0; i < temp.length(); ++i) {
  3802. uint8_t ord = temp[i];
  3803. if (ord == '.' || ord == '-' || ord == '~' || is_ascii_identifier_char(ord)) {
  3804. res += ord;
  3805. } else {
  3806. char p[4] = { '%', 0, 0, 0 };
  3807. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  3808. p[1] = hex[ord >> 4];
  3809. p[2] = hex[ord & 0xF];
  3810. res += p;
  3811. }
  3812. }
  3813. return res;
  3814. }
  3815. String String::uri_decode() const {
  3816. CharString src = utf8();
  3817. CharString res;
  3818. for (int i = 0; i < src.length(); ++i) {
  3819. if (src[i] == '%' && i + 2 < src.length()) {
  3820. char ord1 = src[i + 1];
  3821. if (is_digit(ord1) || is_ascii_upper_case(ord1)) {
  3822. char ord2 = src[i + 2];
  3823. if (is_digit(ord2) || is_ascii_upper_case(ord2)) {
  3824. char bytes[3] = { (char)ord1, (char)ord2, 0 };
  3825. res += (char)strtol(bytes, nullptr, 16);
  3826. i += 2;
  3827. }
  3828. } else {
  3829. res += src[i];
  3830. }
  3831. } else if (src[i] == '+') {
  3832. res += ' ';
  3833. } else {
  3834. res += src[i];
  3835. }
  3836. }
  3837. return String::utf8(res);
  3838. }
  3839. String String::c_unescape() const {
  3840. String escaped = *this;
  3841. escaped = escaped.replace("\\a", "\a");
  3842. escaped = escaped.replace("\\b", "\b");
  3843. escaped = escaped.replace("\\f", "\f");
  3844. escaped = escaped.replace("\\n", "\n");
  3845. escaped = escaped.replace("\\r", "\r");
  3846. escaped = escaped.replace("\\t", "\t");
  3847. escaped = escaped.replace("\\v", "\v");
  3848. escaped = escaped.replace("\\'", "\'");
  3849. escaped = escaped.replace("\\\"", "\"");
  3850. escaped = escaped.replace("\\\\", "\\");
  3851. return escaped;
  3852. }
  3853. String String::c_escape() const {
  3854. String escaped = *this;
  3855. escaped = escaped.replace("\\", "\\\\");
  3856. escaped = escaped.replace("\a", "\\a");
  3857. escaped = escaped.replace("\b", "\\b");
  3858. escaped = escaped.replace("\f", "\\f");
  3859. escaped = escaped.replace("\n", "\\n");
  3860. escaped = escaped.replace("\r", "\\r");
  3861. escaped = escaped.replace("\t", "\\t");
  3862. escaped = escaped.replace("\v", "\\v");
  3863. escaped = escaped.replace("\'", "\\'");
  3864. escaped = escaped.replace("\"", "\\\"");
  3865. return escaped;
  3866. }
  3867. String String::c_escape_multiline() const {
  3868. String escaped = *this;
  3869. escaped = escaped.replace("\\", "\\\\");
  3870. escaped = escaped.replace("\"", "\\\"");
  3871. return escaped;
  3872. }
  3873. String String::json_escape() const {
  3874. String escaped = *this;
  3875. escaped = escaped.replace("\\", "\\\\");
  3876. escaped = escaped.replace("\b", "\\b");
  3877. escaped = escaped.replace("\f", "\\f");
  3878. escaped = escaped.replace("\n", "\\n");
  3879. escaped = escaped.replace("\r", "\\r");
  3880. escaped = escaped.replace("\t", "\\t");
  3881. escaped = escaped.replace("\v", "\\v");
  3882. escaped = escaped.replace("\"", "\\\"");
  3883. return escaped;
  3884. }
  3885. String String::xml_escape(bool p_escape_quotes) const {
  3886. String str = *this;
  3887. str = str.replace("&", "&amp;");
  3888. str = str.replace("<", "&lt;");
  3889. str = str.replace(">", "&gt;");
  3890. if (p_escape_quotes) {
  3891. str = str.replace("'", "&apos;");
  3892. str = str.replace("\"", "&quot;");
  3893. }
  3894. /*
  3895. for (int i=1;i<32;i++) {
  3896. char chr[2]={i,0};
  3897. str=str.replace(chr,"&#"+String::num(i)+";");
  3898. }*/
  3899. return str;
  3900. }
  3901. static _FORCE_INLINE_ int _xml_unescape(const char32_t *p_src, int p_src_len, char32_t *p_dst) {
  3902. int len = 0;
  3903. while (p_src_len) {
  3904. if (*p_src == '&') {
  3905. int eat = 0;
  3906. if (p_src_len >= 4 && p_src[1] == '#') {
  3907. char32_t c = 0;
  3908. bool overflow = false;
  3909. if (p_src[2] == 'x') {
  3910. // Hex entity &#x<num>;
  3911. for (int i = 3; i < p_src_len; i++) {
  3912. eat = i + 1;
  3913. char32_t ct = p_src[i];
  3914. if (ct == ';') {
  3915. break;
  3916. } else if (is_digit(ct)) {
  3917. ct = ct - '0';
  3918. } else if (ct >= 'a' && ct <= 'f') {
  3919. ct = (ct - 'a') + 10;
  3920. } else if (ct >= 'A' && ct <= 'F') {
  3921. ct = (ct - 'A') + 10;
  3922. } else {
  3923. break;
  3924. }
  3925. if (c > (UINT32_MAX >> 4)) {
  3926. overflow = true;
  3927. break;
  3928. }
  3929. c <<= 4;
  3930. c |= ct;
  3931. }
  3932. } else {
  3933. // Decimal entity &#<num>;
  3934. for (int i = 2; i < p_src_len; i++) {
  3935. eat = i + 1;
  3936. char32_t ct = p_src[i];
  3937. if (ct == ';' || !is_digit(ct)) {
  3938. break;
  3939. }
  3940. }
  3941. if (p_src[eat - 1] == ';') {
  3942. int64_t val = String::to_int(p_src + 2, eat - 3);
  3943. if (val > 0 && val <= UINT32_MAX) {
  3944. c = (char32_t)val;
  3945. } else {
  3946. overflow = true;
  3947. }
  3948. }
  3949. }
  3950. // Value must be non-zero, in the range of char32_t,
  3951. // actually end with ';'. If invalid, leave the entity as-is
  3952. if (c == '\0' || overflow || p_src[eat - 1] != ';') {
  3953. eat = 1;
  3954. c = *p_src;
  3955. }
  3956. if (p_dst) {
  3957. *p_dst = c;
  3958. }
  3959. } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') {
  3960. if (p_dst) {
  3961. *p_dst = '>';
  3962. }
  3963. eat = 4;
  3964. } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') {
  3965. if (p_dst) {
  3966. *p_dst = '<';
  3967. }
  3968. eat = 4;
  3969. } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') {
  3970. if (p_dst) {
  3971. *p_dst = '&';
  3972. }
  3973. eat = 5;
  3974. } 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] == ';') {
  3975. if (p_dst) {
  3976. *p_dst = '"';
  3977. }
  3978. eat = 6;
  3979. } 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] == ';') {
  3980. if (p_dst) {
  3981. *p_dst = '\'';
  3982. }
  3983. eat = 6;
  3984. } else {
  3985. if (p_dst) {
  3986. *p_dst = *p_src;
  3987. }
  3988. eat = 1;
  3989. }
  3990. if (p_dst) {
  3991. p_dst++;
  3992. }
  3993. len++;
  3994. p_src += eat;
  3995. p_src_len -= eat;
  3996. } else {
  3997. if (p_dst) {
  3998. *p_dst = *p_src;
  3999. p_dst++;
  4000. }
  4001. len++;
  4002. p_src++;
  4003. p_src_len--;
  4004. }
  4005. }
  4006. return len;
  4007. }
  4008. String String::xml_unescape() const {
  4009. String str;
  4010. int l = length();
  4011. int len = _xml_unescape(get_data(), l, nullptr);
  4012. if (len == 0) {
  4013. return String();
  4014. }
  4015. str.resize(len + 1);
  4016. char32_t *str_ptrw = str.ptrw();
  4017. _xml_unescape(get_data(), l, str_ptrw);
  4018. str_ptrw[len] = 0;
  4019. return str;
  4020. }
  4021. String String::pad_decimals(int p_digits) const {
  4022. String s = *this;
  4023. int c = s.find(".");
  4024. if (c == -1) {
  4025. if (p_digits <= 0) {
  4026. return s;
  4027. }
  4028. s += ".";
  4029. c = s.length() - 1;
  4030. } else {
  4031. if (p_digits <= 0) {
  4032. return s.substr(0, c);
  4033. }
  4034. }
  4035. if (s.length() - (c + 1) > p_digits) {
  4036. return s.substr(0, c + p_digits + 1);
  4037. } else {
  4038. int zeros_to_add = p_digits - s.length() + (c + 1);
  4039. return s + String("0").repeat(zeros_to_add);
  4040. }
  4041. }
  4042. String String::pad_zeros(int p_digits) const {
  4043. String s = *this;
  4044. int end = s.find(".");
  4045. if (end == -1) {
  4046. end = s.length();
  4047. }
  4048. if (end == 0) {
  4049. return s;
  4050. }
  4051. int begin = 0;
  4052. while (begin < end && !is_digit(s[begin])) {
  4053. begin++;
  4054. }
  4055. int zeros_to_add = p_digits - (end - begin);
  4056. if (zeros_to_add <= 0) {
  4057. return s;
  4058. } else {
  4059. return s.insert(begin, String("0").repeat(zeros_to_add));
  4060. }
  4061. }
  4062. String String::trim_prefix(const String &p_prefix) const {
  4063. String s = *this;
  4064. if (s.begins_with(p_prefix)) {
  4065. return s.substr(p_prefix.length(), s.length() - p_prefix.length());
  4066. }
  4067. return s;
  4068. }
  4069. String String::trim_prefix(const char *p_prefix) const {
  4070. String s = *this;
  4071. if (s.begins_with(p_prefix)) {
  4072. int prefix_length = strlen(p_prefix);
  4073. return s.substr(prefix_length, s.length() - prefix_length);
  4074. }
  4075. return s;
  4076. }
  4077. String String::trim_suffix(const String &p_suffix) const {
  4078. String s = *this;
  4079. if (s.ends_with(p_suffix)) {
  4080. return s.substr(0, s.length() - p_suffix.length());
  4081. }
  4082. return s;
  4083. }
  4084. String String::trim_suffix(const char *p_suffix) const {
  4085. String s = *this;
  4086. if (s.ends_with(p_suffix)) {
  4087. return s.substr(0, s.length() - strlen(p_suffix));
  4088. }
  4089. return s;
  4090. }
  4091. bool String::is_valid_int() const {
  4092. int len = length();
  4093. if (len == 0) {
  4094. return false;
  4095. }
  4096. int from = 0;
  4097. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  4098. from++;
  4099. }
  4100. for (int i = from; i < len; i++) {
  4101. if (!is_digit(operator[](i))) {
  4102. return false; // no start with number plz
  4103. }
  4104. }
  4105. return true;
  4106. }
  4107. bool String::is_valid_hex_number(bool p_with_prefix) const {
  4108. int len = length();
  4109. if (len == 0) {
  4110. return false;
  4111. }
  4112. int from = 0;
  4113. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  4114. from++;
  4115. }
  4116. if (p_with_prefix) {
  4117. if (len < 3) {
  4118. return false;
  4119. }
  4120. if (operator[](from) != '0' || operator[](from + 1) != 'x') {
  4121. return false;
  4122. }
  4123. from += 2;
  4124. }
  4125. for (int i = from; i < len; i++) {
  4126. char32_t c = operator[](i);
  4127. if (is_hex_digit(c)) {
  4128. continue;
  4129. }
  4130. return false;
  4131. }
  4132. return true;
  4133. }
  4134. bool String::is_valid_float() const {
  4135. int len = length();
  4136. if (len == 0) {
  4137. return false;
  4138. }
  4139. int from = 0;
  4140. if (operator[](0) == '+' || operator[](0) == '-') {
  4141. from++;
  4142. }
  4143. bool exponent_found = false;
  4144. bool period_found = false;
  4145. bool sign_found = false;
  4146. bool exponent_values_found = false;
  4147. bool numbers_found = false;
  4148. for (int i = from; i < len; i++) {
  4149. if (is_digit(operator[](i))) {
  4150. if (exponent_found) {
  4151. exponent_values_found = true;
  4152. } else {
  4153. numbers_found = true;
  4154. }
  4155. } else if (numbers_found && !exponent_found && operator[](i) == 'e') {
  4156. exponent_found = true;
  4157. } else if (!period_found && !exponent_found && operator[](i) == '.') {
  4158. period_found = true;
  4159. } else if ((operator[](i) == '-' || operator[](i) == '+') && exponent_found && !exponent_values_found && !sign_found) {
  4160. sign_found = true;
  4161. } else {
  4162. return false; // no start with number plz
  4163. }
  4164. }
  4165. return numbers_found;
  4166. }
  4167. String String::path_to_file(const String &p_path) const {
  4168. // Don't get base dir for src, this is expected to be a dir already.
  4169. String src = replace("\\", "/");
  4170. String dst = p_path.replace("\\", "/").get_base_dir();
  4171. String rel = src.path_to(dst);
  4172. if (rel == dst) { // failed
  4173. return p_path;
  4174. } else {
  4175. return rel + p_path.get_file();
  4176. }
  4177. }
  4178. String String::path_to(const String &p_path) const {
  4179. String src = replace("\\", "/");
  4180. String dst = p_path.replace("\\", "/");
  4181. if (!src.ends_with("/")) {
  4182. src += "/";
  4183. }
  4184. if (!dst.ends_with("/")) {
  4185. dst += "/";
  4186. }
  4187. if (src.begins_with("res://") && dst.begins_with("res://")) {
  4188. src = src.replace("res://", "/");
  4189. dst = dst.replace("res://", "/");
  4190. } else if (src.begins_with("user://") && dst.begins_with("user://")) {
  4191. src = src.replace("user://", "/");
  4192. dst = dst.replace("user://", "/");
  4193. } else if (src.begins_with("/") && dst.begins_with("/")) {
  4194. //nothing
  4195. } else {
  4196. //dos style
  4197. String src_begin = src.get_slicec('/', 0);
  4198. String dst_begin = dst.get_slicec('/', 0);
  4199. if (src_begin != dst_begin) {
  4200. return p_path; //impossible to do this
  4201. }
  4202. src = src.substr(src_begin.length(), src.length());
  4203. dst = dst.substr(dst_begin.length(), dst.length());
  4204. }
  4205. //remove leading and trailing slash and split
  4206. Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/");
  4207. Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/");
  4208. //find common parent
  4209. int common_parent = 0;
  4210. while (true) {
  4211. if (src_dirs.size() == common_parent) {
  4212. break;
  4213. }
  4214. if (dst_dirs.size() == common_parent) {
  4215. break;
  4216. }
  4217. if (src_dirs[common_parent] != dst_dirs[common_parent]) {
  4218. break;
  4219. }
  4220. common_parent++;
  4221. }
  4222. common_parent--;
  4223. int dirs_to_backtrack = (src_dirs.size() - 1) - common_parent;
  4224. String dir = String("../").repeat(dirs_to_backtrack);
  4225. for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
  4226. dir += dst_dirs[i] + "/";
  4227. }
  4228. if (dir.length() == 0) {
  4229. dir = "./";
  4230. }
  4231. return dir;
  4232. }
  4233. bool String::is_valid_html_color() const {
  4234. return Color::html_is_valid(*this);
  4235. }
  4236. // Changes made to the set of invalid filename characters must also be reflected in the String documentation for is_valid_filename.
  4237. static const char *invalid_filename_characters = ": / \\ ? * \" | % < >";
  4238. bool String::is_valid_filename() const {
  4239. String stripped = strip_edges();
  4240. if (*this != stripped) {
  4241. return false;
  4242. }
  4243. if (stripped.is_empty()) {
  4244. return false;
  4245. }
  4246. Vector<String> chars = String(invalid_filename_characters).split(" ");
  4247. for (const String &ch : chars) {
  4248. if (contains(ch)) {
  4249. return false;
  4250. }
  4251. }
  4252. return true;
  4253. }
  4254. String String::validate_filename() const {
  4255. Vector<String> chars = String(invalid_filename_characters).split(" ");
  4256. String name = strip_edges();
  4257. for (int i = 0; i < chars.size(); i++) {
  4258. name = name.replace(chars[i], "_");
  4259. }
  4260. return name;
  4261. }
  4262. bool String::is_valid_ip_address() const {
  4263. if (find(":") >= 0) {
  4264. Vector<String> ip = split(":");
  4265. for (int i = 0; i < ip.size(); i++) {
  4266. const String &n = ip[i];
  4267. if (n.is_empty()) {
  4268. continue;
  4269. }
  4270. if (n.is_valid_hex_number(false)) {
  4271. int64_t nint = n.hex_to_int();
  4272. if (nint < 0 || nint > 0xffff) {
  4273. return false;
  4274. }
  4275. continue;
  4276. }
  4277. if (!n.is_valid_ip_address()) {
  4278. return false;
  4279. }
  4280. }
  4281. } else {
  4282. Vector<String> ip = split(".");
  4283. if (ip.size() != 4) {
  4284. return false;
  4285. }
  4286. for (int i = 0; i < ip.size(); i++) {
  4287. const String &n = ip[i];
  4288. if (!n.is_valid_int()) {
  4289. return false;
  4290. }
  4291. int val = n.to_int();
  4292. if (val < 0 || val > 255) {
  4293. return false;
  4294. }
  4295. }
  4296. }
  4297. return true;
  4298. }
  4299. bool String::is_resource_file() const {
  4300. return begins_with("res://") && find("::") == -1;
  4301. }
  4302. bool String::is_relative_path() const {
  4303. return !is_absolute_path();
  4304. }
  4305. String String::get_base_dir() const {
  4306. int end = 0;
  4307. // URL scheme style base.
  4308. int basepos = find("://");
  4309. if (basepos != -1) {
  4310. end = basepos + 3;
  4311. }
  4312. // Windows top level directory base.
  4313. if (end == 0) {
  4314. basepos = find(":/");
  4315. if (basepos == -1) {
  4316. basepos = find(":\\");
  4317. }
  4318. if (basepos != -1) {
  4319. end = basepos + 2;
  4320. }
  4321. }
  4322. // Windows UNC network share path.
  4323. if (end == 0) {
  4324. if (is_network_share_path()) {
  4325. basepos = find("/", 2);
  4326. if (basepos == -1) {
  4327. basepos = find("\\", 2);
  4328. }
  4329. int servpos = find("/", basepos + 1);
  4330. if (servpos == -1) {
  4331. servpos = find("\\", basepos + 1);
  4332. }
  4333. if (servpos != -1) {
  4334. end = servpos + 1;
  4335. }
  4336. }
  4337. }
  4338. // Unix root directory base.
  4339. if (end == 0) {
  4340. if (begins_with("/")) {
  4341. end = 1;
  4342. }
  4343. }
  4344. String rs;
  4345. String base;
  4346. if (end != 0) {
  4347. rs = substr(end, length());
  4348. base = substr(0, end);
  4349. } else {
  4350. rs = *this;
  4351. }
  4352. int sep = MAX(rs.rfind("/"), rs.rfind("\\"));
  4353. if (sep == -1) {
  4354. return base;
  4355. }
  4356. return base + rs.substr(0, sep);
  4357. }
  4358. String String::get_file() const {
  4359. int sep = MAX(rfind("/"), rfind("\\"));
  4360. if (sep == -1) {
  4361. return *this;
  4362. }
  4363. return substr(sep + 1, length());
  4364. }
  4365. String String::get_extension() const {
  4366. int pos = rfind(".");
  4367. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  4368. return "";
  4369. }
  4370. return substr(pos + 1, length());
  4371. }
  4372. String String::path_join(const String &p_file) const {
  4373. if (is_empty()) {
  4374. return p_file;
  4375. }
  4376. if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/')) {
  4377. return *this + p_file;
  4378. }
  4379. return *this + "/" + p_file;
  4380. }
  4381. String String::property_name_encode() const {
  4382. // Escape and quote strings with extended ASCII or further Unicode characters
  4383. // as well as '"', '=' or ' ' (32)
  4384. const char32_t *cstr = get_data();
  4385. for (int i = 0; cstr[i]; i++) {
  4386. if (cstr[i] == '=' || cstr[i] == '"' || cstr[i] == ';' || cstr[i] == '[' || cstr[i] == ']' || cstr[i] < 33 || cstr[i] > 126) {
  4387. return "\"" + c_escape_multiline() + "\"";
  4388. }
  4389. }
  4390. // Keep as is
  4391. return *this;
  4392. }
  4393. // Changes made to the set of invalid characters must also be reflected in the String documentation.
  4394. static const char32_t invalid_node_name_characters[] = { '.', ':', '@', '/', '\"', UNIQUE_NODE_PREFIX[0], 0 };
  4395. String String::get_invalid_node_name_characters(bool p_allow_internal) {
  4396. // Do not use this function for critical validation.
  4397. String r;
  4398. const char32_t *c = invalid_node_name_characters;
  4399. while (*c) {
  4400. if (p_allow_internal && *c == '@') {
  4401. c++;
  4402. continue;
  4403. }
  4404. if (c != invalid_node_name_characters) {
  4405. r += " ";
  4406. }
  4407. r += String::chr(*c);
  4408. c++;
  4409. }
  4410. return r;
  4411. }
  4412. String String::validate_node_name() const {
  4413. // This is a critical validation in node addition, so it must be optimized.
  4414. const char32_t *cn = ptr();
  4415. if (cn == nullptr) {
  4416. return String();
  4417. }
  4418. bool valid = true;
  4419. uint32_t idx = 0;
  4420. while (cn[idx]) {
  4421. const char32_t *c = invalid_node_name_characters;
  4422. while (*c) {
  4423. if (cn[idx] == *c) {
  4424. valid = false;
  4425. break;
  4426. }
  4427. c++;
  4428. }
  4429. if (!valid) {
  4430. break;
  4431. }
  4432. idx++;
  4433. }
  4434. if (valid) {
  4435. return *this;
  4436. }
  4437. String validated = *this;
  4438. char32_t *nn = validated.ptrw();
  4439. while (nn[idx]) {
  4440. const char32_t *c = invalid_node_name_characters;
  4441. while (*c) {
  4442. if (nn[idx] == *c) {
  4443. nn[idx] = '_';
  4444. break;
  4445. }
  4446. c++;
  4447. }
  4448. idx++;
  4449. }
  4450. return validated;
  4451. }
  4452. String String::get_basename() const {
  4453. int pos = rfind(".");
  4454. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  4455. return *this;
  4456. }
  4457. return substr(0, pos);
  4458. }
  4459. String itos(int64_t p_val) {
  4460. return String::num_int64(p_val);
  4461. }
  4462. String uitos(uint64_t p_val) {
  4463. return String::num_uint64(p_val);
  4464. }
  4465. String rtos(double p_val) {
  4466. return String::num(p_val);
  4467. }
  4468. String rtoss(double p_val) {
  4469. return String::num_scientific(p_val);
  4470. }
  4471. // Right-pad with a character.
  4472. String String::rpad(int min_length, const String &character) const {
  4473. String s = *this;
  4474. int padding = min_length - s.length();
  4475. if (padding > 0) {
  4476. s += character.repeat(padding);
  4477. }
  4478. return s;
  4479. }
  4480. // Left-pad with a character.
  4481. String String::lpad(int min_length, const String &character) const {
  4482. String s = *this;
  4483. int padding = min_length - s.length();
  4484. if (padding > 0) {
  4485. s = character.repeat(padding) + s;
  4486. }
  4487. return s;
  4488. }
  4489. // sprintf is implemented in GDScript via:
  4490. // "fish %s pie" % "frog"
  4491. // "fish %s %d pie" % ["frog", 12]
  4492. // In case of an error, the string returned is the error description and "error" is true.
  4493. String String::sprintf(const Array &values, bool *error) const {
  4494. String formatted;
  4495. char32_t *self = (char32_t *)get_data();
  4496. bool in_format = false;
  4497. int value_index = 0;
  4498. int min_chars = 0;
  4499. int min_decimals = 0;
  4500. bool in_decimals = false;
  4501. bool pad_with_zeros = false;
  4502. bool left_justified = false;
  4503. bool show_sign = false;
  4504. bool as_unsigned = false;
  4505. if (error) {
  4506. *error = true;
  4507. }
  4508. for (; *self; self++) {
  4509. const char32_t c = *self;
  4510. if (in_format) { // We have % - let's see what else we get.
  4511. switch (c) {
  4512. case '%': { // Replace %% with %
  4513. formatted += chr(c);
  4514. in_format = false;
  4515. break;
  4516. }
  4517. case 'd': // Integer (signed)
  4518. case 'o': // Octal
  4519. case 'x': // Hexadecimal (lowercase)
  4520. case 'X': { // Hexadecimal (uppercase)
  4521. if (value_index >= values.size()) {
  4522. return "not enough arguments for format string";
  4523. }
  4524. if (!values[value_index].is_num()) {
  4525. return "a number is required";
  4526. }
  4527. int64_t value = values[value_index];
  4528. int base = 16;
  4529. bool capitalize = false;
  4530. switch (c) {
  4531. case 'd':
  4532. base = 10;
  4533. break;
  4534. case 'o':
  4535. base = 8;
  4536. break;
  4537. case 'x':
  4538. break;
  4539. case 'X':
  4540. capitalize = true;
  4541. break;
  4542. }
  4543. // Get basic number.
  4544. String str;
  4545. if (!as_unsigned) {
  4546. str = String::num_int64(ABS(value), base, capitalize);
  4547. } else {
  4548. uint64_t uvalue = *((uint64_t *)&value);
  4549. // In unsigned hex, if the value fits in 32 bits, trim it down to that.
  4550. if (base == 16 && value < 0 && value >= INT32_MIN) {
  4551. uvalue &= 0xffffffff;
  4552. }
  4553. str = String::num_uint64(uvalue, base, capitalize);
  4554. }
  4555. int number_len = str.length();
  4556. bool negative = value < 0 && !as_unsigned;
  4557. // Padding.
  4558. int pad_chars_count = (negative || show_sign) ? min_chars - 1 : min_chars;
  4559. String pad_char = pad_with_zeros ? String("0") : String(" ");
  4560. if (left_justified) {
  4561. str = str.rpad(pad_chars_count, pad_char);
  4562. } else {
  4563. str = str.lpad(pad_chars_count, pad_char);
  4564. }
  4565. // Sign.
  4566. if (show_sign || negative) {
  4567. String sign_char = negative ? "-" : "+";
  4568. if (left_justified) {
  4569. str = str.insert(0, sign_char);
  4570. } else {
  4571. str = str.insert(pad_with_zeros ? 0 : str.length() - number_len, sign_char);
  4572. }
  4573. }
  4574. formatted += str;
  4575. ++value_index;
  4576. in_format = false;
  4577. break;
  4578. }
  4579. case 'f': { // Float
  4580. if (value_index >= values.size()) {
  4581. return "not enough arguments for format string";
  4582. }
  4583. if (!values[value_index].is_num()) {
  4584. return "a number is required";
  4585. }
  4586. double value = values[value_index];
  4587. bool is_negative = signbit(value);
  4588. String str = String::num(Math::abs(value), min_decimals);
  4589. const bool is_finite = Math::is_finite(value);
  4590. // Pad decimals out.
  4591. if (is_finite) {
  4592. str = str.pad_decimals(min_decimals);
  4593. }
  4594. int initial_len = str.length();
  4595. // Padding. Leave room for sign later if required.
  4596. int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars;
  4597. String pad_char = (pad_with_zeros && is_finite) ? String("0") : String(" "); // Never pad NaN or inf with zeros
  4598. if (left_justified) {
  4599. str = str.rpad(pad_chars_count, pad_char);
  4600. } else {
  4601. str = str.lpad(pad_chars_count, pad_char);
  4602. }
  4603. // Add sign if needed.
  4604. if (show_sign || is_negative) {
  4605. String sign_char = is_negative ? "-" : "+";
  4606. if (left_justified) {
  4607. str = str.insert(0, sign_char);
  4608. } else {
  4609. str = str.insert(pad_with_zeros ? 0 : str.length() - initial_len, sign_char);
  4610. }
  4611. }
  4612. formatted += str;
  4613. ++value_index;
  4614. in_format = false;
  4615. break;
  4616. }
  4617. case 'v': { // Vector2/3/4/2i/3i/4i
  4618. if (value_index >= values.size()) {
  4619. return "not enough arguments for format string";
  4620. }
  4621. int count;
  4622. switch (values[value_index].get_type()) {
  4623. case Variant::VECTOR2:
  4624. case Variant::VECTOR2I: {
  4625. count = 2;
  4626. } break;
  4627. case Variant::VECTOR3:
  4628. case Variant::VECTOR3I: {
  4629. count = 3;
  4630. } break;
  4631. case Variant::VECTOR4:
  4632. case Variant::VECTOR4I: {
  4633. count = 4;
  4634. } break;
  4635. default: {
  4636. return "%v requires a vector type (Vector2/3/4/2i/3i/4i)";
  4637. }
  4638. }
  4639. Vector4 vec = values[value_index];
  4640. String str = "(";
  4641. for (int i = 0; i < count; i++) {
  4642. double val = vec[i];
  4643. String number_str = String::num(Math::abs(val), min_decimals);
  4644. const bool is_finite = Math::is_finite(val);
  4645. // Pad decimals out.
  4646. if (is_finite) {
  4647. number_str = number_str.pad_decimals(min_decimals);
  4648. }
  4649. int initial_len = number_str.length();
  4650. // Padding. Leave room for sign later if required.
  4651. int pad_chars_count = val < 0 ? min_chars - 1 : min_chars;
  4652. String pad_char = (pad_with_zeros && is_finite) ? String("0") : String(" "); // Never pad NaN or inf with zeros
  4653. if (left_justified) {
  4654. number_str = number_str.rpad(pad_chars_count, pad_char);
  4655. } else {
  4656. number_str = number_str.lpad(pad_chars_count, pad_char);
  4657. }
  4658. // Add sign if needed.
  4659. if (val < 0) {
  4660. if (left_justified) {
  4661. number_str = number_str.insert(0, "-");
  4662. } else {
  4663. number_str = number_str.insert(pad_with_zeros ? 0 : number_str.length() - initial_len, "-");
  4664. }
  4665. }
  4666. // Add number to combined string
  4667. str += number_str;
  4668. if (i < count - 1) {
  4669. str += ", ";
  4670. }
  4671. }
  4672. str += ")";
  4673. formatted += str;
  4674. ++value_index;
  4675. in_format = false;
  4676. break;
  4677. }
  4678. case 's': { // String
  4679. if (value_index >= values.size()) {
  4680. return "not enough arguments for format string";
  4681. }
  4682. String str = values[value_index];
  4683. // Padding.
  4684. if (left_justified) {
  4685. str = str.rpad(min_chars);
  4686. } else {
  4687. str = str.lpad(min_chars);
  4688. }
  4689. formatted += str;
  4690. ++value_index;
  4691. in_format = false;
  4692. break;
  4693. }
  4694. case 'c': {
  4695. if (value_index >= values.size()) {
  4696. return "not enough arguments for format string";
  4697. }
  4698. // Convert to character.
  4699. String str;
  4700. if (values[value_index].is_num()) {
  4701. int value = values[value_index];
  4702. if (value < 0) {
  4703. return "unsigned integer is lower than minimum";
  4704. } else if (value >= 0xd800 && value <= 0xdfff) {
  4705. return "unsigned integer is invalid Unicode character";
  4706. } else if (value > 0x10ffff) {
  4707. return "unsigned integer is greater than maximum";
  4708. }
  4709. str = chr(values[value_index]);
  4710. } else if (values[value_index].get_type() == Variant::STRING) {
  4711. str = values[value_index];
  4712. if (str.length() != 1) {
  4713. return "%c requires number or single-character string";
  4714. }
  4715. } else {
  4716. return "%c requires number or single-character string";
  4717. }
  4718. // Padding.
  4719. if (left_justified) {
  4720. str = str.rpad(min_chars);
  4721. } else {
  4722. str = str.lpad(min_chars);
  4723. }
  4724. formatted += str;
  4725. ++value_index;
  4726. in_format = false;
  4727. break;
  4728. }
  4729. case '-': { // Left justify
  4730. left_justified = true;
  4731. break;
  4732. }
  4733. case '+': { // Show + if positive.
  4734. show_sign = true;
  4735. break;
  4736. }
  4737. case 'u': { // Treat as unsigned (for int/hex).
  4738. as_unsigned = true;
  4739. break;
  4740. }
  4741. case '0':
  4742. case '1':
  4743. case '2':
  4744. case '3':
  4745. case '4':
  4746. case '5':
  4747. case '6':
  4748. case '7':
  4749. case '8':
  4750. case '9': {
  4751. int n = c - '0';
  4752. if (in_decimals) {
  4753. min_decimals *= 10;
  4754. min_decimals += n;
  4755. } else {
  4756. if (c == '0' && min_chars == 0) {
  4757. if (left_justified) {
  4758. WARN_PRINT("'0' flag ignored with '-' flag in string format");
  4759. } else {
  4760. pad_with_zeros = true;
  4761. }
  4762. } else {
  4763. min_chars *= 10;
  4764. min_chars += n;
  4765. }
  4766. }
  4767. break;
  4768. }
  4769. case '.': { // Float/Vector separator.
  4770. if (in_decimals) {
  4771. return "too many decimal points in format";
  4772. }
  4773. in_decimals = true;
  4774. min_decimals = 0; // We want to add the value manually.
  4775. break;
  4776. }
  4777. case '*': { // Dynamic width, based on value.
  4778. if (value_index >= values.size()) {
  4779. return "not enough arguments for format string";
  4780. }
  4781. Variant::Type value_type = values[value_index].get_type();
  4782. if (!values[value_index].is_num() &&
  4783. value_type != Variant::VECTOR2 && value_type != Variant::VECTOR2I &&
  4784. value_type != Variant::VECTOR3 && value_type != Variant::VECTOR3I &&
  4785. value_type != Variant::VECTOR4 && value_type != Variant::VECTOR4I) {
  4786. return "* wants number or vector";
  4787. }
  4788. int size = values[value_index];
  4789. if (in_decimals) {
  4790. min_decimals = size;
  4791. } else {
  4792. min_chars = size;
  4793. }
  4794. ++value_index;
  4795. break;
  4796. }
  4797. default: {
  4798. return "unsupported format character";
  4799. }
  4800. }
  4801. } else { // Not in format string.
  4802. switch (c) {
  4803. case '%':
  4804. in_format = true;
  4805. // Back to defaults:
  4806. min_chars = 0;
  4807. min_decimals = 6;
  4808. pad_with_zeros = false;
  4809. left_justified = false;
  4810. show_sign = false;
  4811. in_decimals = false;
  4812. break;
  4813. default:
  4814. formatted += chr(c);
  4815. }
  4816. }
  4817. }
  4818. if (in_format) {
  4819. return "incomplete format";
  4820. }
  4821. if (value_index != values.size()) {
  4822. return "not all arguments converted during string formatting";
  4823. }
  4824. if (error) {
  4825. *error = false;
  4826. }
  4827. return formatted;
  4828. }
  4829. String String::quote(const String &quotechar) const {
  4830. return quotechar + *this + quotechar;
  4831. }
  4832. String String::unquote() const {
  4833. if (!is_quoted()) {
  4834. return *this;
  4835. }
  4836. return substr(1, length() - 2);
  4837. }
  4838. Vector<uint8_t> String::to_ascii_buffer() const {
  4839. const String *s = this;
  4840. if (s->is_empty()) {
  4841. return Vector<uint8_t>();
  4842. }
  4843. CharString charstr = s->ascii();
  4844. Vector<uint8_t> retval;
  4845. size_t len = charstr.length();
  4846. retval.resize(len);
  4847. uint8_t *w = retval.ptrw();
  4848. memcpy(w, charstr.ptr(), len);
  4849. return retval;
  4850. }
  4851. Vector<uint8_t> String::to_utf8_buffer() const {
  4852. const String *s = this;
  4853. if (s->is_empty()) {
  4854. return Vector<uint8_t>();
  4855. }
  4856. CharString charstr = s->utf8();
  4857. Vector<uint8_t> retval;
  4858. size_t len = charstr.length();
  4859. retval.resize(len);
  4860. uint8_t *w = retval.ptrw();
  4861. memcpy(w, charstr.ptr(), len);
  4862. return retval;
  4863. }
  4864. Vector<uint8_t> String::to_utf16_buffer() const {
  4865. const String *s = this;
  4866. if (s->is_empty()) {
  4867. return Vector<uint8_t>();
  4868. }
  4869. Char16String charstr = s->utf16();
  4870. Vector<uint8_t> retval;
  4871. size_t len = charstr.length() * sizeof(char16_t);
  4872. retval.resize(len);
  4873. uint8_t *w = retval.ptrw();
  4874. memcpy(w, (const void *)charstr.ptr(), len);
  4875. return retval;
  4876. }
  4877. Vector<uint8_t> String::to_utf32_buffer() const {
  4878. const String *s = this;
  4879. if (s->is_empty()) {
  4880. return Vector<uint8_t>();
  4881. }
  4882. Vector<uint8_t> retval;
  4883. size_t len = s->length() * sizeof(char32_t);
  4884. retval.resize(len);
  4885. uint8_t *w = retval.ptrw();
  4886. memcpy(w, (const void *)s->ptr(), len);
  4887. return retval;
  4888. }
  4889. Vector<uint8_t> String::to_wchar_buffer() const {
  4890. #ifdef WINDOWS_ENABLED
  4891. return to_utf16_buffer();
  4892. #else
  4893. return to_utf32_buffer();
  4894. #endif
  4895. }
  4896. #ifdef TOOLS_ENABLED
  4897. /**
  4898. * "Tools TRanslate". Performs string replacement for internationalization
  4899. * within the editor. A translation context can optionally be specified to
  4900. * disambiguate between identical source strings in translations. When
  4901. * placeholders are desired, use `vformat(TTR("Example: %s"), some_string)`.
  4902. * If a string mentions a quantity (and may therefore need a dynamic plural form),
  4903. * use `TTRN()` instead of `TTR()`.
  4904. *
  4905. * NOTE: Only use `TTR()` in editor-only code (typically within the `editor/` folder).
  4906. * For translations that can be supplied by exported projects, use `RTR()` instead.
  4907. */
  4908. String TTR(const String &p_text, const String &p_context) {
  4909. if (TranslationServer::get_singleton()) {
  4910. return TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  4911. }
  4912. return p_text;
  4913. }
  4914. /**
  4915. * "Tools TRanslate for N items". Performs string replacement for
  4916. * internationalization within the editor. A translation context can optionally
  4917. * be specified to disambiguate between identical source strings in
  4918. * translations. Use `TTR()` if the string doesn't need dynamic plural form.
  4919. * When placeholders are desired, use
  4920. * `vformat(TTRN("%d item", "%d items", some_integer), some_integer)`.
  4921. * The placeholder must be present in both strings to avoid run-time warnings in `vformat()`.
  4922. *
  4923. * NOTE: Only use `TTRN()` in editor-only code (typically within the `editor/` folder).
  4924. * For translations that can be supplied by exported projects, use `RTRN()` instead.
  4925. */
  4926. String TTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4927. if (TranslationServer::get_singleton()) {
  4928. return TranslationServer::get_singleton()->tool_translate_plural(p_text, p_text_plural, p_n, p_context);
  4929. }
  4930. // Return message based on English plural rule if translation is not possible.
  4931. if (p_n == 1) {
  4932. return p_text;
  4933. }
  4934. return p_text_plural;
  4935. }
  4936. /**
  4937. * "Docs TRanslate". Used for the editor class reference documentation,
  4938. * 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 DTR(const String &p_text, const String &p_context) {
  4943. // Comes straight from the XML, so remove indentation and any trailing whitespace.
  4944. const String text = p_text.dedent().strip_edges();
  4945. if (TranslationServer::get_singleton()) {
  4946. return String(TranslationServer::get_singleton()->doc_translate(text, p_context)).replace("$DOCS_URL", VERSION_DOCS_URL);
  4947. }
  4948. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  4949. }
  4950. /**
  4951. * "Docs TRanslate for N items". Used for the editor class reference documentation
  4952. * (with support for plurals), handling descriptions extracted from the XML.
  4953. * It also replaces `$DOCS_URL` with the actual URL to the documentation's branch,
  4954. * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
  4955. */
  4956. String DTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4957. const String text = p_text.dedent().strip_edges();
  4958. const String text_plural = p_text_plural.dedent().strip_edges();
  4959. if (TranslationServer::get_singleton()) {
  4960. return String(TranslationServer::get_singleton()->doc_translate_plural(text, text_plural, p_n, p_context)).replace("$DOCS_URL", VERSION_DOCS_URL);
  4961. }
  4962. // Return message based on English plural rule if translation is not possible.
  4963. if (p_n == 1) {
  4964. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  4965. }
  4966. return text_plural.replace("$DOCS_URL", VERSION_DOCS_URL);
  4967. }
  4968. #endif
  4969. /**
  4970. * "Run-time TRanslate". Performs string replacement for internationalization
  4971. * without the editor. A translation context can optionally be specified to
  4972. * disambiguate between identical source strings in translations. When
  4973. * placeholders are desired, use `vformat(RTR("Example: %s"), some_string)`.
  4974. * If a string mentions a quantity (and may therefore need a dynamic plural form),
  4975. * use `RTRN()` instead of `RTR()`.
  4976. *
  4977. * NOTE: Do not use `RTR()` in editor-only code (typically within the `editor/`
  4978. * folder). For editor translations, use `TTR()` instead.
  4979. */
  4980. String RTR(const String &p_text, const String &p_context) {
  4981. if (TranslationServer::get_singleton()) {
  4982. String rtr = TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  4983. if (rtr.is_empty() || rtr == p_text) {
  4984. return TranslationServer::get_singleton()->translate(p_text, p_context);
  4985. }
  4986. return rtr;
  4987. }
  4988. return p_text;
  4989. }
  4990. /**
  4991. * "Run-time TRanslate for N items". Performs string replacement for
  4992. * internationalization without the editor. A translation context can optionally
  4993. * be specified to disambiguate between identical source strings in translations.
  4994. * Use `RTR()` if the string doesn't need dynamic plural form. When placeholders
  4995. * are desired, use `vformat(RTRN("%d item", "%d items", some_integer), some_integer)`.
  4996. * The placeholder must be present in both strings to avoid run-time warnings in `vformat()`.
  4997. *
  4998. * NOTE: Do not use `RTRN()` in editor-only code (typically within the `editor/`
  4999. * folder). For editor translations, use `TTRN()` instead.
  5000. */
  5001. String RTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  5002. if (TranslationServer::get_singleton()) {
  5003. String rtr = TranslationServer::get_singleton()->tool_translate_plural(p_text, p_text_plural, p_n, p_context);
  5004. if (rtr.is_empty() || rtr == p_text || rtr == p_text_plural) {
  5005. return TranslationServer::get_singleton()->translate_plural(p_text, p_text_plural, p_n, p_context);
  5006. }
  5007. return rtr;
  5008. }
  5009. // Return message based on English plural rule if translation is not possible.
  5010. if (p_n == 1) {
  5011. return p_text;
  5012. }
  5013. return p_text_plural;
  5014. }