ustring.cpp 137 KB

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