ustring.cpp 131 KB

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