ustring.cpp 106 KB

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