ustring.cpp 88 KB

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