ustring.cpp 102 KB

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