ustring.cpp 102 KB

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