ustring.cpp 97 KB

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