ustring.cpp 138 KB

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