ustring.cpp 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416
  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 = this->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 = this->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. signed char String::naturalcasecmp_to(const String &p_str) const {
  773. const char32_t *this_str = get_data();
  774. const char32_t *that_str = p_str.get_data();
  775. if (this_str && that_str) {
  776. while (*this_str == '.' || *that_str == '.') {
  777. if (*this_str++ != '.') {
  778. return 1;
  779. }
  780. if (*that_str++ != '.') {
  781. return -1;
  782. }
  783. if (!*that_str) {
  784. return 1;
  785. }
  786. if (!*this_str) {
  787. return -1;
  788. }
  789. }
  790. while (*this_str) {
  791. if (!*that_str) {
  792. return 1;
  793. } else if (is_digit(*this_str)) {
  794. if (!is_digit(*that_str)) {
  795. return -1;
  796. }
  797. signed char ret = natural_cmp_common(this_str, that_str);
  798. if (ret) {
  799. return ret;
  800. }
  801. } else if (is_digit(*that_str)) {
  802. return 1;
  803. } else {
  804. if (*this_str < *that_str) { // If current character in this is less, we are less.
  805. return -1;
  806. } else if (*this_str > *that_str) { // If current character in this is greater, we are greater.
  807. return 1;
  808. }
  809. this_str++;
  810. that_str++;
  811. }
  812. }
  813. if (*that_str) {
  814. return -1;
  815. }
  816. }
  817. return 0;
  818. }
  819. signed char String::naturalnocasecmp_to(const String &p_str) const {
  820. const char32_t *this_str = get_data();
  821. const char32_t *that_str = p_str.get_data();
  822. if (this_str && that_str) {
  823. while (*this_str == '.' || *that_str == '.') {
  824. if (*this_str++ != '.') {
  825. return 1;
  826. }
  827. if (*that_str++ != '.') {
  828. return -1;
  829. }
  830. if (!*that_str) {
  831. return 1;
  832. }
  833. if (!*this_str) {
  834. return -1;
  835. }
  836. }
  837. while (*this_str) {
  838. if (!*that_str) {
  839. return 1;
  840. } else if (is_digit(*this_str)) {
  841. if (!is_digit(*that_str)) {
  842. return -1;
  843. }
  844. signed char ret = natural_cmp_common(this_str, that_str);
  845. if (ret) {
  846. return ret;
  847. }
  848. } else if (is_digit(*that_str)) {
  849. return 1;
  850. } else {
  851. if (_find_upper(*this_str) < _find_upper(*that_str)) { // If current character in this is less, we are less.
  852. return -1;
  853. } else if (_find_upper(*this_str) > _find_upper(*that_str)) { // If current character in this is greater, we are greater.
  854. return 1;
  855. }
  856. this_str++;
  857. that_str++;
  858. }
  859. }
  860. if (*that_str) {
  861. return -1;
  862. }
  863. }
  864. return 0;
  865. }
  866. const char32_t *String::get_data() const {
  867. static const char32_t zero = 0;
  868. return size() ? &operator[](0) : &zero;
  869. }
  870. String String::_camelcase_to_underscore() const {
  871. const char32_t *cstr = get_data();
  872. String new_string;
  873. int start_index = 0;
  874. for (int i = 1; i < this->size(); i++) {
  875. bool is_prev_upper = is_ascii_upper_case(cstr[i - 1]);
  876. bool is_prev_lower = is_ascii_lower_case(cstr[i - 1]);
  877. bool is_prev_digit = is_digit(cstr[i - 1]);
  878. bool is_curr_upper = is_ascii_upper_case(cstr[i]);
  879. bool is_curr_lower = is_ascii_lower_case(cstr[i]);
  880. bool is_curr_digit = is_digit(cstr[i]);
  881. bool is_next_lower = false;
  882. if (i + 1 < this->size()) {
  883. is_next_lower = is_ascii_lower_case(cstr[i + 1]);
  884. }
  885. const bool cond_a = is_prev_lower && is_curr_upper; // aA
  886. const bool cond_b = (is_prev_upper || is_prev_digit) && is_curr_upper && is_next_lower; // AAa, 2Aa
  887. const bool cond_c = is_prev_digit && is_curr_lower && is_next_lower; // 2aa
  888. const bool cond_d = (is_prev_upper || is_prev_lower) && is_curr_digit; // A2, a2
  889. if (cond_a || cond_b || cond_c || cond_d) {
  890. new_string += this->substr(start_index, i - start_index) + "_";
  891. start_index = i;
  892. }
  893. }
  894. new_string += this->substr(start_index, this->size() - start_index);
  895. return new_string.to_lower();
  896. }
  897. String String::capitalize() const {
  898. String aux = this->_camelcase_to_underscore().replace("_", " ").strip_edges();
  899. String cap;
  900. for (int i = 0; i < aux.get_slice_count(" "); i++) {
  901. String slice = aux.get_slicec(' ', i);
  902. if (slice.length() > 0) {
  903. slice[0] = _find_upper(slice[0]);
  904. if (i > 0) {
  905. cap += " ";
  906. }
  907. cap += slice;
  908. }
  909. }
  910. return cap;
  911. }
  912. String String::to_camel_case() const {
  913. String s = this->to_pascal_case();
  914. if (!s.is_empty()) {
  915. s[0] = _find_lower(s[0]);
  916. }
  917. return s;
  918. }
  919. String String::to_pascal_case() const {
  920. return this->capitalize().replace(" ", "");
  921. }
  922. String String::to_snake_case() const {
  923. return this->_camelcase_to_underscore().replace(" ", "_").strip_edges();
  924. }
  925. String String::get_with_code_lines() const {
  926. const Vector<String> lines = split("\n");
  927. String ret;
  928. for (int i = 0; i < lines.size(); i++) {
  929. if (i > 0) {
  930. ret += "\n";
  931. }
  932. ret += vformat("%4d | %s", i + 1, lines[i]);
  933. }
  934. return ret;
  935. }
  936. int String::get_slice_count(String p_splitter) const {
  937. if (is_empty()) {
  938. return 0;
  939. }
  940. if (p_splitter.is_empty()) {
  941. return 0;
  942. }
  943. int pos = 0;
  944. int slices = 1;
  945. while ((pos = find(p_splitter, pos)) >= 0) {
  946. slices++;
  947. pos += p_splitter.length();
  948. }
  949. return slices;
  950. }
  951. String String::get_slice(String p_splitter, int p_slice) const {
  952. if (is_empty() || p_splitter.is_empty()) {
  953. return "";
  954. }
  955. int pos = 0;
  956. int prev_pos = 0;
  957. //int slices=1;
  958. if (p_slice < 0) {
  959. return "";
  960. }
  961. if (find(p_splitter) == -1) {
  962. return *this;
  963. }
  964. int i = 0;
  965. while (true) {
  966. pos = find(p_splitter, pos);
  967. if (pos == -1) {
  968. pos = length(); //reached end
  969. }
  970. int from = prev_pos;
  971. //int to=pos;
  972. if (p_slice == i) {
  973. return substr(from, pos - from);
  974. }
  975. if (pos == length()) { //reached end and no find
  976. break;
  977. }
  978. pos += p_splitter.length();
  979. prev_pos = pos;
  980. i++;
  981. }
  982. return ""; //no find!
  983. }
  984. String String::get_slicec(char32_t p_splitter, int p_slice) const {
  985. if (is_empty()) {
  986. return String();
  987. }
  988. if (p_slice < 0) {
  989. return String();
  990. }
  991. const char32_t *c = this->ptr();
  992. int i = 0;
  993. int prev = 0;
  994. int count = 0;
  995. while (true) {
  996. if (c[i] == 0 || c[i] == p_splitter) {
  997. if (p_slice == count) {
  998. return substr(prev, i - prev);
  999. } else if (c[i] == 0) {
  1000. return String();
  1001. } else {
  1002. count++;
  1003. prev = i + 1;
  1004. }
  1005. }
  1006. i++;
  1007. }
  1008. }
  1009. Vector<String> String::split_spaces() const {
  1010. Vector<String> ret;
  1011. int from = 0;
  1012. int i = 0;
  1013. int len = length();
  1014. if (len == 0) {
  1015. return ret;
  1016. }
  1017. bool inside = false;
  1018. while (true) {
  1019. bool empty = operator[](i) < 33;
  1020. if (i == 0) {
  1021. inside = !empty;
  1022. }
  1023. if (!empty && !inside) {
  1024. inside = true;
  1025. from = i;
  1026. }
  1027. if (empty && inside) {
  1028. ret.push_back(substr(from, i - from));
  1029. inside = false;
  1030. }
  1031. if (i == len) {
  1032. break;
  1033. }
  1034. i++;
  1035. }
  1036. return ret;
  1037. }
  1038. Vector<String> String::split(const String &p_splitter, bool p_allow_empty, int p_maxsplit) const {
  1039. Vector<String> ret;
  1040. if (is_empty()) {
  1041. if (p_allow_empty) {
  1042. ret.push_back("");
  1043. }
  1044. return ret;
  1045. }
  1046. int from = 0;
  1047. int len = length();
  1048. while (true) {
  1049. int end;
  1050. if (p_splitter.is_empty()) {
  1051. end = from + 1;
  1052. } else {
  1053. end = find(p_splitter, from);
  1054. if (end < 0) {
  1055. end = len;
  1056. }
  1057. }
  1058. if (p_allow_empty || (end > from)) {
  1059. if (p_maxsplit <= 0) {
  1060. ret.push_back(substr(from, end - from));
  1061. } else {
  1062. // Put rest of the string and leave cycle.
  1063. if (p_maxsplit == ret.size()) {
  1064. ret.push_back(substr(from, len));
  1065. break;
  1066. }
  1067. // Otherwise, push items until positive limit is reached.
  1068. ret.push_back(substr(from, end - from));
  1069. }
  1070. }
  1071. if (end == len) {
  1072. break;
  1073. }
  1074. from = end + p_splitter.length();
  1075. }
  1076. return ret;
  1077. }
  1078. Vector<String> String::rsplit(const String &p_splitter, bool p_allow_empty, int p_maxsplit) const {
  1079. Vector<String> ret;
  1080. const int len = length();
  1081. int remaining_len = len;
  1082. while (true) {
  1083. if (remaining_len < p_splitter.length() || (p_maxsplit > 0 && p_maxsplit == ret.size())) {
  1084. // no room for another splitter or hit max splits, push what's left and we're done
  1085. if (p_allow_empty || remaining_len > 0) {
  1086. ret.push_back(substr(0, remaining_len));
  1087. }
  1088. break;
  1089. }
  1090. int left_edge;
  1091. if (p_splitter.is_empty()) {
  1092. left_edge = remaining_len - 1;
  1093. if (left_edge == 0) {
  1094. left_edge--; // Skip to the < 0 condition.
  1095. }
  1096. } else {
  1097. left_edge = rfind(p_splitter, remaining_len - p_splitter.length());
  1098. }
  1099. if (left_edge < 0) {
  1100. // no more splitters, we're done
  1101. ret.push_back(substr(0, remaining_len));
  1102. break;
  1103. }
  1104. int substr_start = left_edge + p_splitter.length();
  1105. if (p_allow_empty || substr_start < remaining_len) {
  1106. ret.push_back(substr(substr_start, remaining_len - substr_start));
  1107. }
  1108. remaining_len = left_edge;
  1109. }
  1110. ret.reverse();
  1111. return ret;
  1112. }
  1113. Vector<double> String::split_floats(const String &p_splitter, bool p_allow_empty) const {
  1114. Vector<double> ret;
  1115. int from = 0;
  1116. int len = length();
  1117. while (true) {
  1118. int end = find(p_splitter, from);
  1119. if (end < 0) {
  1120. end = len;
  1121. }
  1122. if (p_allow_empty || (end > from)) {
  1123. ret.push_back(String::to_float(&get_data()[from]));
  1124. }
  1125. if (end == len) {
  1126. break;
  1127. }
  1128. from = end + p_splitter.length();
  1129. }
  1130. return ret;
  1131. }
  1132. Vector<float> String::split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
  1133. Vector<float> ret;
  1134. int from = 0;
  1135. int len = length();
  1136. while (true) {
  1137. int idx;
  1138. int end = findmk(p_splitters, from, &idx);
  1139. int spl_len = 1;
  1140. if (end < 0) {
  1141. end = len;
  1142. } else {
  1143. spl_len = p_splitters[idx].length();
  1144. }
  1145. if (p_allow_empty || (end > from)) {
  1146. ret.push_back(String::to_float(&get_data()[from]));
  1147. }
  1148. if (end == len) {
  1149. break;
  1150. }
  1151. from = end + spl_len;
  1152. }
  1153. return ret;
  1154. }
  1155. Vector<int> String::split_ints(const String &p_splitter, bool p_allow_empty) const {
  1156. Vector<int> ret;
  1157. int from = 0;
  1158. int len = length();
  1159. while (true) {
  1160. int end = find(p_splitter, from);
  1161. if (end < 0) {
  1162. end = len;
  1163. }
  1164. if (p_allow_empty || (end > from)) {
  1165. ret.push_back(String::to_int(&get_data()[from], end - from));
  1166. }
  1167. if (end == len) {
  1168. break;
  1169. }
  1170. from = end + p_splitter.length();
  1171. }
  1172. return ret;
  1173. }
  1174. Vector<int> String::split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
  1175. Vector<int> ret;
  1176. int from = 0;
  1177. int len = length();
  1178. while (true) {
  1179. int idx;
  1180. int end = findmk(p_splitters, from, &idx);
  1181. int spl_len = 1;
  1182. if (end < 0) {
  1183. end = len;
  1184. } else {
  1185. spl_len = p_splitters[idx].length();
  1186. }
  1187. if (p_allow_empty || (end > from)) {
  1188. ret.push_back(String::to_int(&get_data()[from], end - from));
  1189. }
  1190. if (end == len) {
  1191. break;
  1192. }
  1193. from = end + spl_len;
  1194. }
  1195. return ret;
  1196. }
  1197. String String::join(Vector<String> parts) const {
  1198. String ret;
  1199. for (int i = 0; i < parts.size(); ++i) {
  1200. if (i > 0) {
  1201. ret += *this;
  1202. }
  1203. ret += parts[i];
  1204. }
  1205. return ret;
  1206. }
  1207. char32_t String::char_uppercase(char32_t p_char) {
  1208. return _find_upper(p_char);
  1209. }
  1210. char32_t String::char_lowercase(char32_t p_char) {
  1211. return _find_lower(p_char);
  1212. }
  1213. String String::to_upper() const {
  1214. String upper = *this;
  1215. for (int i = 0; i < upper.size(); i++) {
  1216. const char32_t s = upper[i];
  1217. const char32_t t = _find_upper(s);
  1218. if (s != t) { // avoid copy on write
  1219. upper[i] = t;
  1220. }
  1221. }
  1222. return upper;
  1223. }
  1224. String String::to_lower() const {
  1225. String lower = *this;
  1226. for (int i = 0; i < lower.size(); i++) {
  1227. const char32_t s = lower[i];
  1228. const char32_t t = _find_lower(s);
  1229. if (s != t) { // avoid copy on write
  1230. lower[i] = t;
  1231. }
  1232. }
  1233. return lower;
  1234. }
  1235. String String::chr(char32_t p_char) {
  1236. char32_t c[2] = { p_char, 0 };
  1237. return String(c);
  1238. }
  1239. String String::num(double p_num, int p_decimals) {
  1240. if (Math::is_nan(p_num)) {
  1241. return "nan";
  1242. }
  1243. if (Math::is_inf(p_num)) {
  1244. if (signbit(p_num)) {
  1245. return "-inf";
  1246. } else {
  1247. return "inf";
  1248. }
  1249. }
  1250. if (p_decimals < 0) {
  1251. p_decimals = 14;
  1252. const double abs_num = Math::abs(p_num);
  1253. if (abs_num > 10) {
  1254. // We want to align the digits to the above reasonable default, so we only
  1255. // need to subtract log10 for numbers with a positive power of ten.
  1256. p_decimals -= (int)floor(log10(abs_num));
  1257. }
  1258. }
  1259. if (p_decimals > MAX_DECIMALS) {
  1260. p_decimals = MAX_DECIMALS;
  1261. }
  1262. char fmt[7];
  1263. fmt[0] = '%';
  1264. fmt[1] = '.';
  1265. if (p_decimals < 0) {
  1266. fmt[1] = 'l';
  1267. fmt[2] = 'f';
  1268. fmt[3] = 0;
  1269. } else if (p_decimals < 10) {
  1270. fmt[2] = '0' + p_decimals;
  1271. fmt[3] = 'l';
  1272. fmt[4] = 'f';
  1273. fmt[5] = 0;
  1274. } else {
  1275. fmt[2] = '0' + (p_decimals / 10);
  1276. fmt[3] = '0' + (p_decimals % 10);
  1277. fmt[4] = 'l';
  1278. fmt[5] = 'f';
  1279. fmt[6] = 0;
  1280. }
  1281. // if we want to convert a double with as much decimal places as as
  1282. // DBL_MAX or DBL_MIN then we would theoretically need a buffer of at least
  1283. // DBL_MAX_10_EXP + 2 for DBL_MAX and DBL_MAX_10_EXP + 4 for DBL_MIN.
  1284. // BUT those values where still giving me exceptions, so I tested from
  1285. // DBL_MAX_10_EXP + 10 incrementing one by one and DBL_MAX_10_EXP + 17 (325)
  1286. // was the first buffer size not to throw an exception
  1287. char buf[325];
  1288. #if defined(__GNUC__) || defined(_MSC_VER)
  1289. // PLEASE NOTE that, albeit vcrt online reference states that snprintf
  1290. // should safely truncate the output to the given buffer size, we have
  1291. // found a case where this is not true, so we should create a buffer
  1292. // as big as needed
  1293. snprintf(buf, 325, fmt, p_num);
  1294. #else
  1295. sprintf(buf, fmt, p_num);
  1296. #endif
  1297. buf[324] = 0;
  1298. //destroy trailing zeroes
  1299. {
  1300. bool period = false;
  1301. int z = 0;
  1302. while (buf[z]) {
  1303. if (buf[z] == '.') {
  1304. period = true;
  1305. }
  1306. z++;
  1307. }
  1308. if (period) {
  1309. z--;
  1310. while (z > 0) {
  1311. if (buf[z] == '0') {
  1312. buf[z] = 0;
  1313. } else if (buf[z] == '.') {
  1314. buf[z] = 0;
  1315. break;
  1316. } else {
  1317. break;
  1318. }
  1319. z--;
  1320. }
  1321. }
  1322. }
  1323. return buf;
  1324. }
  1325. String String::num_int64(int64_t p_num, int base, bool capitalize_hex) {
  1326. bool sign = p_num < 0;
  1327. int64_t n = p_num;
  1328. int chars = 0;
  1329. do {
  1330. n /= base;
  1331. chars++;
  1332. } while (n);
  1333. if (sign) {
  1334. chars++;
  1335. }
  1336. String s;
  1337. s.resize(chars + 1);
  1338. char32_t *c = s.ptrw();
  1339. c[chars] = 0;
  1340. n = p_num;
  1341. do {
  1342. int mod = ABS(n % base);
  1343. if (mod >= 10) {
  1344. char a = (capitalize_hex ? 'A' : 'a');
  1345. c[--chars] = a + (mod - 10);
  1346. } else {
  1347. c[--chars] = '0' + mod;
  1348. }
  1349. n /= base;
  1350. } while (n);
  1351. if (sign) {
  1352. c[0] = '-';
  1353. }
  1354. return s;
  1355. }
  1356. String String::num_uint64(uint64_t p_num, int base, bool capitalize_hex) {
  1357. uint64_t n = p_num;
  1358. int chars = 0;
  1359. do {
  1360. n /= base;
  1361. chars++;
  1362. } while (n);
  1363. String s;
  1364. s.resize(chars + 1);
  1365. char32_t *c = s.ptrw();
  1366. c[chars] = 0;
  1367. n = p_num;
  1368. do {
  1369. int mod = n % base;
  1370. if (mod >= 10) {
  1371. char a = (capitalize_hex ? 'A' : 'a');
  1372. c[--chars] = a + (mod - 10);
  1373. } else {
  1374. c[--chars] = '0' + mod;
  1375. }
  1376. n /= base;
  1377. } while (n);
  1378. return s;
  1379. }
  1380. String String::num_real(double p_num, bool p_trailing) {
  1381. if (p_num == (double)(int64_t)p_num) {
  1382. if (p_trailing) {
  1383. return num_int64((int64_t)p_num) + ".0";
  1384. } else {
  1385. return num_int64((int64_t)p_num);
  1386. }
  1387. }
  1388. #ifdef REAL_T_IS_DOUBLE
  1389. int decimals = 14;
  1390. #else
  1391. int decimals = 6;
  1392. #endif
  1393. // We want to align the digits to the above sane default, so we only need
  1394. // to subtract log10 for numbers with a positive power of ten magnitude.
  1395. double abs_num = Math::abs(p_num);
  1396. if (abs_num > 10) {
  1397. decimals -= (int)floor(log10(abs_num));
  1398. }
  1399. return num(p_num, decimals);
  1400. }
  1401. String String::num_scientific(double p_num) {
  1402. if (Math::is_nan(p_num)) {
  1403. return "nan";
  1404. }
  1405. if (Math::is_inf(p_num)) {
  1406. if (signbit(p_num)) {
  1407. return "-inf";
  1408. } else {
  1409. return "inf";
  1410. }
  1411. }
  1412. char buf[256];
  1413. #if defined(__GNUC__) || defined(_MSC_VER)
  1414. #if defined(__MINGW32__) && defined(_TWO_DIGIT_EXPONENT) && !defined(_UCRT)
  1415. // MinGW requires _set_output_format() to conform to C99 output for printf
  1416. unsigned int old_exponent_format = _set_output_format(_TWO_DIGIT_EXPONENT);
  1417. #endif
  1418. snprintf(buf, 256, "%lg", p_num);
  1419. #if defined(__MINGW32__) && defined(_TWO_DIGIT_EXPONENT) && !defined(_UCRT)
  1420. _set_output_format(old_exponent_format);
  1421. #endif
  1422. #else
  1423. sprintf(buf, "%.16lg", p_num);
  1424. #endif
  1425. buf[255] = 0;
  1426. return buf;
  1427. }
  1428. String String::md5(const uint8_t *p_md5) {
  1429. return String::hex_encode_buffer(p_md5, 16);
  1430. }
  1431. String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
  1432. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  1433. String ret;
  1434. char v[2] = { 0, 0 };
  1435. for (int i = 0; i < p_len; i++) {
  1436. v[0] = hex[p_buffer[i] >> 4];
  1437. ret += v;
  1438. v[0] = hex[p_buffer[i] & 0xF];
  1439. ret += v;
  1440. }
  1441. return ret;
  1442. }
  1443. Vector<uint8_t> String::hex_decode() const {
  1444. ERR_FAIL_COND_V_MSG(length() % 2 != 0, Vector<uint8_t>(), "Hexadecimal string of uneven length.");
  1445. #define HEX_TO_BYTE(m_output, m_index) \
  1446. uint8_t m_output; \
  1447. c = operator[](m_index); \
  1448. if (is_digit(c)) { \
  1449. m_output = c - '0'; \
  1450. } else if (c >= 'a' && c <= 'f') { \
  1451. m_output = c - 'a' + 10; \
  1452. } else if (c >= 'A' && c <= 'F') { \
  1453. m_output = c - 'A' + 10; \
  1454. } else { \
  1455. ERR_FAIL_V_MSG(Vector<uint8_t>(), "Invalid hexadecimal character \"" + chr(c) + "\" at index " + m_index + "."); \
  1456. }
  1457. Vector<uint8_t> out;
  1458. int len = length() / 2;
  1459. out.resize(len);
  1460. for (int i = 0; i < len; i++) {
  1461. char32_t c;
  1462. HEX_TO_BYTE(first, i * 2);
  1463. HEX_TO_BYTE(second, i * 2 + 1);
  1464. out.write[i] = first * 16 + second;
  1465. }
  1466. return out;
  1467. #undef HEX_TO_BYTE
  1468. }
  1469. void String::print_unicode_error(const String &p_message, bool p_critical) const {
  1470. if (p_critical) {
  1471. print_error(vformat(U"Unicode parsing error, some characters were replaced with � (U+FFFD): %s", p_message));
  1472. } else {
  1473. print_error(vformat("Unicode parsing error: %s", p_message));
  1474. }
  1475. }
  1476. CharString String::ascii(bool p_allow_extended) const {
  1477. if (!length()) {
  1478. return CharString();
  1479. }
  1480. CharString cs;
  1481. cs.resize(size());
  1482. for (int i = 0; i < size(); i++) {
  1483. char32_t c = operator[](i);
  1484. if ((c <= 0x7f) || (c <= 0xff && p_allow_extended)) {
  1485. cs[i] = c;
  1486. } else {
  1487. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as ASCII/Latin-1", (uint32_t)c));
  1488. cs[i] = 0x20; // ascii doesn't have a replacement character like unicode, 0x1a is sometimes used but is kinda arcane
  1489. }
  1490. }
  1491. return cs;
  1492. }
  1493. String String::utf8(const char *p_utf8, int p_len) {
  1494. String ret;
  1495. ret.parse_utf8(p_utf8, p_len);
  1496. return ret;
  1497. }
  1498. Error String::parse_utf8(const char *p_utf8, int p_len, bool p_skip_cr) {
  1499. if (!p_utf8) {
  1500. return ERR_INVALID_DATA;
  1501. }
  1502. String aux;
  1503. int cstr_size = 0;
  1504. int str_size = 0;
  1505. /* HANDLE BOM (Byte Order Mark) */
  1506. if (p_len < 0 || p_len >= 3) {
  1507. bool has_bom = uint8_t(p_utf8[0]) == 0xef && uint8_t(p_utf8[1]) == 0xbb && uint8_t(p_utf8[2]) == 0xbf;
  1508. if (has_bom) {
  1509. //8-bit encoding, byte order has no meaning in UTF-8, just skip it
  1510. if (p_len >= 0) {
  1511. p_len -= 3;
  1512. }
  1513. p_utf8 += 3;
  1514. }
  1515. }
  1516. bool decode_error = false;
  1517. bool decode_failed = false;
  1518. {
  1519. const char *ptrtmp = p_utf8;
  1520. const char *ptrtmp_limit = &p_utf8[p_len];
  1521. int skip = 0;
  1522. uint8_t c_start = 0;
  1523. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  1524. #if CHAR_MIN == 0
  1525. uint8_t c = *ptrtmp;
  1526. #else
  1527. uint8_t c = *ptrtmp >= 0 ? *ptrtmp : uint8_t(256 + *ptrtmp);
  1528. #endif
  1529. if (skip == 0) {
  1530. if (p_skip_cr && c == '\r') {
  1531. ptrtmp++;
  1532. continue;
  1533. }
  1534. /* Determine the number of characters in sequence */
  1535. if ((c & 0x80) == 0) {
  1536. skip = 0;
  1537. } else if ((c & 0xe0) == 0xc0) {
  1538. skip = 1;
  1539. } else if ((c & 0xf0) == 0xe0) {
  1540. skip = 2;
  1541. } else if ((c & 0xf8) == 0xf0) {
  1542. skip = 3;
  1543. } else if ((c & 0xfc) == 0xf8) {
  1544. skip = 4;
  1545. } else if ((c & 0xfe) == 0xfc) {
  1546. skip = 5;
  1547. } else {
  1548. skip = 0;
  1549. print_unicode_error(vformat("Invalid UTF-8 leading byte (%x)", c), true);
  1550. decode_failed = true;
  1551. }
  1552. c_start = c;
  1553. if (skip == 1 && (c & 0x1e) == 0) {
  1554. print_unicode_error(vformat("Overlong encoding (%x ...)", c));
  1555. decode_error = true;
  1556. }
  1557. str_size++;
  1558. } else {
  1559. 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)) {
  1560. print_unicode_error(vformat("Overlong encoding (%x %x ...)", c_start, c));
  1561. decode_error = true;
  1562. }
  1563. if (c < 0x80 || c > 0xbf) {
  1564. print_unicode_error(vformat("Invalid UTF-8 continuation byte (%x ... %x ...)", c_start, c), true);
  1565. decode_failed = true;
  1566. skip = 0;
  1567. } else {
  1568. --skip;
  1569. }
  1570. }
  1571. cstr_size++;
  1572. ptrtmp++;
  1573. }
  1574. if (skip) {
  1575. print_unicode_error(vformat("Missing %d UTF-8 continuation byte(s)", skip), true);
  1576. decode_failed = true;
  1577. }
  1578. }
  1579. if (str_size == 0) {
  1580. clear();
  1581. return OK; // empty string
  1582. }
  1583. resize(str_size + 1);
  1584. char32_t *dst = ptrw();
  1585. dst[str_size] = 0;
  1586. int skip = 0;
  1587. uint32_t unichar = 0;
  1588. while (cstr_size) {
  1589. #if CHAR_MIN == 0
  1590. uint8_t c = *p_utf8;
  1591. #else
  1592. uint8_t c = *p_utf8 >= 0 ? *p_utf8 : uint8_t(256 + *p_utf8);
  1593. #endif
  1594. if (skip == 0) {
  1595. if (p_skip_cr && c == '\r') {
  1596. p_utf8++;
  1597. continue;
  1598. }
  1599. /* Determine the number of characters in sequence */
  1600. if ((c & 0x80) == 0) {
  1601. *(dst++) = c;
  1602. unichar = 0;
  1603. skip = 0;
  1604. } else if ((c & 0xe0) == 0xc0) {
  1605. unichar = (0xff >> 3) & c;
  1606. skip = 1;
  1607. } else if ((c & 0xf0) == 0xe0) {
  1608. unichar = (0xff >> 4) & c;
  1609. skip = 2;
  1610. } else if ((c & 0xf8) == 0xf0) {
  1611. unichar = (0xff >> 5) & c;
  1612. skip = 3;
  1613. } else if ((c & 0xfc) == 0xf8) {
  1614. unichar = (0xff >> 6) & c;
  1615. skip = 4;
  1616. } else if ((c & 0xfe) == 0xfc) {
  1617. unichar = (0xff >> 7) & c;
  1618. skip = 5;
  1619. } else {
  1620. *(dst++) = _replacement_char;
  1621. unichar = 0;
  1622. skip = 0;
  1623. }
  1624. } else {
  1625. if (c < 0x80 || c > 0xbf) {
  1626. *(dst++) = _replacement_char;
  1627. skip = 0;
  1628. } else {
  1629. unichar = (unichar << 6) | (c & 0x3f);
  1630. --skip;
  1631. if (skip == 0) {
  1632. if (unichar == 0) {
  1633. print_unicode_error("NUL character", true);
  1634. decode_failed = true;
  1635. unichar = _replacement_char;
  1636. } else if ((unichar & 0xfffff800) == 0xd800) {
  1637. print_unicode_error(vformat("Unpaired surrogate (%x)", unichar), true);
  1638. decode_failed = true;
  1639. unichar = _replacement_char;
  1640. } else if (unichar > 0x10ffff) {
  1641. print_unicode_error(vformat("Invalid unicode codepoint (%x)", unichar), true);
  1642. decode_failed = true;
  1643. unichar = _replacement_char;
  1644. }
  1645. *(dst++) = unichar;
  1646. }
  1647. }
  1648. }
  1649. cstr_size--;
  1650. p_utf8++;
  1651. }
  1652. if (skip) {
  1653. *(dst++) = 0x20;
  1654. }
  1655. if (decode_failed) {
  1656. return ERR_INVALID_DATA;
  1657. } else if (decode_error) {
  1658. return ERR_PARSE_ERROR;
  1659. } else {
  1660. return OK;
  1661. }
  1662. }
  1663. CharString String::utf8() const {
  1664. int l = length();
  1665. if (!l) {
  1666. return CharString();
  1667. }
  1668. const char32_t *d = &operator[](0);
  1669. int fl = 0;
  1670. for (int i = 0; i < l; i++) {
  1671. uint32_t c = d[i];
  1672. if (c <= 0x7f) { // 7 bits.
  1673. fl += 1;
  1674. } else if (c <= 0x7ff) { // 11 bits
  1675. fl += 2;
  1676. } else if (c <= 0xffff) { // 16 bits
  1677. fl += 3;
  1678. } else if (c <= 0x001fffff) { // 21 bits
  1679. fl += 4;
  1680. } else if (c <= 0x03ffffff) { // 26 bits
  1681. fl += 5;
  1682. print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
  1683. } else if (c <= 0x7fffffff) { // 31 bits
  1684. fl += 6;
  1685. print_unicode_error(vformat("Invalid unicode codepoint (%x)", c));
  1686. } else {
  1687. fl += 1;
  1688. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-8", c), true);
  1689. }
  1690. }
  1691. CharString utf8s;
  1692. if (fl == 0) {
  1693. return utf8s;
  1694. }
  1695. utf8s.resize(fl + 1);
  1696. uint8_t *cdst = (uint8_t *)utf8s.get_data();
  1697. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1698. for (int i = 0; i < l; i++) {
  1699. uint32_t c = d[i];
  1700. if (c <= 0x7f) { // 7 bits.
  1701. APPEND_CHAR(c);
  1702. } else if (c <= 0x7ff) { // 11 bits
  1703. APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits.
  1704. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1705. } else if (c <= 0xffff) { // 16 bits
  1706. APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits.
  1707. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits.
  1708. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1709. } else if (c <= 0x001fffff) { // 21 bits
  1710. APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits.
  1711. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits.
  1712. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1713. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1714. } else if (c <= 0x03ffffff) { // 26 bits
  1715. APPEND_CHAR(uint32_t(0xf8 | ((c >> 24) & 0x03))); // Top 2 bits.
  1716. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Upper middle 6 bits.
  1717. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // middle 6 bits.
  1718. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1719. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1720. } else if (c <= 0x7fffffff) { // 31 bits
  1721. APPEND_CHAR(uint32_t(0xfc | ((c >> 30) & 0x01))); // Top 1 bit.
  1722. APPEND_CHAR(uint32_t(0x80 | ((c >> 24) & 0x3f))); // Upper upper middle 6 bits.
  1723. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Lower upper middle 6 bits.
  1724. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper lower middle 6 bits.
  1725. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower lower middle 6 bits.
  1726. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1727. } else {
  1728. // the string is a valid UTF32, so it should never happen ...
  1729. print_unicode_error(vformat("Non scalar value (%x)", c), true);
  1730. APPEND_CHAR(uint32_t(0xe0 | ((_replacement_char >> 12) & 0x0f))); // Top 4 bits.
  1731. APPEND_CHAR(uint32_t(0x80 | ((_replacement_char >> 6) & 0x3f))); // Middle 6 bits.
  1732. APPEND_CHAR(uint32_t(0x80 | (_replacement_char & 0x3f))); // Bottom 6 bits.
  1733. }
  1734. }
  1735. #undef APPEND_CHAR
  1736. *cdst = 0; //trailing zero
  1737. return utf8s;
  1738. }
  1739. String String::utf16(const char16_t *p_utf16, int p_len) {
  1740. String ret;
  1741. ret.parse_utf16(p_utf16, p_len);
  1742. return ret;
  1743. }
  1744. Error String::parse_utf16(const char16_t *p_utf16, int p_len) {
  1745. if (!p_utf16) {
  1746. return ERR_INVALID_DATA;
  1747. }
  1748. String aux;
  1749. int cstr_size = 0;
  1750. int str_size = 0;
  1751. /* HANDLE BOM (Byte Order Mark) */
  1752. bool byteswap = false; // assume correct endianness if no BOM found
  1753. if (p_len < 0 || p_len >= 1) {
  1754. bool has_bom = false;
  1755. if (uint16_t(p_utf16[0]) == 0xfeff) { // correct BOM, read as is
  1756. has_bom = true;
  1757. byteswap = false;
  1758. } else if (uint16_t(p_utf16[0]) == 0xfffe) { // backwards BOM, swap bytes
  1759. has_bom = true;
  1760. byteswap = true;
  1761. }
  1762. if (has_bom) {
  1763. if (p_len >= 0) {
  1764. p_len -= 1;
  1765. }
  1766. p_utf16 += 1;
  1767. }
  1768. }
  1769. bool decode_error = false;
  1770. {
  1771. const char16_t *ptrtmp = p_utf16;
  1772. const char16_t *ptrtmp_limit = &p_utf16[p_len];
  1773. uint32_t c_prev = 0;
  1774. bool skip = false;
  1775. while (ptrtmp != ptrtmp_limit && *ptrtmp) {
  1776. uint32_t c = (byteswap) ? BSWAP16(*ptrtmp) : *ptrtmp;
  1777. if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
  1778. if (skip) {
  1779. print_unicode_error(vformat("Unpaired lead surrogate (%x [trail?] %x)", c_prev, c));
  1780. decode_error = true;
  1781. }
  1782. skip = true;
  1783. } else if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
  1784. if (skip) {
  1785. str_size--;
  1786. } else {
  1787. print_unicode_error(vformat("Unpaired trail surrogate (%x [lead?] %x)", c_prev, c));
  1788. decode_error = true;
  1789. }
  1790. skip = false;
  1791. } else {
  1792. skip = false;
  1793. }
  1794. c_prev = c;
  1795. str_size++;
  1796. cstr_size++;
  1797. ptrtmp++;
  1798. }
  1799. if (skip) {
  1800. print_unicode_error(vformat("Unpaired lead surrogate (%x [eol])", c_prev));
  1801. decode_error = true;
  1802. }
  1803. }
  1804. if (str_size == 0) {
  1805. clear();
  1806. return OK; // empty string
  1807. }
  1808. resize(str_size + 1);
  1809. char32_t *dst = ptrw();
  1810. dst[str_size] = 0;
  1811. bool skip = false;
  1812. uint32_t c_prev = 0;
  1813. while (cstr_size) {
  1814. uint32_t c = (byteswap) ? BSWAP16(*p_utf16) : *p_utf16;
  1815. if ((c & 0xfffffc00) == 0xd800) { // lead surrogate
  1816. if (skip) {
  1817. *(dst++) = c_prev; // unpaired, store as is
  1818. }
  1819. skip = true;
  1820. } else if ((c & 0xfffffc00) == 0xdc00) { // trail surrogate
  1821. if (skip) {
  1822. *(dst++) = (c_prev << 10UL) + c - ((0xd800 << 10UL) + 0xdc00 - 0x10000); // decode pair
  1823. } else {
  1824. *(dst++) = c; // unpaired, store as is
  1825. }
  1826. skip = false;
  1827. } else {
  1828. *(dst++) = c;
  1829. skip = false;
  1830. }
  1831. cstr_size--;
  1832. p_utf16++;
  1833. c_prev = c;
  1834. }
  1835. if (skip) {
  1836. *(dst++) = c_prev;
  1837. }
  1838. if (decode_error) {
  1839. return ERR_PARSE_ERROR;
  1840. } else {
  1841. return OK;
  1842. }
  1843. }
  1844. Char16String String::utf16() const {
  1845. int l = length();
  1846. if (!l) {
  1847. return Char16String();
  1848. }
  1849. const char32_t *d = &operator[](0);
  1850. int fl = 0;
  1851. for (int i = 0; i < l; i++) {
  1852. uint32_t c = d[i];
  1853. if (c <= 0xffff) { // 16 bits.
  1854. fl += 1;
  1855. if ((c & 0xfffff800) == 0xd800) {
  1856. print_unicode_error(vformat("Unpaired surrogate (%x)", c));
  1857. }
  1858. } else if (c <= 0x10ffff) { // 32 bits.
  1859. fl += 2;
  1860. } else {
  1861. print_unicode_error(vformat("Invalid unicode codepoint (%x), cannot represent as UTF-16", c), true);
  1862. fl += 1;
  1863. }
  1864. }
  1865. Char16String utf16s;
  1866. if (fl == 0) {
  1867. return utf16s;
  1868. }
  1869. utf16s.resize(fl + 1);
  1870. uint16_t *cdst = (uint16_t *)utf16s.get_data();
  1871. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1872. for (int i = 0; i < l; i++) {
  1873. uint32_t c = d[i];
  1874. if (c <= 0xffff) { // 16 bits.
  1875. APPEND_CHAR(c);
  1876. } else if (c <= 0x10ffff) { // 32 bits.
  1877. APPEND_CHAR(uint32_t((c >> 10) + 0xd7c0)); // lead surrogate.
  1878. APPEND_CHAR(uint32_t((c & 0x3ff) | 0xdc00)); // trail surrogate.
  1879. } else {
  1880. // the string is a valid UTF32, so it should never happen ...
  1881. APPEND_CHAR(uint32_t((_replacement_char >> 10) + 0xd7c0));
  1882. APPEND_CHAR(uint32_t((_replacement_char & 0x3ff) | 0xdc00));
  1883. }
  1884. }
  1885. #undef APPEND_CHAR
  1886. *cdst = 0; //trailing zero
  1887. return utf16s;
  1888. }
  1889. String::String(const char *p_str) {
  1890. copy_from(p_str);
  1891. }
  1892. String::String(const wchar_t *p_str) {
  1893. copy_from(p_str);
  1894. }
  1895. String::String(const char32_t *p_str) {
  1896. copy_from(p_str);
  1897. }
  1898. String::String(const char *p_str, int p_clip_to_len) {
  1899. copy_from(p_str, p_clip_to_len);
  1900. }
  1901. String::String(const wchar_t *p_str, int p_clip_to_len) {
  1902. copy_from(p_str, p_clip_to_len);
  1903. }
  1904. String::String(const char32_t *p_str, int p_clip_to_len) {
  1905. copy_from(p_str, p_clip_to_len);
  1906. }
  1907. String::String(const StrRange &p_range) {
  1908. if (!p_range.c_str) {
  1909. return;
  1910. }
  1911. copy_from(p_range.c_str, p_range.len);
  1912. }
  1913. int64_t String::hex_to_int() const {
  1914. int len = length();
  1915. if (len == 0) {
  1916. return 0;
  1917. }
  1918. const char32_t *s = ptr();
  1919. int64_t sign = s[0] == '-' ? -1 : 1;
  1920. if (sign < 0) {
  1921. s++;
  1922. }
  1923. if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'x') {
  1924. s += 2;
  1925. }
  1926. int64_t hex = 0;
  1927. while (*s) {
  1928. char32_t c = lower_case(*s);
  1929. int64_t n;
  1930. if (is_digit(c)) {
  1931. n = c - '0';
  1932. } else if (c >= 'a' && c <= 'f') {
  1933. n = (c - 'a') + 10;
  1934. } else {
  1935. ERR_FAIL_V_MSG(0, vformat(R"(Invalid hexadecimal notation character "%c" (U+%04X) in string "%s".)", *s, static_cast<int32_t>(*s), *this));
  1936. }
  1937. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  1938. bool overflow = ((hex > INT64_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT64_MAX >> 4) + 1))) || (sign == -1 && hex == (INT64_MAX >> 4) + 1 && c > '0');
  1939. 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."));
  1940. hex *= 16;
  1941. hex += n;
  1942. s++;
  1943. }
  1944. return hex * sign;
  1945. }
  1946. int64_t String::bin_to_int() const {
  1947. int len = length();
  1948. if (len == 0) {
  1949. return 0;
  1950. }
  1951. const char32_t *s = ptr();
  1952. int64_t sign = s[0] == '-' ? -1 : 1;
  1953. if (sign < 0) {
  1954. s++;
  1955. }
  1956. if (len > 2 && s[0] == '0' && lower_case(s[1]) == 'b') {
  1957. s += 2;
  1958. }
  1959. int64_t binary = 0;
  1960. while (*s) {
  1961. char32_t c = lower_case(*s);
  1962. int64_t n;
  1963. if (c == '0' || c == '1') {
  1964. n = c - '0';
  1965. } else {
  1966. return 0;
  1967. }
  1968. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  1969. bool overflow = ((binary > INT64_MAX / 2) && (sign == 1 || (sign == -1 && binary != (INT64_MAX >> 1) + 1))) || (sign == -1 && binary == (INT64_MAX >> 1) + 1 && c > '0');
  1970. 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."));
  1971. binary *= 2;
  1972. binary += n;
  1973. s++;
  1974. }
  1975. return binary * sign;
  1976. }
  1977. int64_t String::to_int() const {
  1978. if (length() == 0) {
  1979. return 0;
  1980. }
  1981. int to = (find(".") >= 0) ? find(".") : length();
  1982. int64_t integer = 0;
  1983. int64_t sign = 1;
  1984. for (int i = 0; i < to; i++) {
  1985. char32_t c = operator[](i);
  1986. if (is_digit(c)) {
  1987. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  1988. 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."));
  1989. integer *= 10;
  1990. integer += c - '0';
  1991. } else if (integer == 0 && c == '-') {
  1992. sign = -sign;
  1993. }
  1994. }
  1995. return integer * sign;
  1996. }
  1997. int64_t String::to_int(const char *p_str, int p_len) {
  1998. int to = 0;
  1999. if (p_len >= 0) {
  2000. to = p_len;
  2001. } else {
  2002. while (p_str[to] != 0 && p_str[to] != '.') {
  2003. to++;
  2004. }
  2005. }
  2006. int64_t integer = 0;
  2007. int64_t sign = 1;
  2008. for (int i = 0; i < to; i++) {
  2009. char c = p_str[i];
  2010. if (is_digit(c)) {
  2011. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  2012. 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."));
  2013. integer *= 10;
  2014. integer += c - '0';
  2015. } else if (c == '-' && integer == 0) {
  2016. sign = -sign;
  2017. } else if (c != ' ') {
  2018. break;
  2019. }
  2020. }
  2021. return integer * sign;
  2022. }
  2023. int64_t String::to_int(const wchar_t *p_str, int p_len) {
  2024. int to = 0;
  2025. if (p_len >= 0) {
  2026. to = p_len;
  2027. } else {
  2028. while (p_str[to] != 0 && p_str[to] != '.') {
  2029. to++;
  2030. }
  2031. }
  2032. int64_t integer = 0;
  2033. int64_t sign = 1;
  2034. for (int i = 0; i < to; i++) {
  2035. wchar_t c = p_str[i];
  2036. if (is_digit(c)) {
  2037. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  2038. 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."));
  2039. integer *= 10;
  2040. integer += c - '0';
  2041. } else if (c == '-' && integer == 0) {
  2042. sign = -sign;
  2043. } else if (c != ' ') {
  2044. break;
  2045. }
  2046. }
  2047. return integer * sign;
  2048. }
  2049. bool String::is_numeric() const {
  2050. if (length() == 0) {
  2051. return false;
  2052. }
  2053. int s = 0;
  2054. if (operator[](0) == '-') {
  2055. ++s;
  2056. }
  2057. bool dot = false;
  2058. for (int i = s; i < length(); i++) {
  2059. char32_t c = operator[](i);
  2060. if (c == '.') {
  2061. if (dot) {
  2062. return false;
  2063. }
  2064. dot = true;
  2065. } else if (!is_digit(c)) {
  2066. return false;
  2067. }
  2068. }
  2069. return true; // TODO: Use the parser below for this instead
  2070. }
  2071. template <class C>
  2072. static double built_in_strtod(
  2073. /* A decimal ASCII floating-point number,
  2074. * optionally preceded by white space. Must
  2075. * have form "-I.FE-X", where I is the integer
  2076. * part of the mantissa, F is the fractional
  2077. * part of the mantissa, and X is the
  2078. * exponent. Either of the signs may be "+",
  2079. * "-", or omitted. Either I or F may be
  2080. * omitted, or both. The decimal point isn't
  2081. * necessary unless F is present. The "E" may
  2082. * actually be an "e". E and X may both be
  2083. * omitted (but not just one). */
  2084. const C *string,
  2085. /* If non-nullptr, store terminating Cacter's
  2086. * address here. */
  2087. C **endPtr = nullptr) {
  2088. /* Largest possible base 10 exponent. Any
  2089. * exponent larger than this will already
  2090. * produce underflow or overflow, so there's
  2091. * no need to worry about additional digits. */
  2092. static const int maxExponent = 511;
  2093. /* Table giving binary powers of 10. Entry
  2094. * is 10^2^i. Used to convert decimal
  2095. * exponents into floating-point numbers. */
  2096. static const double powersOf10[] = {
  2097. 10.,
  2098. 100.,
  2099. 1.0e4,
  2100. 1.0e8,
  2101. 1.0e16,
  2102. 1.0e32,
  2103. 1.0e64,
  2104. 1.0e128,
  2105. 1.0e256
  2106. };
  2107. bool sign, expSign = false;
  2108. double fraction, dblExp;
  2109. const double *d;
  2110. const C *p;
  2111. int c;
  2112. /* Exponent read from "EX" field. */
  2113. int exp = 0;
  2114. /* Exponent that derives from the fractional
  2115. * part. Under normal circumstances, it is
  2116. * the negative of the number of digits in F.
  2117. * However, if I is very long, the last digits
  2118. * of I get dropped (otherwise a long I with a
  2119. * large negative exponent could cause an
  2120. * unnecessary overflow on I alone). In this
  2121. * case, fracExp is incremented one for each
  2122. * dropped digit. */
  2123. int fracExp = 0;
  2124. /* Number of digits in mantissa. */
  2125. int mantSize;
  2126. /* Number of mantissa digits BEFORE decimal point. */
  2127. int decPt;
  2128. /* Temporarily holds location of exponent in string. */
  2129. const C *pExp;
  2130. /*
  2131. * Strip off leading blanks and check for a sign.
  2132. */
  2133. p = string;
  2134. while (*p == ' ' || *p == '\t' || *p == '\n') {
  2135. p += 1;
  2136. }
  2137. if (*p == '-') {
  2138. sign = true;
  2139. p += 1;
  2140. } else {
  2141. if (*p == '+') {
  2142. p += 1;
  2143. }
  2144. sign = false;
  2145. }
  2146. /*
  2147. * Count the number of digits in the mantissa (including the decimal
  2148. * point), and also locate the decimal point.
  2149. */
  2150. decPt = -1;
  2151. for (mantSize = 0;; mantSize += 1) {
  2152. c = *p;
  2153. if (!is_digit(c)) {
  2154. if ((c != '.') || (decPt >= 0)) {
  2155. break;
  2156. }
  2157. decPt = mantSize;
  2158. }
  2159. p += 1;
  2160. }
  2161. /*
  2162. * Now suck up the digits in the mantissa. Use two integers to collect 9
  2163. * digits each (this is faster than using floating-point). If the mantissa
  2164. * has more than 18 digits, ignore the extras, since they can't affect the
  2165. * value anyway.
  2166. */
  2167. pExp = p;
  2168. p -= mantSize;
  2169. if (decPt < 0) {
  2170. decPt = mantSize;
  2171. } else {
  2172. mantSize -= 1; /* One of the digits was the point. */
  2173. }
  2174. if (mantSize > 18) {
  2175. fracExp = decPt - 18;
  2176. mantSize = 18;
  2177. } else {
  2178. fracExp = decPt - mantSize;
  2179. }
  2180. if (mantSize == 0) {
  2181. fraction = 0.0;
  2182. p = string;
  2183. goto done;
  2184. } else {
  2185. int frac1, frac2;
  2186. frac1 = 0;
  2187. for (; mantSize > 9; mantSize -= 1) {
  2188. c = *p;
  2189. p += 1;
  2190. if (c == '.') {
  2191. c = *p;
  2192. p += 1;
  2193. }
  2194. frac1 = 10 * frac1 + (c - '0');
  2195. }
  2196. frac2 = 0;
  2197. for (; mantSize > 0; mantSize -= 1) {
  2198. c = *p;
  2199. p += 1;
  2200. if (c == '.') {
  2201. c = *p;
  2202. p += 1;
  2203. }
  2204. frac2 = 10 * frac2 + (c - '0');
  2205. }
  2206. fraction = (1.0e9 * frac1) + frac2;
  2207. }
  2208. /*
  2209. * Skim off the exponent.
  2210. */
  2211. p = pExp;
  2212. if ((*p == 'E') || (*p == 'e')) {
  2213. p += 1;
  2214. if (*p == '-') {
  2215. expSign = true;
  2216. p += 1;
  2217. } else {
  2218. if (*p == '+') {
  2219. p += 1;
  2220. }
  2221. expSign = false;
  2222. }
  2223. if (!is_digit(char32_t(*p))) {
  2224. p = pExp;
  2225. goto done;
  2226. }
  2227. while (is_digit(char32_t(*p))) {
  2228. exp = exp * 10 + (*p - '0');
  2229. p += 1;
  2230. }
  2231. }
  2232. if (expSign) {
  2233. exp = fracExp - exp;
  2234. } else {
  2235. exp = fracExp + exp;
  2236. }
  2237. /*
  2238. * Generate a floating-point number that represents the exponent. Do this
  2239. * by processing the exponent one bit at a time to combine many powers of
  2240. * 2 of 10. Then combine the exponent with the fraction.
  2241. */
  2242. if (exp < 0) {
  2243. expSign = true;
  2244. exp = -exp;
  2245. } else {
  2246. expSign = false;
  2247. }
  2248. if (exp > maxExponent) {
  2249. exp = maxExponent;
  2250. WARN_PRINT("Exponent too high");
  2251. }
  2252. dblExp = 1.0;
  2253. for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
  2254. if (exp & 01) {
  2255. dblExp *= *d;
  2256. }
  2257. }
  2258. if (expSign) {
  2259. fraction /= dblExp;
  2260. } else {
  2261. fraction *= dblExp;
  2262. }
  2263. done:
  2264. if (endPtr != nullptr) {
  2265. *endPtr = (C *)p;
  2266. }
  2267. if (sign) {
  2268. return -fraction;
  2269. }
  2270. return fraction;
  2271. }
  2272. #define READING_SIGN 0
  2273. #define READING_INT 1
  2274. #define READING_DEC 2
  2275. #define READING_EXP 3
  2276. #define READING_DONE 4
  2277. double String::to_float(const char *p_str) {
  2278. return built_in_strtod<char>(p_str);
  2279. }
  2280. double String::to_float(const char32_t *p_str, const char32_t **r_end) {
  2281. return built_in_strtod<char32_t>(p_str, (char32_t **)r_end);
  2282. }
  2283. double String::to_float(const wchar_t *p_str, const wchar_t **r_end) {
  2284. return built_in_strtod<wchar_t>(p_str, (wchar_t **)r_end);
  2285. }
  2286. uint32_t String::num_characters(int64_t p_int) {
  2287. int r = 1;
  2288. if (p_int < 0) {
  2289. r += 1;
  2290. if (p_int == INT64_MIN) {
  2291. p_int = INT64_MAX;
  2292. } else {
  2293. p_int = -p_int;
  2294. }
  2295. }
  2296. while (p_int >= 10) {
  2297. p_int /= 10;
  2298. r++;
  2299. }
  2300. return r;
  2301. }
  2302. int64_t String::to_int(const char32_t *p_str, int p_len, bool p_clamp) {
  2303. if (p_len == 0 || !p_str[0]) {
  2304. return 0;
  2305. }
  2306. ///@todo make more exact so saving and loading does not lose precision
  2307. int64_t integer = 0;
  2308. int64_t sign = 1;
  2309. int reading = READING_SIGN;
  2310. const char32_t *str = p_str;
  2311. const char32_t *limit = &p_str[p_len];
  2312. while (*str && reading != READING_DONE && str != limit) {
  2313. char32_t c = *(str++);
  2314. switch (reading) {
  2315. case READING_SIGN: {
  2316. if (is_digit(c)) {
  2317. reading = READING_INT;
  2318. // let it fallthrough
  2319. } else if (c == '-') {
  2320. sign = -1;
  2321. reading = READING_INT;
  2322. break;
  2323. } else if (c == '+') {
  2324. sign = 1;
  2325. reading = READING_INT;
  2326. break;
  2327. } else {
  2328. break;
  2329. }
  2330. [[fallthrough]];
  2331. }
  2332. case READING_INT: {
  2333. if (is_digit(c)) {
  2334. if (integer > INT64_MAX / 10) {
  2335. String number("");
  2336. str = p_str;
  2337. while (*str && str != limit) {
  2338. number += *(str++);
  2339. }
  2340. if (p_clamp) {
  2341. if (sign == 1) {
  2342. return INT64_MAX;
  2343. } else {
  2344. return INT64_MIN;
  2345. }
  2346. } else {
  2347. 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."));
  2348. }
  2349. }
  2350. integer *= 10;
  2351. integer += c - '0';
  2352. } else {
  2353. reading = READING_DONE;
  2354. }
  2355. } break;
  2356. }
  2357. }
  2358. return sign * integer;
  2359. }
  2360. double String::to_float() const {
  2361. if (is_empty()) {
  2362. return 0;
  2363. }
  2364. return built_in_strtod<char32_t>(get_data());
  2365. }
  2366. uint32_t String::hash(const char *p_cstr) {
  2367. // static_cast: avoid negative values on platforms where char is signed.
  2368. uint32_t hashv = 5381;
  2369. uint32_t c = static_cast<uint8_t>(*p_cstr++);
  2370. while (c) {
  2371. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2372. c = static_cast<uint8_t>(*p_cstr++);
  2373. }
  2374. return hashv;
  2375. }
  2376. uint32_t String::hash(const char *p_cstr, int p_len) {
  2377. uint32_t hashv = 5381;
  2378. for (int i = 0; i < p_len; i++) {
  2379. // static_cast: avoid negative values on platforms where char is signed.
  2380. hashv = ((hashv << 5) + hashv) + static_cast<uint8_t>(p_cstr[i]); /* hash * 33 + c */
  2381. }
  2382. return hashv;
  2383. }
  2384. uint32_t String::hash(const wchar_t *p_cstr, int p_len) {
  2385. // Avoid negative values on platforms where wchar_t is signed. Account for different sizes.
  2386. using wide_unsigned = std::conditional<sizeof(wchar_t) == 2, uint16_t, uint32_t>::type;
  2387. uint32_t hashv = 5381;
  2388. for (int i = 0; i < p_len; i++) {
  2389. hashv = ((hashv << 5) + hashv) + static_cast<wide_unsigned>(p_cstr[i]); /* hash * 33 + c */
  2390. }
  2391. return hashv;
  2392. }
  2393. uint32_t String::hash(const wchar_t *p_cstr) {
  2394. // Avoid negative values on platforms where wchar_t is signed. Account for different sizes.
  2395. using wide_unsigned = std::conditional<sizeof(wchar_t) == 2, uint16_t, uint32_t>::type;
  2396. uint32_t hashv = 5381;
  2397. uint32_t c = static_cast<wide_unsigned>(*p_cstr++);
  2398. while (c) {
  2399. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2400. c = static_cast<wide_unsigned>(*p_cstr++);
  2401. }
  2402. return hashv;
  2403. }
  2404. uint32_t String::hash(const char32_t *p_cstr, int p_len) {
  2405. uint32_t hashv = 5381;
  2406. for (int i = 0; i < p_len; i++) {
  2407. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  2408. }
  2409. return hashv;
  2410. }
  2411. uint32_t String::hash(const char32_t *p_cstr) {
  2412. uint32_t hashv = 5381;
  2413. uint32_t c = *p_cstr++;
  2414. while (c) {
  2415. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2416. c = *p_cstr++;
  2417. }
  2418. return hashv;
  2419. }
  2420. uint32_t String::hash() const {
  2421. /* simple djb2 hashing */
  2422. const char32_t *chr = get_data();
  2423. uint32_t hashv = 5381;
  2424. uint32_t c = *chr++;
  2425. while (c) {
  2426. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2427. c = *chr++;
  2428. }
  2429. return hashv;
  2430. }
  2431. uint64_t String::hash64() const {
  2432. /* simple djb2 hashing */
  2433. const char32_t *chr = get_data();
  2434. uint64_t hashv = 5381;
  2435. uint64_t c = *chr++;
  2436. while (c) {
  2437. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  2438. c = *chr++;
  2439. }
  2440. return hashv;
  2441. }
  2442. String String::md5_text() const {
  2443. CharString cs = utf8();
  2444. unsigned char hash[16];
  2445. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  2446. return String::hex_encode_buffer(hash, 16);
  2447. }
  2448. String String::sha1_text() const {
  2449. CharString cs = utf8();
  2450. unsigned char hash[20];
  2451. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  2452. return String::hex_encode_buffer(hash, 20);
  2453. }
  2454. String String::sha256_text() const {
  2455. CharString cs = utf8();
  2456. unsigned char hash[32];
  2457. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  2458. return String::hex_encode_buffer(hash, 32);
  2459. }
  2460. Vector<uint8_t> String::md5_buffer() const {
  2461. CharString cs = utf8();
  2462. unsigned char hash[16];
  2463. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  2464. Vector<uint8_t> ret;
  2465. ret.resize(16);
  2466. for (int i = 0; i < 16; i++) {
  2467. ret.write[i] = hash[i];
  2468. }
  2469. return ret;
  2470. }
  2471. Vector<uint8_t> String::sha1_buffer() const {
  2472. CharString cs = utf8();
  2473. unsigned char hash[20];
  2474. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  2475. Vector<uint8_t> ret;
  2476. ret.resize(20);
  2477. for (int i = 0; i < 20; i++) {
  2478. ret.write[i] = hash[i];
  2479. }
  2480. return ret;
  2481. }
  2482. Vector<uint8_t> String::sha256_buffer() const {
  2483. CharString cs = utf8();
  2484. unsigned char hash[32];
  2485. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  2486. Vector<uint8_t> ret;
  2487. ret.resize(32);
  2488. for (int i = 0; i < 32; i++) {
  2489. ret.write[i] = hash[i];
  2490. }
  2491. return ret;
  2492. }
  2493. String String::insert(int p_at_pos, const String &p_string) const {
  2494. if (p_at_pos < 0) {
  2495. return *this;
  2496. }
  2497. if (p_at_pos > length()) {
  2498. p_at_pos = length();
  2499. }
  2500. String pre;
  2501. if (p_at_pos > 0) {
  2502. pre = substr(0, p_at_pos);
  2503. }
  2504. String post;
  2505. if (p_at_pos < length()) {
  2506. post = substr(p_at_pos, length() - p_at_pos);
  2507. }
  2508. return pre + p_string + post;
  2509. }
  2510. String String::erase(int p_pos, int p_chars) const {
  2511. 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));
  2512. 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));
  2513. return left(p_pos) + substr(p_pos + p_chars);
  2514. }
  2515. String String::substr(int p_from, int p_chars) const {
  2516. if (p_chars == -1) {
  2517. p_chars = length() - p_from;
  2518. }
  2519. if (is_empty() || p_from < 0 || p_from >= length() || p_chars <= 0) {
  2520. return "";
  2521. }
  2522. if ((p_from + p_chars) > length()) {
  2523. p_chars = length() - p_from;
  2524. }
  2525. if (p_from == 0 && p_chars >= length()) {
  2526. return String(*this);
  2527. }
  2528. String s;
  2529. s.copy_from_unchecked(&get_data()[p_from], p_chars);
  2530. return s;
  2531. }
  2532. int String::find(const String &p_str, int p_from) const {
  2533. if (p_from < 0) {
  2534. return -1;
  2535. }
  2536. const int src_len = p_str.length();
  2537. const int len = length();
  2538. if (src_len == 0 || len == 0) {
  2539. return -1; // won't find anything!
  2540. }
  2541. const char32_t *src = get_data();
  2542. const char32_t *str = p_str.get_data();
  2543. for (int i = p_from; i <= (len - src_len); i++) {
  2544. bool found = true;
  2545. for (int j = 0; j < src_len; j++) {
  2546. int read_pos = i + j;
  2547. if (read_pos >= len) {
  2548. ERR_PRINT("read_pos>=len");
  2549. return -1;
  2550. }
  2551. if (src[read_pos] != str[j]) {
  2552. found = false;
  2553. break;
  2554. }
  2555. }
  2556. if (found) {
  2557. return i;
  2558. }
  2559. }
  2560. return -1;
  2561. }
  2562. int String::find(const char *p_str, int p_from) const {
  2563. if (p_from < 0) {
  2564. return -1;
  2565. }
  2566. const int len = length();
  2567. if (len == 0) {
  2568. return -1; // won't find anything!
  2569. }
  2570. const char32_t *src = get_data();
  2571. int src_len = 0;
  2572. while (p_str[src_len] != '\0') {
  2573. src_len++;
  2574. }
  2575. if (src_len == 1) {
  2576. const char32_t needle = p_str[0];
  2577. for (int i = p_from; i < len; i++) {
  2578. if (src[i] == needle) {
  2579. return i;
  2580. }
  2581. }
  2582. } else {
  2583. for (int i = p_from; i <= (len - src_len); i++) {
  2584. bool found = true;
  2585. for (int j = 0; j < src_len; j++) {
  2586. int read_pos = i + j;
  2587. if (read_pos >= len) {
  2588. ERR_PRINT("read_pos>=len");
  2589. return -1;
  2590. }
  2591. if (src[read_pos] != (char32_t)p_str[j]) {
  2592. found = false;
  2593. break;
  2594. }
  2595. }
  2596. if (found) {
  2597. return i;
  2598. }
  2599. }
  2600. }
  2601. return -1;
  2602. }
  2603. int String::find_char(const char32_t &p_char, int p_from) const {
  2604. return _cowdata.find(p_char, p_from);
  2605. }
  2606. int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
  2607. if (p_from < 0) {
  2608. return -1;
  2609. }
  2610. if (p_keys.size() == 0) {
  2611. return -1;
  2612. }
  2613. //int src_len=p_str.length();
  2614. const String *keys = &p_keys[0];
  2615. int key_count = p_keys.size();
  2616. int len = length();
  2617. if (len == 0) {
  2618. return -1; // won't find anything!
  2619. }
  2620. const char32_t *src = get_data();
  2621. for (int i = p_from; i < len; i++) {
  2622. bool found = true;
  2623. for (int k = 0; k < key_count; k++) {
  2624. found = true;
  2625. if (r_key) {
  2626. *r_key = k;
  2627. }
  2628. const char32_t *cmp = keys[k].get_data();
  2629. int l = keys[k].length();
  2630. for (int j = 0; j < l; j++) {
  2631. int read_pos = i + j;
  2632. if (read_pos >= len) {
  2633. found = false;
  2634. break;
  2635. }
  2636. if (src[read_pos] != cmp[j]) {
  2637. found = false;
  2638. break;
  2639. }
  2640. }
  2641. if (found) {
  2642. break;
  2643. }
  2644. }
  2645. if (found) {
  2646. return i;
  2647. }
  2648. }
  2649. return -1;
  2650. }
  2651. int String::findn(const String &p_str, int p_from) const {
  2652. if (p_from < 0) {
  2653. return -1;
  2654. }
  2655. int src_len = p_str.length();
  2656. if (src_len == 0 || length() == 0) {
  2657. return -1; // won't find anything!
  2658. }
  2659. const char32_t *srcd = get_data();
  2660. for (int i = p_from; i <= (length() - src_len); i++) {
  2661. bool found = true;
  2662. for (int j = 0; j < src_len; j++) {
  2663. int read_pos = i + j;
  2664. if (read_pos >= length()) {
  2665. ERR_PRINT("read_pos>=length()");
  2666. return -1;
  2667. }
  2668. char32_t src = _find_lower(srcd[read_pos]);
  2669. char32_t dst = _find_lower(p_str[j]);
  2670. if (src != dst) {
  2671. found = false;
  2672. break;
  2673. }
  2674. }
  2675. if (found) {
  2676. return i;
  2677. }
  2678. }
  2679. return -1;
  2680. }
  2681. int String::rfind(const String &p_str, int p_from) const {
  2682. // establish a limit
  2683. int limit = length() - p_str.length();
  2684. if (limit < 0) {
  2685. return -1;
  2686. }
  2687. // establish a starting point
  2688. if (p_from < 0) {
  2689. p_from = limit;
  2690. } else if (p_from > limit) {
  2691. p_from = limit;
  2692. }
  2693. int src_len = p_str.length();
  2694. int len = length();
  2695. if (src_len == 0 || len == 0) {
  2696. return -1; // won't find anything!
  2697. }
  2698. const char32_t *src = get_data();
  2699. for (int i = p_from; i >= 0; i--) {
  2700. bool found = true;
  2701. for (int j = 0; j < src_len; j++) {
  2702. int read_pos = i + j;
  2703. if (read_pos >= len) {
  2704. ERR_PRINT("read_pos>=len");
  2705. return -1;
  2706. }
  2707. if (src[read_pos] != p_str[j]) {
  2708. found = false;
  2709. break;
  2710. }
  2711. }
  2712. if (found) {
  2713. return i;
  2714. }
  2715. }
  2716. return -1;
  2717. }
  2718. int String::rfindn(const String &p_str, int p_from) const {
  2719. // establish a limit
  2720. int limit = length() - p_str.length();
  2721. if (limit < 0) {
  2722. return -1;
  2723. }
  2724. // establish a starting point
  2725. if (p_from < 0) {
  2726. p_from = limit;
  2727. } else if (p_from > limit) {
  2728. p_from = limit;
  2729. }
  2730. int src_len = p_str.length();
  2731. int len = length();
  2732. if (src_len == 0 || len == 0) {
  2733. return -1; // won't find anything!
  2734. }
  2735. const char32_t *src = get_data();
  2736. for (int i = p_from; i >= 0; i--) {
  2737. bool found = true;
  2738. for (int j = 0; j < src_len; j++) {
  2739. int read_pos = i + j;
  2740. if (read_pos >= len) {
  2741. ERR_PRINT("read_pos>=len");
  2742. return -1;
  2743. }
  2744. char32_t srcc = _find_lower(src[read_pos]);
  2745. char32_t dstc = _find_lower(p_str[j]);
  2746. if (srcc != dstc) {
  2747. found = false;
  2748. break;
  2749. }
  2750. }
  2751. if (found) {
  2752. return i;
  2753. }
  2754. }
  2755. return -1;
  2756. }
  2757. bool String::ends_with(const String &p_string) const {
  2758. int l = p_string.length();
  2759. if (l > length()) {
  2760. return false;
  2761. }
  2762. if (l == 0) {
  2763. return true;
  2764. }
  2765. const char32_t *p = &p_string[0];
  2766. const char32_t *s = &operator[](length() - l);
  2767. for (int i = 0; i < l; i++) {
  2768. if (p[i] != s[i]) {
  2769. return false;
  2770. }
  2771. }
  2772. return true;
  2773. }
  2774. bool String::begins_with(const String &p_string) const {
  2775. int l = p_string.length();
  2776. if (l > length()) {
  2777. return false;
  2778. }
  2779. if (l == 0) {
  2780. return true;
  2781. }
  2782. const char32_t *p = &p_string[0];
  2783. const char32_t *s = &operator[](0);
  2784. for (int i = 0; i < l; i++) {
  2785. if (p[i] != s[i]) {
  2786. return false;
  2787. }
  2788. }
  2789. return true;
  2790. }
  2791. bool String::begins_with(const char *p_string) const {
  2792. int l = length();
  2793. if (l == 0 || !p_string) {
  2794. return false;
  2795. }
  2796. const char32_t *str = &operator[](0);
  2797. int i = 0;
  2798. while (*p_string && i < l) {
  2799. if ((char32_t)*p_string != str[i]) {
  2800. return false;
  2801. }
  2802. i++;
  2803. p_string++;
  2804. }
  2805. return *p_string == 0;
  2806. }
  2807. bool String::is_enclosed_in(const String &p_string) const {
  2808. return begins_with(p_string) && ends_with(p_string);
  2809. }
  2810. bool String::is_subsequence_of(const String &p_string) const {
  2811. return _base_is_subsequence_of(p_string, false);
  2812. }
  2813. bool String::is_subsequence_ofn(const String &p_string) const {
  2814. return _base_is_subsequence_of(p_string, true);
  2815. }
  2816. bool String::is_quoted() const {
  2817. return is_enclosed_in("\"") || is_enclosed_in("'");
  2818. }
  2819. int String::_count(const String &p_string, int p_from, int p_to, bool p_case_insensitive) const {
  2820. if (p_string.is_empty()) {
  2821. return 0;
  2822. }
  2823. int len = length();
  2824. int slen = p_string.length();
  2825. if (len < slen) {
  2826. return 0;
  2827. }
  2828. String str;
  2829. if (p_from >= 0 && p_to >= 0) {
  2830. if (p_to == 0) {
  2831. p_to = len;
  2832. } else if (p_from >= p_to) {
  2833. return 0;
  2834. }
  2835. if (p_from == 0 && p_to == len) {
  2836. str = String();
  2837. str.copy_from_unchecked(&get_data()[0], len);
  2838. } else {
  2839. str = substr(p_from, p_to - p_from);
  2840. }
  2841. } else {
  2842. return 0;
  2843. }
  2844. int c = 0;
  2845. int idx = -1;
  2846. do {
  2847. idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
  2848. if (idx != -1) {
  2849. str = str.substr(idx + slen, str.length() - slen);
  2850. ++c;
  2851. }
  2852. } while (idx != -1);
  2853. return c;
  2854. }
  2855. int String::count(const String &p_string, int p_from, int p_to) const {
  2856. return _count(p_string, p_from, p_to, false);
  2857. }
  2858. int String::countn(const String &p_string, int p_from, int p_to) const {
  2859. return _count(p_string, p_from, p_to, true);
  2860. }
  2861. bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const {
  2862. int len = length();
  2863. if (len == 0) {
  2864. // Technically an empty string is subsequence of any string
  2865. return true;
  2866. }
  2867. if (len > p_string.length()) {
  2868. return false;
  2869. }
  2870. const char32_t *src = &operator[](0);
  2871. const char32_t *tgt = &p_string[0];
  2872. for (; *src && *tgt; tgt++) {
  2873. bool match = false;
  2874. if (case_insensitive) {
  2875. char32_t srcc = _find_lower(*src);
  2876. char32_t tgtc = _find_lower(*tgt);
  2877. match = srcc == tgtc;
  2878. } else {
  2879. match = *src == *tgt;
  2880. }
  2881. if (match) {
  2882. src++;
  2883. if (!*src) {
  2884. return true;
  2885. }
  2886. }
  2887. }
  2888. return false;
  2889. }
  2890. Vector<String> String::bigrams() const {
  2891. int n_pairs = length() - 1;
  2892. Vector<String> b;
  2893. if (n_pairs <= 0) {
  2894. return b;
  2895. }
  2896. b.resize(n_pairs);
  2897. for (int i = 0; i < n_pairs; i++) {
  2898. b.write[i] = substr(i, 2);
  2899. }
  2900. return b;
  2901. }
  2902. // Similarity according to Sorensen-Dice coefficient
  2903. float String::similarity(const String &p_string) const {
  2904. if (operator==(p_string)) {
  2905. // Equal strings are totally similar
  2906. return 1.0f;
  2907. }
  2908. if (length() < 2 || p_string.length() < 2) {
  2909. // No way to calculate similarity without a single bigram
  2910. return 0.0f;
  2911. }
  2912. Vector<String> src_bigrams = bigrams();
  2913. Vector<String> tgt_bigrams = p_string.bigrams();
  2914. int src_size = src_bigrams.size();
  2915. int tgt_size = tgt_bigrams.size();
  2916. int sum = src_size + tgt_size;
  2917. int inter = 0;
  2918. for (int i = 0; i < src_size; i++) {
  2919. for (int j = 0; j < tgt_size; j++) {
  2920. if (src_bigrams[i] == tgt_bigrams[j]) {
  2921. inter++;
  2922. break;
  2923. }
  2924. }
  2925. }
  2926. return (2.0f * inter) / sum;
  2927. }
  2928. static bool _wildcard_match(const char32_t *p_pattern, const char32_t *p_string, bool p_case_sensitive) {
  2929. switch (*p_pattern) {
  2930. case '\0':
  2931. return !*p_string;
  2932. case '*':
  2933. return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive));
  2934. case '?':
  2935. return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
  2936. default:
  2937. 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);
  2938. }
  2939. }
  2940. bool String::match(const String &p_wildcard) const {
  2941. if (!p_wildcard.length() || !length()) {
  2942. return false;
  2943. }
  2944. return _wildcard_match(p_wildcard.get_data(), get_data(), true);
  2945. }
  2946. bool String::matchn(const String &p_wildcard) const {
  2947. if (!p_wildcard.length() || !length()) {
  2948. return false;
  2949. }
  2950. return _wildcard_match(p_wildcard.get_data(), get_data(), false);
  2951. }
  2952. String String::format(const Variant &values, String placeholder) const {
  2953. String new_string = String(this->ptr());
  2954. if (values.get_type() == Variant::ARRAY) {
  2955. Array values_arr = values;
  2956. for (int i = 0; i < values_arr.size(); i++) {
  2957. String i_as_str = String::num_int64(i);
  2958. if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
  2959. Array value_arr = values_arr[i];
  2960. if (value_arr.size() == 2) {
  2961. Variant v_key = value_arr[0];
  2962. String key = v_key;
  2963. Variant v_val = value_arr[1];
  2964. String val = v_val;
  2965. new_string = new_string.replace(placeholder.replace("_", key), val);
  2966. } else {
  2967. ERR_PRINT(String("STRING.format Inner Array size != 2 ").ascii().get_data());
  2968. }
  2969. } else { //Array structure ["RobotGuy","Logis","rookie"]
  2970. Variant v_val = values_arr[i];
  2971. String val = v_val;
  2972. if (placeholder.find("_") > -1) {
  2973. new_string = new_string.replace(placeholder.replace("_", i_as_str), val);
  2974. } else {
  2975. new_string = new_string.replace_first(placeholder, val);
  2976. }
  2977. }
  2978. }
  2979. } else if (values.get_type() == Variant::DICTIONARY) {
  2980. Dictionary d = values;
  2981. List<Variant> keys;
  2982. d.get_key_list(&keys);
  2983. for (const Variant &key : keys) {
  2984. new_string = new_string.replace(placeholder.replace("_", key), d[key]);
  2985. }
  2986. } else {
  2987. ERR_PRINT(String("Invalid type: use Array or Dictionary.").ascii().get_data());
  2988. }
  2989. return new_string;
  2990. }
  2991. String String::replace(const String &p_key, const String &p_with) const {
  2992. String new_string;
  2993. int search_from = 0;
  2994. int result = 0;
  2995. while ((result = find(p_key, search_from)) >= 0) {
  2996. new_string += substr(search_from, result - search_from);
  2997. new_string += p_with;
  2998. search_from = result + p_key.length();
  2999. }
  3000. if (search_from == 0) {
  3001. return *this;
  3002. }
  3003. new_string += substr(search_from, length() - search_from);
  3004. return new_string;
  3005. }
  3006. String String::replace(const char *p_key, const char *p_with) const {
  3007. String new_string;
  3008. int search_from = 0;
  3009. int result = 0;
  3010. while ((result = find(p_key, search_from)) >= 0) {
  3011. new_string += substr(search_from, result - search_from);
  3012. new_string += p_with;
  3013. int k = 0;
  3014. while (p_key[k] != '\0') {
  3015. k++;
  3016. }
  3017. search_from = result + k;
  3018. }
  3019. if (search_from == 0) {
  3020. return *this;
  3021. }
  3022. new_string += substr(search_from, length() - search_from);
  3023. return new_string;
  3024. }
  3025. String String::replace_first(const String &p_key, const String &p_with) const {
  3026. int pos = find(p_key);
  3027. if (pos >= 0) {
  3028. return substr(0, pos) + p_with + substr(pos + p_key.length(), length());
  3029. }
  3030. return *this;
  3031. }
  3032. String String::replacen(const String &p_key, const String &p_with) const {
  3033. String new_string;
  3034. int search_from = 0;
  3035. int result = 0;
  3036. while ((result = findn(p_key, search_from)) >= 0) {
  3037. new_string += substr(search_from, result - search_from);
  3038. new_string += p_with;
  3039. search_from = result + p_key.length();
  3040. }
  3041. if (search_from == 0) {
  3042. return *this;
  3043. }
  3044. new_string += substr(search_from, length() - search_from);
  3045. return new_string;
  3046. }
  3047. String String::repeat(int p_count) const {
  3048. ERR_FAIL_COND_V_MSG(p_count < 0, "", "Parameter count should be a positive number.");
  3049. if (p_count == 0) {
  3050. return "";
  3051. }
  3052. if (p_count == 1) {
  3053. return *this;
  3054. }
  3055. int len = length();
  3056. String new_string = *this;
  3057. new_string.resize(p_count * len + 1);
  3058. char32_t *dst = new_string.ptrw();
  3059. int offset = 1;
  3060. int stride = 1;
  3061. while (offset < p_count) {
  3062. memcpy(dst + offset * len, dst, stride * len * sizeof(char32_t));
  3063. offset += stride;
  3064. stride = MIN(stride * 2, p_count - offset);
  3065. }
  3066. dst[p_count * len] = _null;
  3067. return new_string;
  3068. }
  3069. String String::reverse() const {
  3070. int len = length();
  3071. if (len <= 1) {
  3072. return *this;
  3073. }
  3074. String new_string;
  3075. new_string.resize(len + 1);
  3076. const char32_t *src = ptr();
  3077. char32_t *dst = new_string.ptrw();
  3078. for (int i = 0; i < len; i++) {
  3079. dst[i] = src[len - i - 1];
  3080. }
  3081. dst[len] = _null;
  3082. return new_string;
  3083. }
  3084. String String::left(int p_len) const {
  3085. if (p_len < 0) {
  3086. p_len = length() + p_len;
  3087. }
  3088. if (p_len <= 0) {
  3089. return "";
  3090. }
  3091. if (p_len >= length()) {
  3092. return *this;
  3093. }
  3094. String s;
  3095. s.copy_from_unchecked(&get_data()[0], p_len);
  3096. return s;
  3097. }
  3098. String String::right(int p_len) const {
  3099. if (p_len < 0) {
  3100. p_len = length() + p_len;
  3101. }
  3102. if (p_len <= 0) {
  3103. return "";
  3104. }
  3105. if (p_len >= length()) {
  3106. return *this;
  3107. }
  3108. String s;
  3109. s.copy_from_unchecked(&get_data()[length() - p_len], p_len);
  3110. return s;
  3111. }
  3112. char32_t String::unicode_at(int p_idx) const {
  3113. ERR_FAIL_INDEX_V(p_idx, length(), 0);
  3114. return operator[](p_idx);
  3115. }
  3116. String String::indent(const String &p_prefix) const {
  3117. String new_string;
  3118. int line_start = 0;
  3119. for (int i = 0; i < length(); i++) {
  3120. const char32_t c = operator[](i);
  3121. if (c == '\n') {
  3122. if (i == line_start) {
  3123. new_string += c; // Leave empty lines empty.
  3124. } else {
  3125. new_string += p_prefix + substr(line_start, i - line_start + 1);
  3126. }
  3127. line_start = i + 1;
  3128. }
  3129. }
  3130. if (line_start != length()) {
  3131. new_string += p_prefix + substr(line_start);
  3132. }
  3133. return new_string;
  3134. }
  3135. String String::dedent() const {
  3136. String new_string;
  3137. String indent;
  3138. bool has_indent = false;
  3139. bool has_text = false;
  3140. int line_start = 0;
  3141. int indent_stop = -1;
  3142. for (int i = 0; i < length(); i++) {
  3143. char32_t c = operator[](i);
  3144. if (c == '\n') {
  3145. if (has_text) {
  3146. new_string += substr(indent_stop, i - indent_stop);
  3147. }
  3148. new_string += "\n";
  3149. has_text = false;
  3150. line_start = i + 1;
  3151. indent_stop = -1;
  3152. } else if (!has_text) {
  3153. if (c > 32) {
  3154. has_text = true;
  3155. if (!has_indent) {
  3156. has_indent = true;
  3157. indent = substr(line_start, i - line_start);
  3158. indent_stop = i;
  3159. }
  3160. }
  3161. if (has_indent && indent_stop < 0) {
  3162. int j = i - line_start;
  3163. if (j >= indent.length() || c != indent[j]) {
  3164. indent_stop = i;
  3165. }
  3166. }
  3167. }
  3168. }
  3169. if (has_text) {
  3170. new_string += substr(indent_stop, length() - indent_stop);
  3171. }
  3172. return new_string;
  3173. }
  3174. String String::strip_edges(bool left, bool right) const {
  3175. int len = length();
  3176. int beg = 0, end = len;
  3177. if (left) {
  3178. for (int i = 0; i < len; i++) {
  3179. if (operator[](i) <= 32) {
  3180. beg++;
  3181. } else {
  3182. break;
  3183. }
  3184. }
  3185. }
  3186. if (right) {
  3187. for (int i = len - 1; i >= 0; i--) {
  3188. if (operator[](i) <= 32) {
  3189. end--;
  3190. } else {
  3191. break;
  3192. }
  3193. }
  3194. }
  3195. if (beg == 0 && end == len) {
  3196. return *this;
  3197. }
  3198. return substr(beg, end - beg);
  3199. }
  3200. String String::strip_escapes() const {
  3201. String new_string;
  3202. for (int i = 0; i < length(); i++) {
  3203. // Escape characters on first page of the ASCII table, before 32 (Space).
  3204. if (operator[](i) < 32) {
  3205. continue;
  3206. }
  3207. new_string += operator[](i);
  3208. }
  3209. return new_string;
  3210. }
  3211. String String::lstrip(const String &p_chars) const {
  3212. int len = length();
  3213. int beg;
  3214. for (beg = 0; beg < len; beg++) {
  3215. if (p_chars.find_char(get(beg)) == -1) {
  3216. break;
  3217. }
  3218. }
  3219. if (beg == 0) {
  3220. return *this;
  3221. }
  3222. return substr(beg, len - beg);
  3223. }
  3224. String String::rstrip(const String &p_chars) const {
  3225. int len = length();
  3226. int end;
  3227. for (end = len - 1; end >= 0; end--) {
  3228. if (p_chars.find_char(get(end)) == -1) {
  3229. break;
  3230. }
  3231. }
  3232. if (end == len - 1) {
  3233. return *this;
  3234. }
  3235. return substr(0, end + 1);
  3236. }
  3237. bool String::is_network_share_path() const {
  3238. return begins_with("//") || begins_with("\\\\");
  3239. }
  3240. String String::simplify_path() const {
  3241. String s = *this;
  3242. String drive;
  3243. // Check if we have a special path (like res://) or a protocol identifier.
  3244. int p = s.find("://");
  3245. bool found = false;
  3246. if (p > 0) {
  3247. bool only_chars = true;
  3248. for (int i = 0; i < p; i++) {
  3249. if (!is_ascii_alphanumeric_char(s[i])) {
  3250. only_chars = false;
  3251. break;
  3252. }
  3253. }
  3254. if (only_chars) {
  3255. found = true;
  3256. drive = s.substr(0, p + 3);
  3257. s = s.substr(p + 3);
  3258. }
  3259. }
  3260. if (!found) {
  3261. if (is_network_share_path()) {
  3262. // Network path, beginning with // or \\.
  3263. drive = s.substr(0, 2);
  3264. s = s.substr(2);
  3265. } else if (s.begins_with("/") || s.begins_with("\\")) {
  3266. // Absolute path.
  3267. drive = s.substr(0, 1);
  3268. s = s.substr(1);
  3269. } else {
  3270. // Windows-style drive path, like C:/ or C:\.
  3271. p = s.find(":/");
  3272. if (p == -1) {
  3273. p = s.find(":\\");
  3274. }
  3275. if (p != -1 && p < s.find("/")) {
  3276. drive = s.substr(0, p + 2);
  3277. s = s.substr(p + 2);
  3278. }
  3279. }
  3280. }
  3281. s = s.replace("\\", "/");
  3282. while (true) { // in case of using 2 or more slash
  3283. String compare = s.replace("//", "/");
  3284. if (s == compare) {
  3285. break;
  3286. } else {
  3287. s = compare;
  3288. }
  3289. }
  3290. Vector<String> dirs = s.split("/", false);
  3291. for (int i = 0; i < dirs.size(); i++) {
  3292. String d = dirs[i];
  3293. if (d == ".") {
  3294. dirs.remove_at(i);
  3295. i--;
  3296. } else if (d == "..") {
  3297. if (i == 0) {
  3298. dirs.remove_at(i);
  3299. i--;
  3300. } else {
  3301. dirs.remove_at(i);
  3302. dirs.remove_at(i - 1);
  3303. i -= 2;
  3304. }
  3305. }
  3306. }
  3307. s = "";
  3308. for (int i = 0; i < dirs.size(); i++) {
  3309. if (i > 0) {
  3310. s += "/";
  3311. }
  3312. s += dirs[i];
  3313. }
  3314. return drive + s;
  3315. }
  3316. static int _humanize_digits(int p_num) {
  3317. if (p_num < 100) {
  3318. return 2;
  3319. } else if (p_num < 1024) {
  3320. return 1;
  3321. } else {
  3322. return 0;
  3323. }
  3324. }
  3325. String String::humanize_size(uint64_t p_size) {
  3326. uint64_t _div = 1;
  3327. Vector<String> prefixes;
  3328. prefixes.push_back(RTR("B"));
  3329. prefixes.push_back(RTR("KiB"));
  3330. prefixes.push_back(RTR("MiB"));
  3331. prefixes.push_back(RTR("GiB"));
  3332. prefixes.push_back(RTR("TiB"));
  3333. prefixes.push_back(RTR("PiB"));
  3334. prefixes.push_back(RTR("EiB"));
  3335. int prefix_idx = 0;
  3336. while (prefix_idx < prefixes.size() - 1 && p_size > (_div * 1024)) {
  3337. _div *= 1024;
  3338. prefix_idx++;
  3339. }
  3340. const int digits = prefix_idx > 0 ? _humanize_digits(p_size / _div) : 0;
  3341. const double divisor = prefix_idx > 0 ? _div : 1;
  3342. return String::num(p_size / divisor).pad_decimals(digits) + " " + prefixes[prefix_idx];
  3343. }
  3344. bool String::is_absolute_path() const {
  3345. if (length() > 1) {
  3346. return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
  3347. } else if ((length()) == 1) {
  3348. return (operator[](0) == '/' || operator[](0) == '\\');
  3349. } else {
  3350. return false;
  3351. }
  3352. }
  3353. String String::validate_identifier() const {
  3354. if (is_empty()) {
  3355. return "_"; // Empty string is not a valid identifier;
  3356. }
  3357. String result;
  3358. if (is_digit(operator[](0))) {
  3359. result = "_" + *this;
  3360. } else {
  3361. result = *this;
  3362. }
  3363. int len = result.length();
  3364. char32_t *buffer = result.ptrw();
  3365. for (int i = 0; i < len; i++) {
  3366. if (!is_ascii_identifier_char(buffer[i])) {
  3367. buffer[i] = '_';
  3368. }
  3369. }
  3370. return result;
  3371. }
  3372. bool String::is_valid_identifier() const {
  3373. int len = length();
  3374. if (len == 0) {
  3375. return false;
  3376. }
  3377. if (is_digit(operator[](0))) {
  3378. return false;
  3379. }
  3380. const char32_t *str = &operator[](0);
  3381. for (int i = 0; i < len; i++) {
  3382. if (!is_ascii_identifier_char(str[i])) {
  3383. return false;
  3384. }
  3385. }
  3386. return true;
  3387. }
  3388. bool String::is_valid_string() const {
  3389. int l = length();
  3390. const char32_t *src = get_data();
  3391. bool valid = true;
  3392. for (int i = 0; i < l; i++) {
  3393. valid = valid && (src[i] < 0xd800 || (src[i] > 0xdfff && src[i] <= 0x10ffff));
  3394. }
  3395. return valid;
  3396. }
  3397. String String::uri_encode() const {
  3398. const CharString temp = utf8();
  3399. String res;
  3400. for (int i = 0; i < temp.length(); ++i) {
  3401. uint8_t ord = temp[i];
  3402. if (ord == '.' || ord == '-' || ord == '~' || is_ascii_identifier_char(ord)) {
  3403. res += ord;
  3404. } else {
  3405. char p[4] = { '%', 0, 0, 0 };
  3406. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  3407. p[1] = hex[ord >> 4];
  3408. p[2] = hex[ord & 0xF];
  3409. res += p;
  3410. }
  3411. }
  3412. return res;
  3413. }
  3414. String String::uri_decode() const {
  3415. CharString src = utf8();
  3416. CharString res;
  3417. for (int i = 0; i < src.length(); ++i) {
  3418. if (src[i] == '%' && i + 2 < src.length()) {
  3419. char ord1 = src[i + 1];
  3420. if (is_digit(ord1) || is_ascii_upper_case(ord1)) {
  3421. char ord2 = src[i + 2];
  3422. if (is_digit(ord2) || is_ascii_upper_case(ord2)) {
  3423. char bytes[3] = { (char)ord1, (char)ord2, 0 };
  3424. res += (char)strtol(bytes, nullptr, 16);
  3425. i += 2;
  3426. }
  3427. } else {
  3428. res += src[i];
  3429. }
  3430. } else if (src[i] == '+') {
  3431. res += ' ';
  3432. } else {
  3433. res += src[i];
  3434. }
  3435. }
  3436. return String::utf8(res);
  3437. }
  3438. String String::c_unescape() const {
  3439. String escaped = *this;
  3440. escaped = escaped.replace("\\a", "\a");
  3441. escaped = escaped.replace("\\b", "\b");
  3442. escaped = escaped.replace("\\f", "\f");
  3443. escaped = escaped.replace("\\n", "\n");
  3444. escaped = escaped.replace("\\r", "\r");
  3445. escaped = escaped.replace("\\t", "\t");
  3446. escaped = escaped.replace("\\v", "\v");
  3447. escaped = escaped.replace("\\'", "\'");
  3448. escaped = escaped.replace("\\\"", "\"");
  3449. escaped = escaped.replace("\\\\", "\\");
  3450. return escaped;
  3451. }
  3452. String String::c_escape() const {
  3453. String escaped = *this;
  3454. escaped = escaped.replace("\\", "\\\\");
  3455. escaped = escaped.replace("\a", "\\a");
  3456. escaped = escaped.replace("\b", "\\b");
  3457. escaped = escaped.replace("\f", "\\f");
  3458. escaped = escaped.replace("\n", "\\n");
  3459. escaped = escaped.replace("\r", "\\r");
  3460. escaped = escaped.replace("\t", "\\t");
  3461. escaped = escaped.replace("\v", "\\v");
  3462. escaped = escaped.replace("\'", "\\'");
  3463. escaped = escaped.replace("\"", "\\\"");
  3464. return escaped;
  3465. }
  3466. String String::c_escape_multiline() const {
  3467. String escaped = *this;
  3468. escaped = escaped.replace("\\", "\\\\");
  3469. escaped = escaped.replace("\"", "\\\"");
  3470. return escaped;
  3471. }
  3472. String String::json_escape() const {
  3473. String escaped = *this;
  3474. escaped = escaped.replace("\\", "\\\\");
  3475. escaped = escaped.replace("\b", "\\b");
  3476. escaped = escaped.replace("\f", "\\f");
  3477. escaped = escaped.replace("\n", "\\n");
  3478. escaped = escaped.replace("\r", "\\r");
  3479. escaped = escaped.replace("\t", "\\t");
  3480. escaped = escaped.replace("\v", "\\v");
  3481. escaped = escaped.replace("\"", "\\\"");
  3482. return escaped;
  3483. }
  3484. String String::xml_escape(bool p_escape_quotes) const {
  3485. String str = *this;
  3486. str = str.replace("&", "&amp;");
  3487. str = str.replace("<", "&lt;");
  3488. str = str.replace(">", "&gt;");
  3489. if (p_escape_quotes) {
  3490. str = str.replace("'", "&apos;");
  3491. str = str.replace("\"", "&quot;");
  3492. }
  3493. /*
  3494. for (int i=1;i<32;i++) {
  3495. char chr[2]={i,0};
  3496. str=str.replace(chr,"&#"+String::num(i)+";");
  3497. }*/
  3498. return str;
  3499. }
  3500. static _FORCE_INLINE_ int _xml_unescape(const char32_t *p_src, int p_src_len, char32_t *p_dst) {
  3501. int len = 0;
  3502. while (p_src_len) {
  3503. if (*p_src == '&') {
  3504. int eat = 0;
  3505. if (p_src_len >= 4 && p_src[1] == '#') {
  3506. char32_t c = 0;
  3507. bool overflow = false;
  3508. if (p_src[2] == 'x') {
  3509. // Hex entity &#x<num>;
  3510. for (int i = 3; i < p_src_len; i++) {
  3511. eat = i + 1;
  3512. char32_t ct = p_src[i];
  3513. if (ct == ';') {
  3514. break;
  3515. } else if (is_digit(ct)) {
  3516. ct = ct - '0';
  3517. } else if (ct >= 'a' && ct <= 'f') {
  3518. ct = (ct - 'a') + 10;
  3519. } else if (ct >= 'A' && ct <= 'F') {
  3520. ct = (ct - 'A') + 10;
  3521. } else {
  3522. break;
  3523. }
  3524. if (c > (UINT32_MAX >> 4)) {
  3525. overflow = true;
  3526. break;
  3527. }
  3528. c <<= 4;
  3529. c |= ct;
  3530. }
  3531. } else {
  3532. // Decimal entity &#<num>;
  3533. for (int i = 2; i < p_src_len; i++) {
  3534. eat = i + 1;
  3535. char32_t ct = p_src[i];
  3536. if (ct == ';' || !is_digit(ct)) {
  3537. break;
  3538. }
  3539. }
  3540. if (p_src[eat - 1] == ';') {
  3541. int64_t val = String::to_int(p_src + 2, eat - 3);
  3542. if (val > 0 && val <= UINT32_MAX) {
  3543. c = (char32_t)val;
  3544. } else {
  3545. overflow = true;
  3546. }
  3547. }
  3548. }
  3549. // Value must be non-zero, in the range of char32_t,
  3550. // actually end with ';'. If invalid, leave the entity as-is
  3551. if (c == '\0' || overflow || p_src[eat - 1] != ';') {
  3552. eat = 1;
  3553. c = *p_src;
  3554. }
  3555. if (p_dst) {
  3556. *p_dst = c;
  3557. }
  3558. } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') {
  3559. if (p_dst) {
  3560. *p_dst = '>';
  3561. }
  3562. eat = 4;
  3563. } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') {
  3564. if (p_dst) {
  3565. *p_dst = '<';
  3566. }
  3567. eat = 4;
  3568. } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') {
  3569. if (p_dst) {
  3570. *p_dst = '&';
  3571. }
  3572. eat = 5;
  3573. } 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] == ';') {
  3574. if (p_dst) {
  3575. *p_dst = '"';
  3576. }
  3577. eat = 6;
  3578. } 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] == ';') {
  3579. if (p_dst) {
  3580. *p_dst = '\'';
  3581. }
  3582. eat = 6;
  3583. } else {
  3584. if (p_dst) {
  3585. *p_dst = *p_src;
  3586. }
  3587. eat = 1;
  3588. }
  3589. if (p_dst) {
  3590. p_dst++;
  3591. }
  3592. len++;
  3593. p_src += eat;
  3594. p_src_len -= eat;
  3595. } else {
  3596. if (p_dst) {
  3597. *p_dst = *p_src;
  3598. p_dst++;
  3599. }
  3600. len++;
  3601. p_src++;
  3602. p_src_len--;
  3603. }
  3604. }
  3605. return len;
  3606. }
  3607. String String::xml_unescape() const {
  3608. String str;
  3609. int l = length();
  3610. int len = _xml_unescape(get_data(), l, nullptr);
  3611. if (len == 0) {
  3612. return String();
  3613. }
  3614. str.resize(len + 1);
  3615. _xml_unescape(get_data(), l, str.ptrw());
  3616. str[len] = 0;
  3617. return str;
  3618. }
  3619. String String::pad_decimals(int p_digits) const {
  3620. String s = *this;
  3621. int c = s.find(".");
  3622. if (c == -1) {
  3623. if (p_digits <= 0) {
  3624. return s;
  3625. }
  3626. s += ".";
  3627. c = s.length() - 1;
  3628. } else {
  3629. if (p_digits <= 0) {
  3630. return s.substr(0, c);
  3631. }
  3632. }
  3633. if (s.length() - (c + 1) > p_digits) {
  3634. return s.substr(0, c + p_digits + 1);
  3635. } else {
  3636. int zeros_to_add = p_digits - s.length() + (c + 1);
  3637. return s + String("0").repeat(zeros_to_add);
  3638. }
  3639. }
  3640. String String::pad_zeros(int p_digits) const {
  3641. String s = *this;
  3642. int end = s.find(".");
  3643. if (end == -1) {
  3644. end = s.length();
  3645. }
  3646. if (end == 0) {
  3647. return s;
  3648. }
  3649. int begin = 0;
  3650. while (begin < end && !is_digit(s[begin])) {
  3651. begin++;
  3652. }
  3653. int zeros_to_add = p_digits - (end - begin);
  3654. if (zeros_to_add <= 0) {
  3655. return s;
  3656. } else {
  3657. return s.insert(begin, String("0").repeat(zeros_to_add));
  3658. }
  3659. }
  3660. String String::trim_prefix(const String &p_prefix) const {
  3661. String s = *this;
  3662. if (s.begins_with(p_prefix)) {
  3663. return s.substr(p_prefix.length(), s.length() - p_prefix.length());
  3664. }
  3665. return s;
  3666. }
  3667. String String::trim_suffix(const String &p_suffix) const {
  3668. String s = *this;
  3669. if (s.ends_with(p_suffix)) {
  3670. return s.substr(0, s.length() - p_suffix.length());
  3671. }
  3672. return s;
  3673. }
  3674. bool String::is_valid_int() const {
  3675. int len = length();
  3676. if (len == 0) {
  3677. return false;
  3678. }
  3679. int from = 0;
  3680. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  3681. from++;
  3682. }
  3683. for (int i = from; i < len; i++) {
  3684. if (!is_digit(operator[](i))) {
  3685. return false; // no start with number plz
  3686. }
  3687. }
  3688. return true;
  3689. }
  3690. bool String::is_valid_hex_number(bool p_with_prefix) const {
  3691. int len = length();
  3692. if (len == 0) {
  3693. return false;
  3694. }
  3695. int from = 0;
  3696. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  3697. from++;
  3698. }
  3699. if (p_with_prefix) {
  3700. if (len < 3) {
  3701. return false;
  3702. }
  3703. if (operator[](from) != '0' || operator[](from + 1) != 'x') {
  3704. return false;
  3705. }
  3706. from += 2;
  3707. }
  3708. for (int i = from; i < len; i++) {
  3709. char32_t c = operator[](i);
  3710. if (is_hex_digit(c)) {
  3711. continue;
  3712. }
  3713. return false;
  3714. }
  3715. return true;
  3716. }
  3717. bool String::is_valid_float() const {
  3718. int len = length();
  3719. if (len == 0) {
  3720. return false;
  3721. }
  3722. int from = 0;
  3723. if (operator[](0) == '+' || operator[](0) == '-') {
  3724. from++;
  3725. }
  3726. bool exponent_found = false;
  3727. bool period_found = false;
  3728. bool sign_found = false;
  3729. bool exponent_values_found = false;
  3730. bool numbers_found = false;
  3731. for (int i = from; i < len; i++) {
  3732. if (is_digit(operator[](i))) {
  3733. if (exponent_found) {
  3734. exponent_values_found = true;
  3735. } else {
  3736. numbers_found = true;
  3737. }
  3738. } else if (numbers_found && !exponent_found && operator[](i) == 'e') {
  3739. exponent_found = true;
  3740. } else if (!period_found && !exponent_found && operator[](i) == '.') {
  3741. period_found = true;
  3742. } else if ((operator[](i) == '-' || operator[](i) == '+') && exponent_found && !exponent_values_found && !sign_found) {
  3743. sign_found = true;
  3744. } else {
  3745. return false; // no start with number plz
  3746. }
  3747. }
  3748. return numbers_found;
  3749. }
  3750. String String::path_to_file(const String &p_path) const {
  3751. // Don't get base dir for src, this is expected to be a dir already.
  3752. String src = this->replace("\\", "/");
  3753. String dst = p_path.replace("\\", "/").get_base_dir();
  3754. String rel = src.path_to(dst);
  3755. if (rel == dst) { // failed
  3756. return p_path;
  3757. } else {
  3758. return rel + p_path.get_file();
  3759. }
  3760. }
  3761. String String::path_to(const String &p_path) const {
  3762. String src = this->replace("\\", "/");
  3763. String dst = p_path.replace("\\", "/");
  3764. if (!src.ends_with("/")) {
  3765. src += "/";
  3766. }
  3767. if (!dst.ends_with("/")) {
  3768. dst += "/";
  3769. }
  3770. if (src.begins_with("res://") && dst.begins_with("res://")) {
  3771. src = src.replace("res://", "/");
  3772. dst = dst.replace("res://", "/");
  3773. } else if (src.begins_with("user://") && dst.begins_with("user://")) {
  3774. src = src.replace("user://", "/");
  3775. dst = dst.replace("user://", "/");
  3776. } else if (src.begins_with("/") && dst.begins_with("/")) {
  3777. //nothing
  3778. } else {
  3779. //dos style
  3780. String src_begin = src.get_slicec('/', 0);
  3781. String dst_begin = dst.get_slicec('/', 0);
  3782. if (src_begin != dst_begin) {
  3783. return p_path; //impossible to do this
  3784. }
  3785. src = src.substr(src_begin.length(), src.length());
  3786. dst = dst.substr(dst_begin.length(), dst.length());
  3787. }
  3788. //remove leading and trailing slash and split
  3789. Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/");
  3790. Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/");
  3791. //find common parent
  3792. int common_parent = 0;
  3793. while (true) {
  3794. if (src_dirs.size() == common_parent) {
  3795. break;
  3796. }
  3797. if (dst_dirs.size() == common_parent) {
  3798. break;
  3799. }
  3800. if (src_dirs[common_parent] != dst_dirs[common_parent]) {
  3801. break;
  3802. }
  3803. common_parent++;
  3804. }
  3805. common_parent--;
  3806. int dirs_to_backtrack = (src_dirs.size() - 1) - common_parent;
  3807. String dir = String("../").repeat(dirs_to_backtrack);
  3808. for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
  3809. dir += dst_dirs[i] + "/";
  3810. }
  3811. if (dir.length() == 0) {
  3812. dir = "./";
  3813. }
  3814. return dir;
  3815. }
  3816. bool String::is_valid_html_color() const {
  3817. return Color::html_is_valid(*this);
  3818. }
  3819. // Changes made to the set of invalid filename characters must also be reflected in the String documentation for is_valid_filename.
  3820. static const char *invalid_filename_characters = ": / \\ ? * \" | % < >";
  3821. bool String::is_valid_filename() const {
  3822. String stripped = strip_edges();
  3823. if (*this != stripped) {
  3824. return false;
  3825. }
  3826. if (stripped.is_empty()) {
  3827. return false;
  3828. }
  3829. Vector<String> chars = String(invalid_filename_characters).split(" ");
  3830. for (const String &ch : chars) {
  3831. if (contains(ch)) {
  3832. return false;
  3833. }
  3834. }
  3835. return true;
  3836. }
  3837. String String::validate_filename() const {
  3838. Vector<String> chars = String(invalid_filename_characters).split(" ");
  3839. String name = strip_edges();
  3840. for (int i = 0; i < chars.size(); i++) {
  3841. name = name.replace(chars[i], "_");
  3842. }
  3843. return name;
  3844. }
  3845. bool String::is_valid_ip_address() const {
  3846. if (find(":") >= 0) {
  3847. Vector<String> ip = split(":");
  3848. for (int i = 0; i < ip.size(); i++) {
  3849. String n = ip[i];
  3850. if (n.is_empty()) {
  3851. continue;
  3852. }
  3853. if (n.is_valid_hex_number(false)) {
  3854. int64_t nint = n.hex_to_int();
  3855. if (nint < 0 || nint > 0xffff) {
  3856. return false;
  3857. }
  3858. continue;
  3859. }
  3860. if (!n.is_valid_ip_address()) {
  3861. return false;
  3862. }
  3863. }
  3864. } else {
  3865. Vector<String> ip = split(".");
  3866. if (ip.size() != 4) {
  3867. return false;
  3868. }
  3869. for (int i = 0; i < ip.size(); i++) {
  3870. String n = ip[i];
  3871. if (!n.is_valid_int()) {
  3872. return false;
  3873. }
  3874. int val = n.to_int();
  3875. if (val < 0 || val > 255) {
  3876. return false;
  3877. }
  3878. }
  3879. }
  3880. return true;
  3881. }
  3882. bool String::is_resource_file() const {
  3883. return begins_with("res://") && find("::") == -1;
  3884. }
  3885. bool String::is_relative_path() const {
  3886. return !is_absolute_path();
  3887. }
  3888. String String::get_base_dir() const {
  3889. int end = 0;
  3890. // URL scheme style base.
  3891. int basepos = find("://");
  3892. if (basepos != -1) {
  3893. end = basepos + 3;
  3894. }
  3895. // Windows top level directory base.
  3896. if (end == 0) {
  3897. basepos = find(":/");
  3898. if (basepos == -1) {
  3899. basepos = find(":\\");
  3900. }
  3901. if (basepos != -1) {
  3902. end = basepos + 2;
  3903. }
  3904. }
  3905. // Windows UNC network share path.
  3906. if (end == 0) {
  3907. if (is_network_share_path()) {
  3908. basepos = find("/", 2);
  3909. if (basepos == -1) {
  3910. basepos = find("\\", 2);
  3911. }
  3912. int servpos = find("/", basepos + 1);
  3913. if (servpos == -1) {
  3914. servpos = find("\\", basepos + 1);
  3915. }
  3916. if (servpos != -1) {
  3917. end = servpos + 1;
  3918. }
  3919. }
  3920. }
  3921. // Unix root directory base.
  3922. if (end == 0) {
  3923. if (begins_with("/")) {
  3924. end = 1;
  3925. }
  3926. }
  3927. String rs;
  3928. String base;
  3929. if (end != 0) {
  3930. rs = substr(end, length());
  3931. base = substr(0, end);
  3932. } else {
  3933. rs = *this;
  3934. }
  3935. int sep = MAX(rs.rfind("/"), rs.rfind("\\"));
  3936. if (sep == -1) {
  3937. return base;
  3938. }
  3939. return base + rs.substr(0, sep);
  3940. }
  3941. String String::get_file() const {
  3942. int sep = MAX(rfind("/"), rfind("\\"));
  3943. if (sep == -1) {
  3944. return *this;
  3945. }
  3946. return substr(sep + 1, length());
  3947. }
  3948. String String::get_extension() const {
  3949. int pos = rfind(".");
  3950. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  3951. return "";
  3952. }
  3953. return substr(pos + 1, length());
  3954. }
  3955. String String::path_join(const String &p_file) const {
  3956. if (is_empty()) {
  3957. return p_file;
  3958. }
  3959. if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/')) {
  3960. return *this + p_file;
  3961. }
  3962. return *this + "/" + p_file;
  3963. }
  3964. String String::property_name_encode() const {
  3965. // Escape and quote strings with extended ASCII or further Unicode characters
  3966. // as well as '"', '=' or ' ' (32)
  3967. const char32_t *cstr = get_data();
  3968. for (int i = 0; cstr[i]; i++) {
  3969. if (cstr[i] == '=' || cstr[i] == '"' || cstr[i] == ';' || cstr[i] == '[' || cstr[i] == ']' || cstr[i] < 33 || cstr[i] > 126) {
  3970. return "\"" + c_escape_multiline() + "\"";
  3971. }
  3972. }
  3973. // Keep as is
  3974. return *this;
  3975. }
  3976. // Changes made to the set of invalid characters must also be reflected in the String documentation.
  3977. static const char32_t invalid_node_name_characters[] = { '.', ':', '@', '/', '\"', UNIQUE_NODE_PREFIX[0], 0 };
  3978. String String::get_invalid_node_name_characters(bool p_allow_internal) {
  3979. // Do not use this function for critical validation.
  3980. String r;
  3981. const char32_t *c = invalid_node_name_characters;
  3982. while (*c) {
  3983. if (p_allow_internal && *c == '@') {
  3984. c++;
  3985. continue;
  3986. }
  3987. if (c != invalid_node_name_characters) {
  3988. r += " ";
  3989. }
  3990. r += String::chr(*c);
  3991. c++;
  3992. }
  3993. return r;
  3994. }
  3995. String String::validate_node_name() const {
  3996. // This is a critical validation in node addition, so it must be optimized.
  3997. const char32_t *cn = ptr();
  3998. if (cn == nullptr) {
  3999. return String();
  4000. }
  4001. bool valid = true;
  4002. uint32_t idx = 0;
  4003. while (cn[idx]) {
  4004. const char32_t *c = invalid_node_name_characters;
  4005. while (*c) {
  4006. if (cn[idx] == *c) {
  4007. valid = false;
  4008. break;
  4009. }
  4010. c++;
  4011. }
  4012. if (!valid) {
  4013. break;
  4014. }
  4015. idx++;
  4016. }
  4017. if (valid) {
  4018. return *this;
  4019. }
  4020. String validated = *this;
  4021. char32_t *nn = validated.ptrw();
  4022. while (nn[idx]) {
  4023. const char32_t *c = invalid_node_name_characters;
  4024. while (*c) {
  4025. if (nn[idx] == *c) {
  4026. nn[idx] = '_';
  4027. break;
  4028. }
  4029. c++;
  4030. }
  4031. idx++;
  4032. }
  4033. return validated;
  4034. }
  4035. String String::get_basename() const {
  4036. int pos = rfind(".");
  4037. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  4038. return *this;
  4039. }
  4040. return substr(0, pos);
  4041. }
  4042. String itos(int64_t p_val) {
  4043. return String::num_int64(p_val);
  4044. }
  4045. String uitos(uint64_t p_val) {
  4046. return String::num_uint64(p_val);
  4047. }
  4048. String rtos(double p_val) {
  4049. return String::num(p_val);
  4050. }
  4051. String rtoss(double p_val) {
  4052. return String::num_scientific(p_val);
  4053. }
  4054. // Right-pad with a character.
  4055. String String::rpad(int min_length, const String &character) const {
  4056. String s = *this;
  4057. int padding = min_length - s.length();
  4058. if (padding > 0) {
  4059. s += character.repeat(padding);
  4060. }
  4061. return s;
  4062. }
  4063. // Left-pad with a character.
  4064. String String::lpad(int min_length, const String &character) const {
  4065. String s = *this;
  4066. int padding = min_length - s.length();
  4067. if (padding > 0) {
  4068. s = character.repeat(padding) + s;
  4069. }
  4070. return s;
  4071. }
  4072. // sprintf is implemented in GDScript via:
  4073. // "fish %s pie" % "frog"
  4074. // "fish %s %d pie" % ["frog", 12]
  4075. // In case of an error, the string returned is the error description and "error" is true.
  4076. String String::sprintf(const Array &values, bool *error) const {
  4077. String formatted;
  4078. char32_t *self = (char32_t *)get_data();
  4079. bool in_format = false;
  4080. int value_index = 0;
  4081. int min_chars = 0;
  4082. int min_decimals = 0;
  4083. bool in_decimals = false;
  4084. bool pad_with_zeros = false;
  4085. bool left_justified = false;
  4086. bool show_sign = false;
  4087. if (error) {
  4088. *error = true;
  4089. }
  4090. for (; *self; self++) {
  4091. const char32_t c = *self;
  4092. if (in_format) { // We have % - let's see what else we get.
  4093. switch (c) {
  4094. case '%': { // Replace %% with %
  4095. formatted += chr(c);
  4096. in_format = false;
  4097. break;
  4098. }
  4099. case 'd': // Integer (signed)
  4100. case 'o': // Octal
  4101. case 'x': // Hexadecimal (lowercase)
  4102. case 'X': { // Hexadecimal (uppercase)
  4103. if (value_index >= values.size()) {
  4104. return "not enough arguments for format string";
  4105. }
  4106. if (!values[value_index].is_num()) {
  4107. return "a number is required";
  4108. }
  4109. int64_t value = values[value_index];
  4110. int base = 16;
  4111. bool capitalize = false;
  4112. switch (c) {
  4113. case 'd':
  4114. base = 10;
  4115. break;
  4116. case 'o':
  4117. base = 8;
  4118. break;
  4119. case 'x':
  4120. break;
  4121. case 'X':
  4122. base = 16;
  4123. capitalize = true;
  4124. break;
  4125. }
  4126. // Get basic number.
  4127. String str = String::num_int64(ABS(value), base, capitalize);
  4128. int number_len = str.length();
  4129. // Padding.
  4130. int pad_chars_count = (value < 0 || show_sign) ? min_chars - 1 : min_chars;
  4131. String pad_char = pad_with_zeros ? String("0") : String(" ");
  4132. if (left_justified) {
  4133. str = str.rpad(pad_chars_count, pad_char);
  4134. } else {
  4135. str = str.lpad(pad_chars_count, pad_char);
  4136. }
  4137. // Sign.
  4138. if (show_sign || value < 0) {
  4139. String sign_char = value < 0 ? "-" : "+";
  4140. if (left_justified) {
  4141. str = str.insert(0, sign_char);
  4142. } else {
  4143. str = str.insert(pad_with_zeros ? 0 : str.length() - number_len, sign_char);
  4144. }
  4145. }
  4146. formatted += str;
  4147. ++value_index;
  4148. in_format = false;
  4149. break;
  4150. }
  4151. case 'f': { // Float
  4152. if (value_index >= values.size()) {
  4153. return "not enough arguments for format string";
  4154. }
  4155. if (!values[value_index].is_num()) {
  4156. return "a number is required";
  4157. }
  4158. double value = values[value_index];
  4159. bool is_negative = signbit(value);
  4160. String str = String::num(Math::abs(value), min_decimals);
  4161. const bool is_finite = Math::is_finite(value);
  4162. // Pad decimals out.
  4163. if (is_finite) {
  4164. str = str.pad_decimals(min_decimals);
  4165. }
  4166. int initial_len = str.length();
  4167. // Padding. Leave room for sign later if required.
  4168. int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars;
  4169. String pad_char = (pad_with_zeros && is_finite) ? String("0") : String(" "); // Never pad NaN or inf with zeros
  4170. if (left_justified) {
  4171. str = str.rpad(pad_chars_count, pad_char);
  4172. } else {
  4173. str = str.lpad(pad_chars_count, pad_char);
  4174. }
  4175. // Add sign if needed.
  4176. if (show_sign || is_negative) {
  4177. String sign_char = is_negative ? "-" : "+";
  4178. if (left_justified) {
  4179. str = str.insert(0, sign_char);
  4180. } else {
  4181. str = str.insert(pad_with_zeros ? 0 : str.length() - initial_len, sign_char);
  4182. }
  4183. }
  4184. formatted += str;
  4185. ++value_index;
  4186. in_format = false;
  4187. break;
  4188. }
  4189. case 'v': { // Vector2/3/4/2i/3i/4i
  4190. if (value_index >= values.size()) {
  4191. return "not enough arguments for format string";
  4192. }
  4193. int count;
  4194. switch (values[value_index].get_type()) {
  4195. case Variant::VECTOR2:
  4196. case Variant::VECTOR2I: {
  4197. count = 2;
  4198. } break;
  4199. case Variant::VECTOR3:
  4200. case Variant::VECTOR3I: {
  4201. count = 3;
  4202. } break;
  4203. case Variant::VECTOR4:
  4204. case Variant::VECTOR4I: {
  4205. count = 4;
  4206. } break;
  4207. default: {
  4208. return "%v requires a vector type (Vector2/3/4/2i/3i/4i)";
  4209. }
  4210. }
  4211. Vector4 vec = values[value_index];
  4212. String str = "(";
  4213. for (int i = 0; i < count; i++) {
  4214. double val = vec[i];
  4215. String number_str = String::num(Math::abs(val), min_decimals);
  4216. const bool is_finite = Math::is_finite(val);
  4217. // Pad decimals out.
  4218. if (is_finite) {
  4219. number_str = number_str.pad_decimals(min_decimals);
  4220. }
  4221. int initial_len = number_str.length();
  4222. // Padding. Leave room for sign later if required.
  4223. int pad_chars_count = val < 0 ? min_chars - 1 : min_chars;
  4224. String pad_char = (pad_with_zeros && is_finite) ? String("0") : String(" "); // Never pad NaN or inf with zeros
  4225. if (left_justified) {
  4226. number_str = number_str.rpad(pad_chars_count, pad_char);
  4227. } else {
  4228. number_str = number_str.lpad(pad_chars_count, pad_char);
  4229. }
  4230. // Add sign if needed.
  4231. if (val < 0) {
  4232. if (left_justified) {
  4233. number_str = number_str.insert(0, "-");
  4234. } else {
  4235. number_str = number_str.insert(pad_with_zeros ? 0 : number_str.length() - initial_len, "-");
  4236. }
  4237. }
  4238. // Add number to combined string
  4239. str += number_str;
  4240. if (i < count - 1) {
  4241. str += ", ";
  4242. }
  4243. }
  4244. str += ")";
  4245. formatted += str;
  4246. ++value_index;
  4247. in_format = false;
  4248. break;
  4249. }
  4250. case 's': { // String
  4251. if (value_index >= values.size()) {
  4252. return "not enough arguments for format string";
  4253. }
  4254. String str = values[value_index];
  4255. // Padding.
  4256. if (left_justified) {
  4257. str = str.rpad(min_chars);
  4258. } else {
  4259. str = str.lpad(min_chars);
  4260. }
  4261. formatted += str;
  4262. ++value_index;
  4263. in_format = false;
  4264. break;
  4265. }
  4266. case 'c': {
  4267. if (value_index >= values.size()) {
  4268. return "not enough arguments for format string";
  4269. }
  4270. // Convert to character.
  4271. String str;
  4272. if (values[value_index].is_num()) {
  4273. int value = values[value_index];
  4274. if (value < 0) {
  4275. return "unsigned integer is lower than minimum";
  4276. } else if (value >= 0xd800 && value <= 0xdfff) {
  4277. return "unsigned integer is invalid Unicode character";
  4278. } else if (value > 0x10ffff) {
  4279. return "unsigned integer is greater than maximum";
  4280. }
  4281. str = chr(values[value_index]);
  4282. } else if (values[value_index].get_type() == Variant::STRING) {
  4283. str = values[value_index];
  4284. if (str.length() != 1) {
  4285. return "%c requires number or single-character string";
  4286. }
  4287. } else {
  4288. return "%c requires number or single-character string";
  4289. }
  4290. // Padding.
  4291. if (left_justified) {
  4292. str = str.rpad(min_chars);
  4293. } else {
  4294. str = str.lpad(min_chars);
  4295. }
  4296. formatted += str;
  4297. ++value_index;
  4298. in_format = false;
  4299. break;
  4300. }
  4301. case '-': { // Left justify
  4302. left_justified = true;
  4303. break;
  4304. }
  4305. case '+': { // Show + if positive.
  4306. show_sign = true;
  4307. break;
  4308. }
  4309. case '0':
  4310. case '1':
  4311. case '2':
  4312. case '3':
  4313. case '4':
  4314. case '5':
  4315. case '6':
  4316. case '7':
  4317. case '8':
  4318. case '9': {
  4319. int n = c - '0';
  4320. if (in_decimals) {
  4321. min_decimals *= 10;
  4322. min_decimals += n;
  4323. } else {
  4324. if (c == '0' && min_chars == 0) {
  4325. if (left_justified) {
  4326. WARN_PRINT("'0' flag ignored with '-' flag in string format");
  4327. } else {
  4328. pad_with_zeros = true;
  4329. }
  4330. } else {
  4331. min_chars *= 10;
  4332. min_chars += n;
  4333. }
  4334. }
  4335. break;
  4336. }
  4337. case '.': { // Float/Vector separator.
  4338. if (in_decimals) {
  4339. return "too many decimal points in format";
  4340. }
  4341. in_decimals = true;
  4342. min_decimals = 0; // We want to add the value manually.
  4343. break;
  4344. }
  4345. case '*': { // Dynamic width, based on value.
  4346. if (value_index >= values.size()) {
  4347. return "not enough arguments for format string";
  4348. }
  4349. Variant::Type value_type = values[value_index].get_type();
  4350. if (!values[value_index].is_num() &&
  4351. value_type != Variant::VECTOR2 && value_type != Variant::VECTOR2I &&
  4352. value_type != Variant::VECTOR3 && value_type != Variant::VECTOR3I &&
  4353. value_type != Variant::VECTOR4 && value_type != Variant::VECTOR4I) {
  4354. return "* wants number or vector";
  4355. }
  4356. int size = values[value_index];
  4357. if (in_decimals) {
  4358. min_decimals = size;
  4359. } else {
  4360. min_chars = size;
  4361. }
  4362. ++value_index;
  4363. break;
  4364. }
  4365. default: {
  4366. return "unsupported format character";
  4367. }
  4368. }
  4369. } else { // Not in format string.
  4370. switch (c) {
  4371. case '%':
  4372. in_format = true;
  4373. // Back to defaults:
  4374. min_chars = 0;
  4375. min_decimals = 6;
  4376. pad_with_zeros = false;
  4377. left_justified = false;
  4378. show_sign = false;
  4379. in_decimals = false;
  4380. break;
  4381. default:
  4382. formatted += chr(c);
  4383. }
  4384. }
  4385. }
  4386. if (in_format) {
  4387. return "incomplete format";
  4388. }
  4389. if (value_index != values.size()) {
  4390. return "not all arguments converted during string formatting";
  4391. }
  4392. if (error) {
  4393. *error = false;
  4394. }
  4395. return formatted;
  4396. }
  4397. String String::quote(String quotechar) const {
  4398. return quotechar + *this + quotechar;
  4399. }
  4400. String String::unquote() const {
  4401. if (!is_quoted()) {
  4402. return *this;
  4403. }
  4404. return substr(1, length() - 2);
  4405. }
  4406. Vector<uint8_t> String::to_ascii_buffer() const {
  4407. const String *s = this;
  4408. if (s->is_empty()) {
  4409. return Vector<uint8_t>();
  4410. }
  4411. CharString charstr = s->ascii();
  4412. Vector<uint8_t> retval;
  4413. size_t len = charstr.length();
  4414. retval.resize(len);
  4415. uint8_t *w = retval.ptrw();
  4416. memcpy(w, charstr.ptr(), len);
  4417. return retval;
  4418. }
  4419. Vector<uint8_t> String::to_utf8_buffer() const {
  4420. const String *s = this;
  4421. if (s->is_empty()) {
  4422. return Vector<uint8_t>();
  4423. }
  4424. CharString charstr = s->utf8();
  4425. Vector<uint8_t> retval;
  4426. size_t len = charstr.length();
  4427. retval.resize(len);
  4428. uint8_t *w = retval.ptrw();
  4429. memcpy(w, charstr.ptr(), len);
  4430. return retval;
  4431. }
  4432. Vector<uint8_t> String::to_utf16_buffer() const {
  4433. const String *s = this;
  4434. if (s->is_empty()) {
  4435. return Vector<uint8_t>();
  4436. }
  4437. Char16String charstr = s->utf16();
  4438. Vector<uint8_t> retval;
  4439. size_t len = charstr.length() * sizeof(char16_t);
  4440. retval.resize(len);
  4441. uint8_t *w = retval.ptrw();
  4442. memcpy(w, (const void *)charstr.ptr(), len);
  4443. return retval;
  4444. }
  4445. Vector<uint8_t> String::to_utf32_buffer() const {
  4446. const String *s = this;
  4447. if (s->is_empty()) {
  4448. return Vector<uint8_t>();
  4449. }
  4450. Vector<uint8_t> retval;
  4451. size_t len = s->length() * sizeof(char32_t);
  4452. retval.resize(len);
  4453. uint8_t *w = retval.ptrw();
  4454. memcpy(w, (const void *)s->ptr(), len);
  4455. return retval;
  4456. }
  4457. Vector<uint8_t> String::to_wchar_buffer() const {
  4458. #ifdef WINDOWS_ENABLED
  4459. return to_utf16_buffer();
  4460. #else
  4461. return to_utf32_buffer();
  4462. #endif
  4463. }
  4464. #ifdef TOOLS_ENABLED
  4465. /**
  4466. * "Tools TRanslate". Performs string replacement for internationalization
  4467. * within the editor. A translation context can optionally be specified to
  4468. * disambiguate between identical source strings in translations. When
  4469. * placeholders are desired, use `vformat(TTR("Example: %s"), some_string)`.
  4470. * If a string mentions a quantity (and may therefore need a dynamic plural form),
  4471. * use `TTRN()` instead of `TTR()`.
  4472. *
  4473. * NOTE: Only use `TTR()` in editor-only code (typically within the `editor/` folder).
  4474. * For translations that can be supplied by exported projects, use `RTR()` instead.
  4475. */
  4476. String TTR(const String &p_text, const String &p_context) {
  4477. if (TranslationServer::get_singleton()) {
  4478. return TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  4479. }
  4480. return p_text;
  4481. }
  4482. /**
  4483. * "Tools TRanslate for N items". Performs string replacement for
  4484. * internationalization within the editor. A translation context can optionally
  4485. * be specified to disambiguate between identical source strings in
  4486. * translations. Use `TTR()` if the string doesn't need dynamic plural form.
  4487. * When placeholders are desired, use
  4488. * `vformat(TTRN("%d item", "%d items", some_integer), some_integer)`.
  4489. * The placeholder must be present in both strings to avoid run-time warnings in `vformat()`.
  4490. *
  4491. * NOTE: Only use `TTRN()` in editor-only code (typically within the `editor/` folder).
  4492. * For translations that can be supplied by exported projects, use `RTRN()` instead.
  4493. */
  4494. String TTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4495. if (TranslationServer::get_singleton()) {
  4496. return TranslationServer::get_singleton()->tool_translate_plural(p_text, p_text_plural, p_n, p_context);
  4497. }
  4498. // Return message based on English plural rule if translation is not possible.
  4499. if (p_n == 1) {
  4500. return p_text;
  4501. }
  4502. return p_text_plural;
  4503. }
  4504. /**
  4505. * "Docs TRanslate". Used for the editor class reference documentation,
  4506. * handling descriptions extracted from the XML.
  4507. * It also replaces `$DOCS_URL` with the actual URL to the documentation's branch,
  4508. * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
  4509. */
  4510. String DTR(const String &p_text, const String &p_context) {
  4511. // Comes straight from the XML, so remove indentation and any trailing whitespace.
  4512. const String text = p_text.dedent().strip_edges();
  4513. if (TranslationServer::get_singleton()) {
  4514. return String(TranslationServer::get_singleton()->doc_translate(text, p_context)).replace("$DOCS_URL", VERSION_DOCS_URL);
  4515. }
  4516. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  4517. }
  4518. /**
  4519. * "Docs TRanslate for N items". Used for the editor class reference documentation
  4520. * (with support for plurals), handling descriptions extracted from the XML.
  4521. * It also replaces `$DOCS_URL` with the actual URL to the documentation's branch,
  4522. * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
  4523. */
  4524. String DTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4525. const String text = p_text.dedent().strip_edges();
  4526. const String text_plural = p_text_plural.dedent().strip_edges();
  4527. if (TranslationServer::get_singleton()) {
  4528. return String(TranslationServer::get_singleton()->doc_translate_plural(text, text_plural, p_n, p_context)).replace("$DOCS_URL", VERSION_DOCS_URL);
  4529. }
  4530. // Return message based on English plural rule if translation is not possible.
  4531. if (p_n == 1) {
  4532. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  4533. }
  4534. return text_plural.replace("$DOCS_URL", VERSION_DOCS_URL);
  4535. }
  4536. #endif
  4537. /**
  4538. * "Run-time TRanslate". Performs string replacement for internationalization
  4539. * within a running project. The translation string must be supplied by the
  4540. * project, as Godot does not provide built-in translations for `RTR()` strings
  4541. * to keep binary size low. A translation context can optionally be specified to
  4542. * disambiguate between identical source strings in translations. When
  4543. * placeholders are desired, use `vformat(RTR("Example: %s"), some_string)`.
  4544. * If a string mentions a quantity (and may therefore need a dynamic plural form),
  4545. * use `RTRN()` instead of `RTR()`.
  4546. *
  4547. * NOTE: Do not use `RTR()` in editor-only code (typically within the `editor/`
  4548. * folder). For editor translations, use `TTR()` instead.
  4549. */
  4550. String RTR(const String &p_text, const String &p_context) {
  4551. if (TranslationServer::get_singleton()) {
  4552. String rtr = TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  4553. if (rtr.is_empty() || rtr == p_text) {
  4554. return TranslationServer::get_singleton()->translate(p_text, p_context);
  4555. } else {
  4556. return rtr;
  4557. }
  4558. }
  4559. return p_text;
  4560. }
  4561. /**
  4562. * "Run-time TRanslate for N items". Performs string replacement for
  4563. * internationalization within a running project. The translation string must be
  4564. * supplied by the project, as Godot does not provide built-in translations for
  4565. * `RTRN()` strings to keep binary size low. A translation context can
  4566. * optionally be specified to disambiguate between identical source strings in
  4567. * translations. Use `RTR()` if the string doesn't need dynamic plural form.
  4568. * When placeholders are desired, use
  4569. * `vformat(RTRN("%d item", "%d items", some_integer), some_integer)`.
  4570. * The placeholder must be present in both strings to avoid run-time warnings in `vformat()`.
  4571. *
  4572. * NOTE: Do not use `RTRN()` in editor-only code (typically within the `editor/`
  4573. * folder). For editor translations, use `TTRN()` instead.
  4574. */
  4575. String RTRN(const String &p_text, const String &p_text_plural, int p_n, const String &p_context) {
  4576. if (TranslationServer::get_singleton()) {
  4577. String rtr = TranslationServer::get_singleton()->tool_translate_plural(p_text, p_text_plural, p_n, p_context);
  4578. if (rtr.is_empty() || rtr == p_text || rtr == p_text_plural) {
  4579. return TranslationServer::get_singleton()->translate_plural(p_text, p_text_plural, p_n, p_context);
  4580. } else {
  4581. return rtr;
  4582. }
  4583. }
  4584. // Return message based on English plural rule if translation is not possible.
  4585. if (p_n == 1) {
  4586. return p_text;
  4587. }
  4588. return p_text_plural;
  4589. }