ustring.cpp 137 KB

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