ustring.cpp 109 KB

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