ustring.cpp 103 KB

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