ustring.cpp 136 KB

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