2
0

ustring.cpp 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574
  1. /*************************************************************************/
  2. /* ustring.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #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. uint8_t c = *ptrtmp >= 0 ? *ptrtmp : uint8_t(256 + *ptrtmp);
  1195. if (p_skip_cr && c == '\r') {
  1196. ptrtmp++;
  1197. continue;
  1198. }
  1199. /* Determine the number of characters in sequence */
  1200. if ((c & 0x80) == 0) {
  1201. skip = 0;
  1202. } else if ((c & 0xE0) == 0xC0) {
  1203. skip = 1;
  1204. } else if ((c & 0xF0) == 0xE0) {
  1205. skip = 2;
  1206. } else if ((c & 0xF8) == 0xF0) {
  1207. skip = 3;
  1208. if (sizeof(wchar_t) == 2) {
  1209. str_size++; // encode as surrogate pair.
  1210. }
  1211. } else if ((c & 0xFC) == 0xF8) {
  1212. skip = 4;
  1213. // invalid character, too long to encode as surrogates.
  1214. } else if ((c & 0xFE) == 0xFC) {
  1215. skip = 5;
  1216. // invalid character, too long to encode as surrogates.
  1217. } else {
  1218. _UNICERROR("invalid skip");
  1219. return true; //invalid utf8
  1220. }
  1221. if (skip == 1 && (c & 0x1E) == 0) {
  1222. //printf("overlong rejected\n");
  1223. _UNICERROR("overlong rejected");
  1224. return true; //reject overlong
  1225. }
  1226. str_size++;
  1227. } else {
  1228. --skip;
  1229. }
  1230. cstr_size++;
  1231. ptrtmp++;
  1232. }
  1233. if (skip) {
  1234. _UNICERROR("no space left");
  1235. return true; //not enough spac
  1236. }
  1237. }
  1238. if (str_size == 0) {
  1239. clear();
  1240. return false;
  1241. }
  1242. resize(str_size + 1);
  1243. CharType *dst = ptrw();
  1244. dst[str_size] = 0;
  1245. while (cstr_size) {
  1246. int len = 0;
  1247. if (p_skip_cr && *p_utf8 == '\r') {
  1248. p_utf8++;
  1249. continue;
  1250. }
  1251. /* Determine the number of characters in sequence */
  1252. if ((*p_utf8 & 0x80) == 0) {
  1253. len = 1;
  1254. } else if ((*p_utf8 & 0xE0) == 0xC0) {
  1255. len = 2;
  1256. } else if ((*p_utf8 & 0xF0) == 0xE0) {
  1257. len = 3;
  1258. } else if ((*p_utf8 & 0xF8) == 0xF0) {
  1259. len = 4;
  1260. } else if ((*p_utf8 & 0xFC) == 0xF8) {
  1261. len = 5;
  1262. } else if ((*p_utf8 & 0xFE) == 0xFC) {
  1263. len = 6;
  1264. } else {
  1265. _UNICERROR("invalid len");
  1266. return true; //invalid UTF8
  1267. }
  1268. if (len > cstr_size) {
  1269. _UNICERROR("no space left");
  1270. return true; //not enough space
  1271. }
  1272. if (len == 2 && (*p_utf8 & 0x1E) == 0) {
  1273. //printf("overlong rejected\n");
  1274. _UNICERROR("no space left");
  1275. return true; //reject overlong
  1276. }
  1277. /* Convert the first character */
  1278. uint32_t unichar = 0;
  1279. if (len == 1) {
  1280. unichar = *p_utf8;
  1281. } else {
  1282. unichar = (0xFF >> (len + 1)) & *p_utf8;
  1283. for (int i = 1; i < len; i++) {
  1284. if ((p_utf8[i] & 0xC0) != 0x80) {
  1285. _UNICERROR("invalid utf8");
  1286. return true; //invalid utf8
  1287. }
  1288. if (unichar == 0 && i == 2 && ((p_utf8[i] & 0x7F) >> (7 - len)) == 0) {
  1289. _UNICERROR("invalid utf8 overlong");
  1290. return true; //no overlong
  1291. }
  1292. unichar = (unichar << 6) | (p_utf8[i] & 0x3F);
  1293. }
  1294. }
  1295. if (sizeof(wchar_t) == 2 && unichar > 0x10FFFF) {
  1296. unichar = ' '; // invalid character, too long to encode as surrogates.
  1297. } else if (sizeof(wchar_t) == 2 && unichar > 0xFFFF) {
  1298. *(dst++) = uint32_t((unichar >> 10) + 0xD7C0); // lead surrogate.
  1299. *(dst++) = uint32_t((unichar & 0x3FF) | 0xDC00); // trail surrogate.
  1300. } else {
  1301. *(dst++) = unichar;
  1302. }
  1303. cstr_size -= len;
  1304. p_utf8 += len;
  1305. }
  1306. return false;
  1307. }
  1308. CharString String::utf8() const {
  1309. int l = length();
  1310. if (!l) {
  1311. return CharString();
  1312. }
  1313. const CharType *d = &operator[](0);
  1314. int fl = 0;
  1315. for (int i = 0; i < l; i++) {
  1316. uint32_t c = d[i];
  1317. if ((c & 0xfffffc00) == 0xd800) { // decode surrogate pair.
  1318. if ((i < l - 1) && (d[i + 1] & 0xfffffc00) == 0xdc00) {
  1319. c = (c << 10UL) + d[i + 1] - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  1320. i++; // skip trail surrogate.
  1321. } else {
  1322. fl += 1;
  1323. continue;
  1324. }
  1325. } else if ((c & 0xfffffc00) == 0xdc00) {
  1326. fl += 1;
  1327. continue;
  1328. }
  1329. if (c <= 0x7f) { // 7 bits.
  1330. fl += 1;
  1331. } else if (c <= 0x7ff) { // 11 bits
  1332. fl += 2;
  1333. } else if (c <= 0xffff) { // 16 bits
  1334. fl += 3;
  1335. } else if (c <= 0x001fffff) { // 21 bits
  1336. fl += 4;
  1337. } else if (c <= 0x03ffffff) { // 26 bits
  1338. fl += 5;
  1339. } else if (c <= 0x7fffffff) { // 31 bits
  1340. fl += 6;
  1341. }
  1342. }
  1343. CharString utf8s;
  1344. if (fl == 0) {
  1345. return utf8s;
  1346. }
  1347. utf8s.resize(fl + 1);
  1348. uint8_t *cdst = (uint8_t *)utf8s.get_data();
  1349. #define APPEND_CHAR(m_c) *(cdst++) = m_c
  1350. for (int i = 0; i < l; i++) {
  1351. uint32_t c = d[i];
  1352. if ((c & 0xfffffc00) == 0xd800) { // decode surrogate pair.
  1353. if ((i < l - 1) && (d[i + 1] & 0xfffffc00) == 0xdc00) {
  1354. c = (c << 10UL) + d[i + 1] - ((0xd800 << 10UL) + 0xdc00 - 0x10000);
  1355. i++; // skip trail surrogate.
  1356. } else {
  1357. APPEND_CHAR(' ');
  1358. continue;
  1359. }
  1360. } else if ((c & 0xfffffc00) == 0xdc00) {
  1361. APPEND_CHAR(' ');
  1362. continue;
  1363. }
  1364. if (c <= 0x7f) { // 7 bits.
  1365. APPEND_CHAR(c);
  1366. } else if (c <= 0x7ff) { // 11 bits
  1367. APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits.
  1368. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1369. } else if (c <= 0xffff) { // 16 bits
  1370. APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits.
  1371. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits.
  1372. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1373. } else if (c <= 0x001fffff) { // 21 bits
  1374. APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits.
  1375. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits.
  1376. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1377. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1378. } else if (c <= 0x03ffffff) { // 26 bits
  1379. APPEND_CHAR(uint32_t(0xf8 | ((c >> 24) & 0x03))); // Top 2 bits.
  1380. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Upper middle 6 bits.
  1381. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // middle 6 bits.
  1382. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
  1383. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1384. } else if (c <= 0x7fffffff) { // 31 bits
  1385. APPEND_CHAR(uint32_t(0xfc | ((c >> 30) & 0x01))); // Top 1 bit.
  1386. APPEND_CHAR(uint32_t(0x80 | ((c >> 24) & 0x3f))); // Upper upper middle 6 bits.
  1387. APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Lower upper middle 6 bits.
  1388. APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper lower middle 6 bits.
  1389. APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower lower middle 6 bits.
  1390. APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
  1391. }
  1392. }
  1393. #undef APPEND_CHAR
  1394. *cdst = 0; //trailing zero
  1395. return utf8s;
  1396. }
  1397. String::String(const char *p_str) {
  1398. copy_from(p_str);
  1399. }
  1400. String::String(const CharType *p_str, int p_clip_to_len) {
  1401. copy_from(p_str, p_clip_to_len);
  1402. }
  1403. String::String(const StrRange &p_range) {
  1404. if (!p_range.c_str) {
  1405. return;
  1406. }
  1407. copy_from(p_range.c_str, p_range.len);
  1408. }
  1409. int String::hex_to_int(bool p_with_prefix) const {
  1410. int len = length();
  1411. 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 + "\".");
  1412. const CharType *s = ptr();
  1413. int sign = s[0] == '-' ? -1 : 1;
  1414. if (sign < 0) {
  1415. s++;
  1416. }
  1417. if (p_with_prefix) {
  1418. ERR_FAIL_COND_V_MSG(s[0] != '0' || LOWERCASE(s[1]) != 'x', 0, "Invalid hexadecimal notation prefix in string \"" + *this + "\".");
  1419. s += 2;
  1420. }
  1421. int hex = 0;
  1422. while (*s) {
  1423. CharType c = LOWERCASE(*s);
  1424. int n;
  1425. if (c >= '0' && c <= '9') {
  1426. n = c - '0';
  1427. } else if (c >= 'a' && c <= 'f') {
  1428. n = (c - 'a') + 10;
  1429. } else {
  1430. ERR_FAIL_V_MSG(0, "Invalid hexadecimal notation character \"" + chr(*s) + "\" in string \"" + *this + "\".");
  1431. }
  1432. // Check for overflow/underflow, with special case to ensure INT32_MIN does not result in error
  1433. bool overflow = ((hex > INT32_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT32_MAX >> 4) + 1))) || (sign == -1 && hex == (INT32_MAX >> 4) + 1 && c > '0');
  1434. 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."));
  1435. hex *= 16;
  1436. hex += n;
  1437. s++;
  1438. }
  1439. return hex * sign;
  1440. }
  1441. int64_t String::hex_to_int64(bool p_with_prefix) const {
  1442. int len = length();
  1443. 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 + "\".");
  1444. const CharType *s = ptr();
  1445. int64_t sign = s[0] == '-' ? -1 : 1;
  1446. if (sign < 0) {
  1447. s++;
  1448. }
  1449. if (p_with_prefix) {
  1450. ERR_FAIL_COND_V_MSG(s[0] != '0' || LOWERCASE(s[1]) != 'x', 0, "Invalid hexadecimal notation prefix in string \"" + *this + "\".");
  1451. s += 2;
  1452. }
  1453. int64_t hex = 0;
  1454. while (*s) {
  1455. CharType c = LOWERCASE(*s);
  1456. int64_t n;
  1457. if (c >= '0' && c <= '9') {
  1458. n = c - '0';
  1459. } else if (c >= 'a' && c <= 'f') {
  1460. n = (c - 'a') + 10;
  1461. } else {
  1462. ERR_FAIL_V_MSG(0, "Invalid hexadecimal notation character \"" + chr(*s) + "\" in string \"" + *this + "\".");
  1463. }
  1464. bool overflow = ((hex > INT64_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT64_MAX >> 4) + 1))) || (sign == -1 && hex == (INT64_MAX >> 4) + 1 && c > '0');
  1465. 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."));
  1466. hex *= 16;
  1467. hex += n;
  1468. s++;
  1469. }
  1470. return hex * sign;
  1471. }
  1472. int64_t String::bin_to_int64(bool p_with_prefix) const {
  1473. int len = length();
  1474. 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 + "\".");
  1475. const CharType *s = ptr();
  1476. int64_t sign = s[0] == '-' ? -1 : 1;
  1477. if (sign < 0) {
  1478. s++;
  1479. }
  1480. if (p_with_prefix) {
  1481. ERR_FAIL_COND_V_MSG(s[0] != '0' || LOWERCASE(s[1]) != 'b', 0, "Invalid binary notation prefix in string \"" + *this + "\".");
  1482. s += 2;
  1483. }
  1484. int64_t binary = 0;
  1485. while (*s) {
  1486. CharType c = LOWERCASE(*s);
  1487. int64_t n;
  1488. if (c == '0' || c == '1') {
  1489. n = c - '0';
  1490. } else {
  1491. ERR_FAIL_V_MSG(0, "Invalid binary notation character \"" + chr(*s) + "\" in string \"" + *this + "\".");
  1492. }
  1493. // Check for overflow/underflow, with special case to ensure INT64_MIN does not result in error
  1494. bool overflow = ((binary > INT64_MAX / 2) && (sign == 1 || (sign == -1 && binary != (INT64_MAX >> 1) + 1))) || (sign == -1 && binary == (INT64_MAX >> 1) + 1 && c > '0');
  1495. 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."));
  1496. binary *= 2;
  1497. binary += n;
  1498. s++;
  1499. }
  1500. return binary * sign;
  1501. }
  1502. int String::to_int() const {
  1503. if (length() == 0) {
  1504. return 0;
  1505. }
  1506. int to = (find(".") >= 0) ? find(".") : length();
  1507. int integer = 0;
  1508. int sign = 1;
  1509. for (int i = 0; i < to; i++) {
  1510. CharType c = operator[](i);
  1511. if (c >= '0' && c <= '9') {
  1512. bool overflow = (integer > INT32_MAX / 10) || (integer == INT32_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  1513. 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."));
  1514. integer *= 10;
  1515. integer += c - '0';
  1516. } else if (integer == 0 && c == '-') {
  1517. sign = -sign;
  1518. }
  1519. }
  1520. return integer * sign;
  1521. }
  1522. int64_t String::to_int64() const {
  1523. if (length() == 0) {
  1524. return 0;
  1525. }
  1526. int to = (find(".") >= 0) ? find(".") : length();
  1527. int64_t integer = 0;
  1528. int64_t sign = 1;
  1529. for (int i = 0; i < to; i++) {
  1530. CharType c = operator[](i);
  1531. if (c >= '0' && c <= '9') {
  1532. bool overflow = (integer > INT64_MAX / 10) || (integer == INT64_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  1533. 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."));
  1534. integer *= 10;
  1535. integer += c - '0';
  1536. } else if (integer == 0 && c == '-') {
  1537. sign = -sign;
  1538. }
  1539. }
  1540. return integer * sign;
  1541. }
  1542. int String::to_int(const char *p_str, int p_len) {
  1543. int to = 0;
  1544. if (p_len >= 0) {
  1545. to = p_len;
  1546. } else {
  1547. while (p_str[to] != 0 && p_str[to] != '.') {
  1548. to++;
  1549. }
  1550. }
  1551. int integer = 0;
  1552. int sign = 1;
  1553. for (int i = 0; i < to; i++) {
  1554. char c = p_str[i];
  1555. if (c >= '0' && c <= '9') {
  1556. bool overflow = (integer > INT32_MAX / 10) || (integer == INT32_MAX / 10 && ((sign == 1 && c > '7') || (sign == -1 && c > '8')));
  1557. 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."));
  1558. integer *= 10;
  1559. integer += c - '0';
  1560. } else if (c == '-' && integer == 0) {
  1561. sign = -sign;
  1562. } else if (c != ' ') {
  1563. break;
  1564. }
  1565. }
  1566. return integer * sign;
  1567. }
  1568. bool String::is_numeric() const {
  1569. if (length() == 0) {
  1570. return false;
  1571. };
  1572. int s = 0;
  1573. if (operator[](0) == '-') {
  1574. ++s;
  1575. }
  1576. bool dot = false;
  1577. for (int i = s; i < length(); i++) {
  1578. CharType c = operator[](i);
  1579. if (c == '.') {
  1580. if (dot) {
  1581. return false;
  1582. };
  1583. dot = true;
  1584. }
  1585. if (c < '0' || c > '9') {
  1586. return false;
  1587. };
  1588. };
  1589. return true; // TODO: Use the parser below for this instead
  1590. };
  1591. template <class C>
  1592. static double built_in_strtod(
  1593. /* A decimal ASCII floating-point number,
  1594. * optionally preceded by white space. Must
  1595. * have form "-I.FE-X", where I is the integer
  1596. * part of the mantissa, F is the fractional
  1597. * part of the mantissa, and X is the
  1598. * exponent. Either of the signs may be "+",
  1599. * "-", or omitted. Either I or F may be
  1600. * omitted, or both. The decimal point isn't
  1601. * necessary unless F is present. The "E" may
  1602. * actually be an "e". E and X may both be
  1603. * omitted (but not just one). */
  1604. const C *string,
  1605. /* If non-nullptr, store terminating Cacter's
  1606. * address here. */
  1607. C **endPtr = nullptr) {
  1608. /* Largest possible base 10 exponent. Any
  1609. * exponent larger than this will already
  1610. * produce underflow or overflow, so there's
  1611. * no need to worry about additional digits. */
  1612. static const int maxExponent = 511;
  1613. /* Table giving binary powers of 10. Entry
  1614. * is 10^2^i. Used to convert decimal
  1615. * exponents into floating-point numbers. */
  1616. static const double powersOf10[] = {
  1617. 10.,
  1618. 100.,
  1619. 1.0e4,
  1620. 1.0e8,
  1621. 1.0e16,
  1622. 1.0e32,
  1623. 1.0e64,
  1624. 1.0e128,
  1625. 1.0e256
  1626. };
  1627. bool sign, expSign = false;
  1628. double fraction, dblExp;
  1629. const double *d;
  1630. const C *p;
  1631. int c;
  1632. /* Exponent read from "EX" field. */
  1633. int exp = 0;
  1634. /* Exponent that derives from the fractional
  1635. * part. Under normal circumstances, it is
  1636. * the negative of the number of digits in F.
  1637. * However, if I is very long, the last digits
  1638. * of I get dropped (otherwise a long I with a
  1639. * large negative exponent could cause an
  1640. * unnecessary overflow on I alone). In this
  1641. * case, fracExp is incremented one for each
  1642. * dropped digit. */
  1643. int fracExp = 0;
  1644. /* Number of digits in mantissa. */
  1645. int mantSize;
  1646. /* Number of mantissa digits BEFORE decimal point. */
  1647. int decPt;
  1648. /* Temporarily holds location of exponent in string. */
  1649. const C *pExp;
  1650. /*
  1651. * Strip off leading blanks and check for a sign.
  1652. */
  1653. p = string;
  1654. while (*p == ' ' || *p == '\t' || *p == '\n') {
  1655. p += 1;
  1656. }
  1657. if (*p == '-') {
  1658. sign = true;
  1659. p += 1;
  1660. } else {
  1661. if (*p == '+') {
  1662. p += 1;
  1663. }
  1664. sign = false;
  1665. }
  1666. /*
  1667. * Count the number of digits in the mantissa (including the decimal
  1668. * point), and also locate the decimal point.
  1669. */
  1670. decPt = -1;
  1671. for (mantSize = 0;; mantSize += 1) {
  1672. c = *p;
  1673. if (!IS_DIGIT(c)) {
  1674. if ((c != '.') || (decPt >= 0)) {
  1675. break;
  1676. }
  1677. decPt = mantSize;
  1678. }
  1679. p += 1;
  1680. }
  1681. /*
  1682. * Now suck up the digits in the mantissa. Use two integers to collect 9
  1683. * digits each (this is faster than using floating-point). If the mantissa
  1684. * has more than 18 digits, ignore the extras, since they can't affect the
  1685. * value anyway.
  1686. */
  1687. pExp = p;
  1688. p -= mantSize;
  1689. if (decPt < 0) {
  1690. decPt = mantSize;
  1691. } else {
  1692. mantSize -= 1; /* One of the digits was the point. */
  1693. }
  1694. if (mantSize > 18) {
  1695. fracExp = decPt - 18;
  1696. mantSize = 18;
  1697. } else {
  1698. fracExp = decPt - mantSize;
  1699. }
  1700. if (mantSize == 0) {
  1701. fraction = 0.0;
  1702. p = string;
  1703. goto done;
  1704. } else {
  1705. int frac1, frac2;
  1706. frac1 = 0;
  1707. for (; mantSize > 9; mantSize -= 1) {
  1708. c = *p;
  1709. p += 1;
  1710. if (c == '.') {
  1711. c = *p;
  1712. p += 1;
  1713. }
  1714. frac1 = 10 * frac1 + (c - '0');
  1715. }
  1716. frac2 = 0;
  1717. for (; mantSize > 0; mantSize -= 1) {
  1718. c = *p;
  1719. p += 1;
  1720. if (c == '.') {
  1721. c = *p;
  1722. p += 1;
  1723. }
  1724. frac2 = 10 * frac2 + (c - '0');
  1725. }
  1726. fraction = (1.0e9 * frac1) + frac2;
  1727. }
  1728. /*
  1729. * Skim off the exponent.
  1730. */
  1731. p = pExp;
  1732. if ((*p == 'E') || (*p == 'e')) {
  1733. p += 1;
  1734. if (*p == '-') {
  1735. expSign = true;
  1736. p += 1;
  1737. } else {
  1738. if (*p == '+') {
  1739. p += 1;
  1740. }
  1741. expSign = false;
  1742. }
  1743. if (!IS_DIGIT(CharType(*p))) {
  1744. p = pExp;
  1745. goto done;
  1746. }
  1747. while (IS_DIGIT(CharType(*p))) {
  1748. exp = exp * 10 + (*p - '0');
  1749. p += 1;
  1750. }
  1751. }
  1752. if (expSign) {
  1753. exp = fracExp - exp;
  1754. } else {
  1755. exp = fracExp + exp;
  1756. }
  1757. /*
  1758. * Generate a floating-point number that represents the exponent. Do this
  1759. * by processing the exponent one bit at a time to combine many powers of
  1760. * 2 of 10. Then combine the exponent with the fraction.
  1761. */
  1762. if (exp < 0) {
  1763. expSign = true;
  1764. exp = -exp;
  1765. } else {
  1766. expSign = false;
  1767. }
  1768. if (exp > maxExponent) {
  1769. exp = maxExponent;
  1770. WARN_PRINT("Exponent too high");
  1771. }
  1772. dblExp = 1.0;
  1773. for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
  1774. if (exp & 01) {
  1775. dblExp *= *d;
  1776. }
  1777. }
  1778. if (expSign) {
  1779. fraction /= dblExp;
  1780. } else {
  1781. fraction *= dblExp;
  1782. }
  1783. done:
  1784. if (endPtr != nullptr) {
  1785. *endPtr = (C *)p;
  1786. }
  1787. if (sign) {
  1788. return -fraction;
  1789. }
  1790. return fraction;
  1791. }
  1792. #define READING_SIGN 0
  1793. #define READING_INT 1
  1794. #define READING_DEC 2
  1795. #define READING_EXP 3
  1796. #define READING_DONE 4
  1797. double String::to_double(const char *p_str) {
  1798. #ifndef NO_USE_STDLIB
  1799. return built_in_strtod<char>(p_str);
  1800. #else
  1801. return built_in_strtod<char>(p_str);
  1802. #endif
  1803. }
  1804. float String::to_float() const {
  1805. return to_double();
  1806. }
  1807. double String::to_double(const CharType *p_str, const CharType **r_end) {
  1808. return built_in_strtod<CharType>(p_str, (CharType **)r_end);
  1809. }
  1810. int64_t String::to_int(const CharType *p_str, int p_len) {
  1811. if (p_len == 0 || !p_str[0]) {
  1812. return 0;
  1813. }
  1814. ///@todo make more exact so saving and loading does not lose precision
  1815. int64_t integer = 0;
  1816. int64_t sign = 1;
  1817. int reading = READING_SIGN;
  1818. const CharType *str = p_str;
  1819. const CharType *limit = &p_str[p_len];
  1820. while (*str && reading != READING_DONE && str != limit) {
  1821. CharType c = *(str++);
  1822. switch (reading) {
  1823. case READING_SIGN: {
  1824. if (c >= '0' && c <= '9') {
  1825. reading = READING_INT;
  1826. // let it fallthrough
  1827. } else if (c == '-') {
  1828. sign = -1;
  1829. reading = READING_INT;
  1830. break;
  1831. } else if (c == '+') {
  1832. sign = 1;
  1833. reading = READING_INT;
  1834. break;
  1835. } else {
  1836. break;
  1837. }
  1838. }
  1839. case READING_INT: {
  1840. if (c >= '0' && c <= '9') {
  1841. if (integer > INT64_MAX / 10) {
  1842. String number("");
  1843. str = p_str;
  1844. while (*str && str != limit) {
  1845. number += *(str++);
  1846. }
  1847. 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."));
  1848. }
  1849. integer *= 10;
  1850. integer += c - '0';
  1851. } else {
  1852. reading = READING_DONE;
  1853. }
  1854. } break;
  1855. }
  1856. }
  1857. return sign * integer;
  1858. }
  1859. double String::to_double() const {
  1860. if (empty()) {
  1861. return 0;
  1862. }
  1863. #ifndef NO_USE_STDLIB
  1864. return built_in_strtod<CharType>(c_str());
  1865. //return wcstod(c_str(),NULL); DOES NOT WORK ON ANDROID :(
  1866. #else
  1867. return built_in_strtod<CharType>(c_str());
  1868. #endif
  1869. }
  1870. bool operator==(const char *p_chr, const String &p_str) {
  1871. return p_str == p_chr;
  1872. }
  1873. String operator+(const char *p_chr, const String &p_str) {
  1874. String tmp = p_chr;
  1875. tmp += p_str;
  1876. return tmp;
  1877. }
  1878. String operator+(CharType p_chr, const String &p_str) {
  1879. return (String::chr(p_chr) + p_str);
  1880. }
  1881. uint32_t String::hash(const char *p_cstr) {
  1882. uint32_t hashv = 5381;
  1883. uint32_t c;
  1884. while ((c = *p_cstr++)) {
  1885. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1886. }
  1887. return hashv;
  1888. }
  1889. uint32_t String::hash(const char *p_cstr, int p_len) {
  1890. uint32_t hashv = 5381;
  1891. for (int i = 0; i < p_len; i++) {
  1892. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  1893. }
  1894. return hashv;
  1895. }
  1896. uint32_t String::hash(const CharType *p_cstr, int p_len) {
  1897. uint32_t hashv = 5381;
  1898. for (int i = 0; i < p_len; i++) {
  1899. hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
  1900. }
  1901. return hashv;
  1902. }
  1903. uint32_t String::hash(const CharType *p_cstr) {
  1904. uint32_t hashv = 5381;
  1905. uint32_t c;
  1906. while ((c = *p_cstr++)) {
  1907. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1908. }
  1909. return hashv;
  1910. }
  1911. uint32_t String::hash() const {
  1912. /* simple djb2 hashing */
  1913. const CharType *chr = c_str();
  1914. uint32_t hashv = 5381;
  1915. uint32_t c;
  1916. while ((c = *chr++)) {
  1917. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1918. }
  1919. return hashv;
  1920. }
  1921. uint64_t String::hash64() const {
  1922. /* simple djb2 hashing */
  1923. const CharType *chr = c_str();
  1924. uint64_t hashv = 5381;
  1925. uint64_t c;
  1926. while ((c = *chr++)) {
  1927. hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
  1928. }
  1929. return hashv;
  1930. }
  1931. String String::md5_text() const {
  1932. CharString cs = utf8();
  1933. unsigned char hash[16];
  1934. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  1935. return String::hex_encode_buffer(hash, 16);
  1936. }
  1937. String String::sha1_text() const {
  1938. CharString cs = utf8();
  1939. unsigned char hash[20];
  1940. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  1941. return String::hex_encode_buffer(hash, 20);
  1942. }
  1943. String String::sha256_text() const {
  1944. CharString cs = utf8();
  1945. unsigned char hash[32];
  1946. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  1947. return String::hex_encode_buffer(hash, 32);
  1948. }
  1949. Vector<uint8_t> String::md5_buffer() const {
  1950. CharString cs = utf8();
  1951. unsigned char hash[16];
  1952. CryptoCore::md5((unsigned char *)cs.ptr(), cs.length(), hash);
  1953. Vector<uint8_t> ret;
  1954. ret.resize(16);
  1955. for (int i = 0; i < 16; i++) {
  1956. ret.write[i] = hash[i];
  1957. }
  1958. return ret;
  1959. };
  1960. Vector<uint8_t> String::sha1_buffer() const {
  1961. CharString cs = utf8();
  1962. unsigned char hash[20];
  1963. CryptoCore::sha1((unsigned char *)cs.ptr(), cs.length(), hash);
  1964. Vector<uint8_t> ret;
  1965. ret.resize(20);
  1966. for (int i = 0; i < 20; i++) {
  1967. ret.write[i] = hash[i];
  1968. }
  1969. return ret;
  1970. }
  1971. Vector<uint8_t> String::sha256_buffer() const {
  1972. CharString cs = utf8();
  1973. unsigned char hash[32];
  1974. CryptoCore::sha256((unsigned char *)cs.ptr(), cs.length(), hash);
  1975. Vector<uint8_t> ret;
  1976. ret.resize(32);
  1977. for (int i = 0; i < 32; i++) {
  1978. ret.write[i] = hash[i];
  1979. }
  1980. return ret;
  1981. }
  1982. String String::insert(int p_at_pos, const String &p_string) const {
  1983. if (p_at_pos < 0) {
  1984. return *this;
  1985. }
  1986. if (p_at_pos > length()) {
  1987. p_at_pos = length();
  1988. }
  1989. String pre;
  1990. if (p_at_pos > 0) {
  1991. pre = substr(0, p_at_pos);
  1992. }
  1993. String post;
  1994. if (p_at_pos < length()) {
  1995. post = substr(p_at_pos, length() - p_at_pos);
  1996. }
  1997. return pre + p_string + post;
  1998. }
  1999. String String::substr(int p_from, int p_chars) const {
  2000. if (p_chars == -1) {
  2001. p_chars = length() - p_from;
  2002. }
  2003. if (empty() || p_from < 0 || p_from >= length() || p_chars <= 0) {
  2004. return "";
  2005. }
  2006. if ((p_from + p_chars) > length()) {
  2007. p_chars = length() - p_from;
  2008. }
  2009. if (p_from == 0 && p_chars >= length()) {
  2010. return String(*this);
  2011. }
  2012. String s = String();
  2013. s.copy_from_unchecked(&c_str()[p_from], p_chars);
  2014. return s;
  2015. }
  2016. int String::find_last(const String &p_str) const {
  2017. return rfind(p_str);
  2018. }
  2019. int String::find(const String &p_str, int p_from) const {
  2020. if (p_from < 0) {
  2021. return -1;
  2022. }
  2023. const int src_len = p_str.length();
  2024. const int len = length();
  2025. if (src_len == 0 || len == 0) {
  2026. return -1; // won't find anything!
  2027. }
  2028. const CharType *src = c_str();
  2029. const CharType *str = p_str.c_str();
  2030. for (int i = p_from; i <= (len - src_len); i++) {
  2031. bool found = true;
  2032. for (int j = 0; j < src_len; j++) {
  2033. int read_pos = i + j;
  2034. if (read_pos >= len) {
  2035. ERR_PRINT("read_pos>=len");
  2036. return -1;
  2037. };
  2038. if (src[read_pos] != str[j]) {
  2039. found = false;
  2040. break;
  2041. }
  2042. }
  2043. if (found) {
  2044. return i;
  2045. }
  2046. }
  2047. return -1;
  2048. }
  2049. int String::find(const char *p_str, int p_from) const {
  2050. if (p_from < 0) {
  2051. return -1;
  2052. }
  2053. const int len = length();
  2054. if (len == 0) {
  2055. return -1; // won't find anything!
  2056. }
  2057. const CharType *src = c_str();
  2058. int src_len = 0;
  2059. while (p_str[src_len] != '\0') {
  2060. src_len++;
  2061. }
  2062. if (src_len == 1) {
  2063. const char needle = p_str[0];
  2064. for (int i = p_from; i < len; i++) {
  2065. if (src[i] == needle) {
  2066. return i;
  2067. }
  2068. }
  2069. } else {
  2070. for (int i = p_from; i <= (len - src_len); i++) {
  2071. bool found = true;
  2072. for (int j = 0; j < src_len; j++) {
  2073. int read_pos = i + j;
  2074. if (read_pos >= len) {
  2075. ERR_PRINT("read_pos>=len");
  2076. return -1;
  2077. };
  2078. if (src[read_pos] != p_str[j]) {
  2079. found = false;
  2080. break;
  2081. }
  2082. }
  2083. if (found) {
  2084. return i;
  2085. }
  2086. }
  2087. }
  2088. return -1;
  2089. }
  2090. int String::find_char(const CharType &p_char, int p_from) const {
  2091. return _cowdata.find(p_char, p_from);
  2092. }
  2093. int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
  2094. if (p_from < 0) {
  2095. return -1;
  2096. }
  2097. if (p_keys.size() == 0) {
  2098. return -1;
  2099. }
  2100. //int src_len=p_str.length();
  2101. const String *keys = &p_keys[0];
  2102. int key_count = p_keys.size();
  2103. int len = length();
  2104. if (len == 0) {
  2105. return -1; // won't find anything!
  2106. }
  2107. const CharType *src = c_str();
  2108. for (int i = p_from; i < len; i++) {
  2109. bool found = true;
  2110. for (int k = 0; k < key_count; k++) {
  2111. found = true;
  2112. if (r_key) {
  2113. *r_key = k;
  2114. }
  2115. const CharType *cmp = keys[k].c_str();
  2116. int l = keys[k].length();
  2117. for (int j = 0; j < l; j++) {
  2118. int read_pos = i + j;
  2119. if (read_pos >= len) {
  2120. found = false;
  2121. break;
  2122. };
  2123. if (src[read_pos] != cmp[j]) {
  2124. found = false;
  2125. break;
  2126. }
  2127. }
  2128. if (found) {
  2129. break;
  2130. }
  2131. }
  2132. if (found) {
  2133. return i;
  2134. }
  2135. }
  2136. return -1;
  2137. }
  2138. int String::findn(const String &p_str, int p_from) const {
  2139. if (p_from < 0) {
  2140. return -1;
  2141. }
  2142. int src_len = p_str.length();
  2143. if (src_len == 0 || length() == 0) {
  2144. return -1; // won't find anything!
  2145. }
  2146. const CharType *srcd = c_str();
  2147. for (int i = p_from; i <= (length() - src_len); i++) {
  2148. bool found = true;
  2149. for (int j = 0; j < src_len; j++) {
  2150. int read_pos = i + j;
  2151. if (read_pos >= length()) {
  2152. ERR_PRINT("read_pos>=length()");
  2153. return -1;
  2154. };
  2155. CharType src = _find_lower(srcd[read_pos]);
  2156. CharType dst = _find_lower(p_str[j]);
  2157. if (src != dst) {
  2158. found = false;
  2159. break;
  2160. }
  2161. }
  2162. if (found) {
  2163. return i;
  2164. }
  2165. }
  2166. return -1;
  2167. }
  2168. int String::rfind(const String &p_str, int p_from) const {
  2169. // establish a limit
  2170. int limit = length() - p_str.length();
  2171. if (limit < 0) {
  2172. return -1;
  2173. }
  2174. // establish a starting point
  2175. if (p_from < 0) {
  2176. p_from = limit;
  2177. } else if (p_from > limit) {
  2178. p_from = limit;
  2179. }
  2180. int src_len = p_str.length();
  2181. int len = length();
  2182. if (src_len == 0 || len == 0) {
  2183. return -1; // won't find anything!
  2184. }
  2185. const CharType *src = c_str();
  2186. for (int i = p_from; i >= 0; i--) {
  2187. bool found = true;
  2188. for (int j = 0; j < src_len; j++) {
  2189. int read_pos = i + j;
  2190. if (read_pos >= len) {
  2191. ERR_PRINT("read_pos>=len");
  2192. return -1;
  2193. };
  2194. if (src[read_pos] != p_str[j]) {
  2195. found = false;
  2196. break;
  2197. }
  2198. }
  2199. if (found) {
  2200. return i;
  2201. }
  2202. }
  2203. return -1;
  2204. }
  2205. int String::rfindn(const String &p_str, int p_from) const {
  2206. // establish a limit
  2207. int limit = length() - p_str.length();
  2208. if (limit < 0) {
  2209. return -1;
  2210. }
  2211. // establish a starting point
  2212. if (p_from < 0) {
  2213. p_from = limit;
  2214. } else if (p_from > limit) {
  2215. p_from = limit;
  2216. }
  2217. int src_len = p_str.length();
  2218. int len = length();
  2219. if (src_len == 0 || len == 0) {
  2220. return -1; // won't find anything!
  2221. }
  2222. const CharType *src = c_str();
  2223. for (int i = p_from; i >= 0; i--) {
  2224. bool found = true;
  2225. for (int j = 0; j < src_len; j++) {
  2226. int read_pos = i + j;
  2227. if (read_pos >= len) {
  2228. ERR_PRINT("read_pos>=len");
  2229. return -1;
  2230. };
  2231. CharType srcc = _find_lower(src[read_pos]);
  2232. CharType dstc = _find_lower(p_str[j]);
  2233. if (srcc != dstc) {
  2234. found = false;
  2235. break;
  2236. }
  2237. }
  2238. if (found) {
  2239. return i;
  2240. }
  2241. }
  2242. return -1;
  2243. }
  2244. bool String::ends_with(const String &p_string) const {
  2245. int l = p_string.length();
  2246. if (l > length()) {
  2247. return false;
  2248. }
  2249. if (l == 0) {
  2250. return true;
  2251. }
  2252. const CharType *p = &p_string[0];
  2253. const CharType *s = &operator[](length() - l);
  2254. for (int i = 0; i < l; i++) {
  2255. if (p[i] != s[i]) {
  2256. return false;
  2257. }
  2258. }
  2259. return true;
  2260. }
  2261. bool String::begins_with(const String &p_string) const {
  2262. int l = p_string.length();
  2263. if (l > length()) {
  2264. return false;
  2265. }
  2266. if (l == 0) {
  2267. return true;
  2268. }
  2269. const CharType *p = &p_string[0];
  2270. const CharType *s = &operator[](0);
  2271. for (int i = 0; i < l; i++) {
  2272. if (p[i] != s[i]) {
  2273. return false;
  2274. }
  2275. }
  2276. return true;
  2277. }
  2278. bool String::begins_with(const char *p_string) const {
  2279. int l = length();
  2280. if (l == 0 || !p_string) {
  2281. return false;
  2282. }
  2283. const CharType *str = &operator[](0);
  2284. int i = 0;
  2285. while (*p_string && i < l) {
  2286. if (*p_string != str[i]) {
  2287. return false;
  2288. }
  2289. i++;
  2290. p_string++;
  2291. }
  2292. return *p_string == 0;
  2293. }
  2294. bool String::is_enclosed_in(const String &p_string) const {
  2295. return begins_with(p_string) && ends_with(p_string);
  2296. }
  2297. bool String::is_subsequence_of(const String &p_string) const {
  2298. return _base_is_subsequence_of(p_string, false);
  2299. }
  2300. bool String::is_subsequence_ofi(const String &p_string) const {
  2301. return _base_is_subsequence_of(p_string, true);
  2302. }
  2303. bool String::is_quoted() const {
  2304. return is_enclosed_in("\"") || is_enclosed_in("'");
  2305. }
  2306. int String::_count(const String &p_string, int p_from, int p_to, bool p_case_insensitive) const {
  2307. if (p_string.empty()) {
  2308. return 0;
  2309. }
  2310. int len = length();
  2311. int slen = p_string.length();
  2312. if (len < slen) {
  2313. return 0;
  2314. }
  2315. String str;
  2316. if (p_from >= 0 && p_to >= 0) {
  2317. if (p_to == 0) {
  2318. p_to = len;
  2319. } else if (p_from >= p_to) {
  2320. return 0;
  2321. }
  2322. if (p_from == 0 && p_to == len) {
  2323. str = String();
  2324. str.copy_from_unchecked(&c_str()[0], len);
  2325. } else {
  2326. str = substr(p_from, p_to - p_from);
  2327. }
  2328. } else {
  2329. return 0;
  2330. }
  2331. int c = 0;
  2332. int idx = -1;
  2333. do {
  2334. idx = p_case_insensitive ? str.findn(p_string) : str.find(p_string);
  2335. if (idx != -1) {
  2336. str = str.substr(idx + slen, str.length() - slen);
  2337. ++c;
  2338. }
  2339. } while (idx != -1);
  2340. return c;
  2341. }
  2342. int String::count(const String &p_string, int p_from, int p_to) const {
  2343. return _count(p_string, p_from, p_to, false);
  2344. }
  2345. int String::countn(const String &p_string, int p_from, int p_to) const {
  2346. return _count(p_string, p_from, p_to, true);
  2347. }
  2348. bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const {
  2349. int len = length();
  2350. if (len == 0) {
  2351. // Technically an empty string is subsequence of any string
  2352. return true;
  2353. }
  2354. if (len > p_string.length()) {
  2355. return false;
  2356. }
  2357. const CharType *src = &operator[](0);
  2358. const CharType *tgt = &p_string[0];
  2359. for (; *src && *tgt; tgt++) {
  2360. bool match = false;
  2361. if (case_insensitive) {
  2362. CharType srcc = _find_lower(*src);
  2363. CharType tgtc = _find_lower(*tgt);
  2364. match = srcc == tgtc;
  2365. } else {
  2366. match = *src == *tgt;
  2367. }
  2368. if (match) {
  2369. src++;
  2370. if (!*src) {
  2371. return true;
  2372. }
  2373. }
  2374. }
  2375. return false;
  2376. }
  2377. Vector<String> String::bigrams() const {
  2378. int n_pairs = length() - 1;
  2379. Vector<String> b;
  2380. if (n_pairs <= 0) {
  2381. return b;
  2382. }
  2383. b.resize(n_pairs);
  2384. for (int i = 0; i < n_pairs; i++) {
  2385. b.write[i] = substr(i, 2);
  2386. }
  2387. return b;
  2388. }
  2389. // Similarity according to Sorensen-Dice coefficient
  2390. float String::similarity(const String &p_string) const {
  2391. if (operator==(p_string)) {
  2392. // Equal strings are totally similar
  2393. return 1.0f;
  2394. }
  2395. if (length() < 2 || p_string.length() < 2) {
  2396. // No way to calculate similarity without a single bigram
  2397. return 0.0f;
  2398. }
  2399. Vector<String> src_bigrams = bigrams();
  2400. Vector<String> tgt_bigrams = p_string.bigrams();
  2401. int src_size = src_bigrams.size();
  2402. int tgt_size = tgt_bigrams.size();
  2403. float sum = src_size + tgt_size;
  2404. float inter = 0;
  2405. for (int i = 0; i < src_size; i++) {
  2406. for (int j = 0; j < tgt_size; j++) {
  2407. if (src_bigrams[i] == tgt_bigrams[j]) {
  2408. inter++;
  2409. break;
  2410. }
  2411. }
  2412. }
  2413. return (2.0f * inter) / sum;
  2414. }
  2415. static bool _wildcard_match(const CharType *p_pattern, const CharType *p_string, bool p_case_sensitive) {
  2416. switch (*p_pattern) {
  2417. case '\0':
  2418. return !*p_string;
  2419. case '*':
  2420. return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive));
  2421. case '?':
  2422. return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
  2423. default:
  2424. 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);
  2425. }
  2426. }
  2427. bool String::match(const String &p_wildcard) const {
  2428. if (!p_wildcard.length() || !length()) {
  2429. return false;
  2430. }
  2431. return _wildcard_match(p_wildcard.c_str(), c_str(), true);
  2432. }
  2433. bool String::matchn(const String &p_wildcard) const {
  2434. if (!p_wildcard.length() || !length()) {
  2435. return false;
  2436. }
  2437. return _wildcard_match(p_wildcard.c_str(), c_str(), false);
  2438. }
  2439. String String::format(const Variant &values, String placeholder) const {
  2440. String new_string = String(this->ptr());
  2441. if (values.get_type() == Variant::ARRAY) {
  2442. Array values_arr = values;
  2443. for (int i = 0; i < values_arr.size(); i++) {
  2444. String i_as_str = String::num_int64(i);
  2445. if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
  2446. Array value_arr = values_arr[i];
  2447. if (value_arr.size() == 2) {
  2448. Variant v_key = value_arr[0];
  2449. String key = v_key;
  2450. Variant v_val = value_arr[1];
  2451. String val = v_val;
  2452. new_string = new_string.replace(placeholder.replace("_", key), val);
  2453. } else {
  2454. ERR_PRINT(String("STRING.format Inner Array size != 2 ").ascii().get_data());
  2455. }
  2456. } else { //Array structure ["RobotGuy","Logis","rookie"]
  2457. Variant v_val = values_arr[i];
  2458. String val = v_val;
  2459. if (placeholder.find("_") > -1) {
  2460. new_string = new_string.replace(placeholder.replace("_", i_as_str), val);
  2461. } else {
  2462. new_string = new_string.replace_first(placeholder, val);
  2463. }
  2464. }
  2465. }
  2466. } else if (values.get_type() == Variant::DICTIONARY) {
  2467. Dictionary d = values;
  2468. List<Variant> keys;
  2469. d.get_key_list(&keys);
  2470. for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
  2471. String key = E->get();
  2472. String val = d[E->get()];
  2473. new_string = new_string.replace(placeholder.replace("_", key), val);
  2474. }
  2475. } else {
  2476. ERR_PRINT(String("Invalid type: use Array or Dictionary.").ascii().get_data());
  2477. }
  2478. return new_string;
  2479. }
  2480. String String::replace(const String &p_key, const String &p_with) const {
  2481. String new_string;
  2482. int search_from = 0;
  2483. int result = 0;
  2484. while ((result = find(p_key, search_from)) >= 0) {
  2485. new_string += substr(search_from, result - search_from);
  2486. new_string += p_with;
  2487. search_from = result + p_key.length();
  2488. }
  2489. if (search_from == 0) {
  2490. return *this;
  2491. }
  2492. new_string += substr(search_from, length() - search_from);
  2493. return new_string;
  2494. }
  2495. String String::replace(const char *p_key, const char *p_with) const {
  2496. String new_string;
  2497. int search_from = 0;
  2498. int result = 0;
  2499. while ((result = find(p_key, search_from)) >= 0) {
  2500. new_string += substr(search_from, result - search_from);
  2501. new_string += p_with;
  2502. int k = 0;
  2503. while (p_key[k] != '\0') {
  2504. k++;
  2505. }
  2506. search_from = result + k;
  2507. }
  2508. if (search_from == 0) {
  2509. return *this;
  2510. }
  2511. new_string += substr(search_from, length() - search_from);
  2512. return new_string;
  2513. }
  2514. String String::replace_first(const String &p_key, const String &p_with) const {
  2515. int pos = find(p_key);
  2516. if (pos >= 0) {
  2517. return substr(0, pos) + p_with + substr(pos + p_key.length(), length());
  2518. }
  2519. return *this;
  2520. }
  2521. String String::replacen(const String &p_key, const String &p_with) const {
  2522. String new_string;
  2523. int search_from = 0;
  2524. int result = 0;
  2525. while ((result = findn(p_key, search_from)) >= 0) {
  2526. new_string += substr(search_from, result - search_from);
  2527. new_string += p_with;
  2528. search_from = result + p_key.length();
  2529. }
  2530. if (search_from == 0) {
  2531. return *this;
  2532. }
  2533. new_string += substr(search_from, length() - search_from);
  2534. return new_string;
  2535. }
  2536. String String::repeat(int p_count) const {
  2537. ERR_FAIL_COND_V_MSG(p_count < 0, "", "Parameter count should be a positive number.");
  2538. String new_string;
  2539. const CharType *src = this->c_str();
  2540. new_string.resize(length() * p_count + 1);
  2541. new_string[length() * p_count] = 0;
  2542. for (int i = 0; i < p_count; i++) {
  2543. for (int j = 0; j < length(); j++) {
  2544. new_string[i * length() + j] = src[j];
  2545. }
  2546. }
  2547. return new_string;
  2548. }
  2549. String String::left(int p_pos) const {
  2550. if (p_pos <= 0) {
  2551. return "";
  2552. }
  2553. if (p_pos >= length()) {
  2554. return *this;
  2555. }
  2556. return substr(0, p_pos);
  2557. }
  2558. String String::right(int p_pos) const {
  2559. if (p_pos >= length()) {
  2560. return "";
  2561. }
  2562. if (p_pos <= 0) {
  2563. return *this;
  2564. }
  2565. return substr(p_pos, (length() - p_pos));
  2566. }
  2567. CharType String::ord_at(int p_idx) const {
  2568. ERR_FAIL_INDEX_V(p_idx, length(), 0);
  2569. return operator[](p_idx);
  2570. }
  2571. String String::indent(const String &p_prefix) const {
  2572. String new_string;
  2573. int line_start = 0;
  2574. for (int i = 0; i < length(); i++) {
  2575. const char32_t c = operator[](i);
  2576. if (c == '\n') {
  2577. if (i == line_start) {
  2578. new_string += c; // Leave empty lines empty.
  2579. } else {
  2580. new_string += p_prefix + substr(line_start, i - line_start + 1);
  2581. }
  2582. line_start = i + 1;
  2583. }
  2584. }
  2585. if (line_start != length()) {
  2586. new_string += p_prefix + substr(line_start);
  2587. }
  2588. return new_string;
  2589. }
  2590. String String::dedent() const {
  2591. String new_string;
  2592. String indent;
  2593. bool has_indent = false;
  2594. bool has_text = false;
  2595. int line_start = 0;
  2596. int indent_stop = -1;
  2597. for (int i = 0; i < length(); i++) {
  2598. CharType c = operator[](i);
  2599. if (c == '\n') {
  2600. if (has_text) {
  2601. new_string += substr(indent_stop, i - indent_stop);
  2602. }
  2603. new_string += "\n";
  2604. has_text = false;
  2605. line_start = i + 1;
  2606. indent_stop = -1;
  2607. } else if (!has_text) {
  2608. if (c > 32) {
  2609. has_text = true;
  2610. if (!has_indent) {
  2611. has_indent = true;
  2612. indent = substr(line_start, i - line_start);
  2613. indent_stop = i;
  2614. }
  2615. }
  2616. if (has_indent && indent_stop < 0) {
  2617. int j = i - line_start;
  2618. if (j >= indent.length() || c != indent[j]) {
  2619. indent_stop = i;
  2620. }
  2621. }
  2622. }
  2623. }
  2624. if (has_text) {
  2625. new_string += substr(indent_stop, length() - indent_stop);
  2626. }
  2627. return new_string;
  2628. }
  2629. String String::strip_edges(bool left, bool right) const {
  2630. int len = length();
  2631. int beg = 0, end = len;
  2632. if (left) {
  2633. for (int i = 0; i < len; i++) {
  2634. if (operator[](i) <= 32) {
  2635. beg++;
  2636. } else {
  2637. break;
  2638. }
  2639. }
  2640. }
  2641. if (right) {
  2642. for (int i = (int)(len - 1); i >= 0; i--) {
  2643. if (operator[](i) <= 32) {
  2644. end--;
  2645. } else {
  2646. break;
  2647. }
  2648. }
  2649. }
  2650. if (beg == 0 && end == len) {
  2651. return *this;
  2652. }
  2653. return substr(beg, end - beg);
  2654. }
  2655. String String::strip_escapes() const {
  2656. String new_string;
  2657. for (int i = 0; i < length(); i++) {
  2658. // Escape characters on first page of the ASCII table, before 32 (Space).
  2659. if (operator[](i) < 32) {
  2660. continue;
  2661. }
  2662. new_string += operator[](i);
  2663. }
  2664. return new_string;
  2665. }
  2666. String String::lstrip(const String &p_chars) const {
  2667. int len = length();
  2668. int beg;
  2669. for (beg = 0; beg < len; beg++) {
  2670. if (p_chars.find_char(get(beg)) == -1) {
  2671. break;
  2672. }
  2673. }
  2674. if (beg == 0) {
  2675. return *this;
  2676. }
  2677. return substr(beg, len - beg);
  2678. }
  2679. String String::rstrip(const String &p_chars) const {
  2680. int len = length();
  2681. int end;
  2682. for (end = len - 1; end >= 0; end--) {
  2683. if (p_chars.find_char(get(end)) == -1) {
  2684. break;
  2685. }
  2686. }
  2687. if (end == len - 1) {
  2688. return *this;
  2689. }
  2690. return substr(0, end + 1);
  2691. }
  2692. bool String::is_network_share_path() const {
  2693. return begins_with("//") || begins_with("\\\\");
  2694. }
  2695. String String::simplify_path() const {
  2696. String s = *this;
  2697. String drive;
  2698. if (s.begins_with("local://")) {
  2699. drive = "local://";
  2700. s = s.substr(8, s.length());
  2701. } else if (s.begins_with("res://")) {
  2702. drive = "res://";
  2703. s = s.substr(6, s.length());
  2704. } else if (s.begins_with("user://")) {
  2705. drive = "user://";
  2706. s = s.substr(7, s.length());
  2707. } else if (is_network_share_path()) {
  2708. drive = s.substr(0, 2);
  2709. s = s.substr(2, s.length() - 2);
  2710. } else if (s.begins_with("/") || s.begins_with("\\")) {
  2711. drive = s.substr(0, 1);
  2712. s = s.substr(1, s.length() - 1);
  2713. } else {
  2714. int p = s.find(":/");
  2715. if (p == -1) {
  2716. p = s.find(":\\");
  2717. }
  2718. if (p != -1 && p < s.find("/")) {
  2719. drive = s.substr(0, p + 2);
  2720. s = s.substr(p + 2, s.length());
  2721. }
  2722. }
  2723. s = s.replace("\\", "/");
  2724. while (true) { // in case of using 2 or more slash
  2725. String compare = s.replace("//", "/");
  2726. if (s == compare) {
  2727. break;
  2728. } else {
  2729. s = compare;
  2730. }
  2731. }
  2732. Vector<String> dirs = s.split("/", false);
  2733. for (int i = 0; i < dirs.size(); i++) {
  2734. String d = dirs[i];
  2735. if (d == ".") {
  2736. dirs.remove(i);
  2737. i--;
  2738. } else if (d == "..") {
  2739. if (i == 0) {
  2740. dirs.remove(i);
  2741. i--;
  2742. } else {
  2743. dirs.remove(i);
  2744. dirs.remove(i - 1);
  2745. i -= 2;
  2746. }
  2747. }
  2748. }
  2749. s = "";
  2750. for (int i = 0; i < dirs.size(); i++) {
  2751. if (i > 0) {
  2752. s += "/";
  2753. }
  2754. s += dirs[i];
  2755. }
  2756. return drive + s;
  2757. }
  2758. static int _humanize_digits(int p_num) {
  2759. if (p_num < 100) {
  2760. return 2;
  2761. } else if (p_num < 1024) {
  2762. return 1;
  2763. } else {
  2764. return 0;
  2765. }
  2766. }
  2767. String String::humanize_size(uint64_t p_size) {
  2768. uint64_t _div = 1;
  2769. Vector<String> prefixes;
  2770. prefixes.push_back(RTR("B"));
  2771. prefixes.push_back(RTR("KiB"));
  2772. prefixes.push_back(RTR("MiB"));
  2773. prefixes.push_back(RTR("GiB"));
  2774. prefixes.push_back(RTR("TiB"));
  2775. prefixes.push_back(RTR("PiB"));
  2776. prefixes.push_back(RTR("EiB"));
  2777. int prefix_idx = 0;
  2778. while (prefix_idx < prefixes.size() - 1 && p_size > (_div * 1024)) {
  2779. _div *= 1024;
  2780. prefix_idx++;
  2781. }
  2782. const int digits = prefix_idx > 0 ? _humanize_digits(p_size / _div) : 0;
  2783. const double divisor = prefix_idx > 0 ? _div : 1;
  2784. return String::num(p_size / divisor).pad_decimals(digits) + " " + prefixes[prefix_idx];
  2785. }
  2786. bool String::is_abs_path() const {
  2787. if (length() > 1) {
  2788. return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
  2789. } else if ((length()) == 1) {
  2790. return (operator[](0) == '/' || operator[](0) == '\\');
  2791. } else {
  2792. return false;
  2793. }
  2794. }
  2795. static _FORCE_INLINE_ bool _is_valid_identifier_bit(int p_index, CharType p_char) {
  2796. if (p_index == 0 && p_char >= '0' && p_char <= '9') {
  2797. return false; // No start with number plz.
  2798. }
  2799. return (p_char >= '0' && p_char <= '9') || (p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z') || p_char == '_';
  2800. }
  2801. String String::validate_identifier() const {
  2802. if (empty()) {
  2803. return "_"; // Empty string is not a valid identifier.
  2804. }
  2805. String result = *this;
  2806. int len = result.length();
  2807. wchar_t *buffer = result.ptrw();
  2808. for (int i = 0; i < len; i++) {
  2809. if (!_is_valid_identifier_bit(i, buffer[i])) {
  2810. buffer[i] = '_';
  2811. }
  2812. }
  2813. return result;
  2814. }
  2815. bool String::is_valid_identifier() const {
  2816. int len = length();
  2817. if (len == 0) {
  2818. return false;
  2819. }
  2820. const wchar_t *str = &operator[](0);
  2821. for (int i = 0; i < len; i++) {
  2822. if (!_is_valid_identifier_bit(i, str[i])) {
  2823. return false;
  2824. }
  2825. }
  2826. return true;
  2827. }
  2828. //kind of poor should be rewritten properly
  2829. String String::word_wrap(int p_chars_per_line) const {
  2830. int from = 0;
  2831. int last_space = 0;
  2832. String ret;
  2833. for (int i = 0; i < length(); i++) {
  2834. if (i - from >= p_chars_per_line) {
  2835. if (last_space == -1) {
  2836. ret += substr(from, i - from + 1) + "\n";
  2837. } else {
  2838. ret += substr(from, last_space - from) + "\n";
  2839. i = last_space; //rewind
  2840. }
  2841. from = i + 1;
  2842. last_space = -1;
  2843. } else if (operator[](i) == ' ' || operator[](i) == '\t') {
  2844. last_space = i;
  2845. } else if (operator[](i) == '\n') {
  2846. ret += substr(from, i - from) + "\n";
  2847. from = i + 1;
  2848. last_space = -1;
  2849. }
  2850. }
  2851. if (from < length()) {
  2852. ret += substr(from, length());
  2853. }
  2854. return ret;
  2855. }
  2856. String String::http_escape() const {
  2857. const CharString temp = utf8();
  2858. String res;
  2859. for (int i = 0; i < temp.length(); ++i) {
  2860. uint8_t ord = temp[i];
  2861. if (ord == '.' || ord == '-' || ord == '_' || ord == '~' ||
  2862. (ord >= 'a' && ord <= 'z') ||
  2863. (ord >= 'A' && ord <= 'Z') ||
  2864. (ord >= '0' && ord <= '9')) {
  2865. res += ord;
  2866. } else {
  2867. char p[4] = { '%', 0, 0, 0 };
  2868. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  2869. p[1] = hex[ord >> 4];
  2870. p[2] = hex[ord & 0xF];
  2871. res += p;
  2872. }
  2873. }
  2874. return res;
  2875. }
  2876. String String::http_unescape() const {
  2877. String res;
  2878. for (int i = 0; i < length(); ++i) {
  2879. if (ord_at(i) == '%' && i + 2 < length()) {
  2880. CharType ord1 = ord_at(i + 1);
  2881. if ((ord1 >= '0' && ord1 <= '9') || (ord1 >= 'A' && ord1 <= 'Z')) {
  2882. CharType ord2 = ord_at(i + 2);
  2883. if ((ord2 >= '0' && ord2 <= '9') || (ord2 >= 'A' && ord2 <= 'Z')) {
  2884. char bytes[3] = { (char)ord1, (char)ord2, 0 };
  2885. res += (char)strtol(bytes, nullptr, 16);
  2886. i += 2;
  2887. }
  2888. } else {
  2889. res += ord_at(i);
  2890. }
  2891. } else {
  2892. res += ord_at(i);
  2893. }
  2894. }
  2895. return String::utf8(res.ascii());
  2896. }
  2897. String String::c_unescape() const {
  2898. String escaped = *this;
  2899. escaped = escaped.replace("\\a", "\a");
  2900. escaped = escaped.replace("\\b", "\b");
  2901. escaped = escaped.replace("\\f", "\f");
  2902. escaped = escaped.replace("\\n", "\n");
  2903. escaped = escaped.replace("\\r", "\r");
  2904. escaped = escaped.replace("\\t", "\t");
  2905. escaped = escaped.replace("\\v", "\v");
  2906. escaped = escaped.replace("\\'", "\'");
  2907. escaped = escaped.replace("\\\"", "\"");
  2908. escaped = escaped.replace("\\?", "\?");
  2909. escaped = escaped.replace("\\\\", "\\");
  2910. return escaped;
  2911. }
  2912. String String::c_escape() const {
  2913. String escaped = *this;
  2914. escaped = escaped.replace("\\", "\\\\");
  2915. escaped = escaped.replace("\a", "\\a");
  2916. escaped = escaped.replace("\b", "\\b");
  2917. escaped = escaped.replace("\f", "\\f");
  2918. escaped = escaped.replace("\n", "\\n");
  2919. escaped = escaped.replace("\r", "\\r");
  2920. escaped = escaped.replace("\t", "\\t");
  2921. escaped = escaped.replace("\v", "\\v");
  2922. escaped = escaped.replace("\'", "\\'");
  2923. escaped = escaped.replace("\?", "\\?");
  2924. escaped = escaped.replace("\"", "\\\"");
  2925. return escaped;
  2926. }
  2927. String String::c_escape_multiline() const {
  2928. String escaped = *this;
  2929. escaped = escaped.replace("\\", "\\\\");
  2930. escaped = escaped.replace("\"", "\\\"");
  2931. return escaped;
  2932. }
  2933. String String::json_escape() const {
  2934. String escaped = *this;
  2935. escaped = escaped.replace("\\", "\\\\");
  2936. escaped = escaped.replace("\b", "\\b");
  2937. escaped = escaped.replace("\f", "\\f");
  2938. escaped = escaped.replace("\n", "\\n");
  2939. escaped = escaped.replace("\r", "\\r");
  2940. escaped = escaped.replace("\t", "\\t");
  2941. escaped = escaped.replace("\v", "\\v");
  2942. escaped = escaped.replace("\"", "\\\"");
  2943. return escaped;
  2944. }
  2945. String String::xml_escape(bool p_escape_quotes) const {
  2946. String str = *this;
  2947. str = str.replace("&", "&amp;");
  2948. str = str.replace("<", "&lt;");
  2949. str = str.replace(">", "&gt;");
  2950. if (p_escape_quotes) {
  2951. str = str.replace("'", "&apos;");
  2952. str = str.replace("\"", "&quot;");
  2953. }
  2954. /*
  2955. for (int i=1;i<32;i++) {
  2956. char chr[2]={i,0};
  2957. str=str.replace(chr,"&#"+String::num(i)+";");
  2958. }*/
  2959. return str;
  2960. }
  2961. static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src, int p_src_len, CharType *p_dst) {
  2962. int len = 0;
  2963. while (p_src_len) {
  2964. if (*p_src == '&') {
  2965. int eat = 0;
  2966. if (p_src_len >= 4 && p_src[1] == '#') {
  2967. CharType c = 0;
  2968. bool overflow = false;
  2969. if (p_src[2] == 'x') {
  2970. // Hex entity &#x<num>;
  2971. for (int i = 3; i < p_src_len; i++) {
  2972. eat = i + 1;
  2973. CharType ct = p_src[i];
  2974. if (ct == ';') {
  2975. break;
  2976. } else if (ct >= '0' && ct <= '9') {
  2977. ct = ct - '0';
  2978. } else if (ct >= 'a' && ct <= 'f') {
  2979. ct = (ct - 'a') + 10;
  2980. } else if (ct >= 'A' && ct <= 'F') {
  2981. ct = (ct - 'A') + 10;
  2982. } else {
  2983. break;
  2984. }
  2985. if (c > (WCHAR_MAX >> 4)) {
  2986. overflow = true;
  2987. break;
  2988. }
  2989. c <<= 4;
  2990. c |= ct;
  2991. }
  2992. } else {
  2993. // Decimal entity &#<num>;
  2994. for (int i = 2; i < p_src_len; i++) {
  2995. eat = i + 1;
  2996. CharType ct = p_src[i];
  2997. if (ct == ';' || ct < '0' || ct > '9') {
  2998. break;
  2999. }
  3000. }
  3001. if (p_src[eat - 1] == ';') {
  3002. int64_t val = String::to_int(p_src + 2, eat - 3);
  3003. if (val > 0 && val <= WCHAR_MAX) {
  3004. c = (CharType)val;
  3005. } else {
  3006. overflow = true;
  3007. }
  3008. }
  3009. }
  3010. // Value must be non-zero, in the range of char32_t,
  3011. // actually end with ';'. If invalid, leave the entity as-is
  3012. if (c == '\0' || overflow || p_src[eat - 1] != ';') {
  3013. eat = 1;
  3014. c = *p_src;
  3015. }
  3016. if (p_dst) {
  3017. *p_dst = c;
  3018. }
  3019. } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') {
  3020. if (p_dst) {
  3021. *p_dst = '>';
  3022. }
  3023. eat = 4;
  3024. } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') {
  3025. if (p_dst) {
  3026. *p_dst = '<';
  3027. }
  3028. eat = 4;
  3029. } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') {
  3030. if (p_dst) {
  3031. *p_dst = '&';
  3032. }
  3033. eat = 5;
  3034. } 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] == ';') {
  3035. if (p_dst) {
  3036. *p_dst = '"';
  3037. }
  3038. eat = 6;
  3039. } 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] == ';') {
  3040. if (p_dst) {
  3041. *p_dst = '\'';
  3042. }
  3043. eat = 6;
  3044. } else {
  3045. if (p_dst) {
  3046. *p_dst = *p_src;
  3047. }
  3048. eat = 1;
  3049. }
  3050. if (p_dst) {
  3051. p_dst++;
  3052. }
  3053. len++;
  3054. p_src += eat;
  3055. p_src_len -= eat;
  3056. } else {
  3057. if (p_dst) {
  3058. *p_dst = *p_src;
  3059. p_dst++;
  3060. }
  3061. len++;
  3062. p_src++;
  3063. p_src_len--;
  3064. }
  3065. }
  3066. return len;
  3067. }
  3068. String String::xml_unescape() const {
  3069. String str;
  3070. int l = length();
  3071. int len = _xml_unescape(c_str(), l, nullptr);
  3072. if (len == 0) {
  3073. return String();
  3074. }
  3075. str.resize(len + 1);
  3076. _xml_unescape(c_str(), l, str.ptrw());
  3077. str[len] = 0;
  3078. return str;
  3079. }
  3080. String String::pad_decimals(int p_digits) const {
  3081. String s = *this;
  3082. int c = s.find(".");
  3083. if (c == -1) {
  3084. if (p_digits <= 0) {
  3085. return s;
  3086. }
  3087. s += ".";
  3088. c = s.length() - 1;
  3089. } else {
  3090. if (p_digits <= 0) {
  3091. return s.substr(0, c);
  3092. }
  3093. }
  3094. if (s.length() - (c + 1) > p_digits) {
  3095. s = s.substr(0, c + p_digits + 1);
  3096. } else {
  3097. while (s.length() - (c + 1) < p_digits) {
  3098. s += "0";
  3099. }
  3100. }
  3101. return s;
  3102. }
  3103. String String::pad_zeros(int p_digits) const {
  3104. String s = *this;
  3105. int end = s.find(".");
  3106. if (end == -1) {
  3107. end = s.length();
  3108. }
  3109. if (end == 0) {
  3110. return s;
  3111. }
  3112. int begin = 0;
  3113. while (begin < end && (s[begin] < '0' || s[begin] > '9')) {
  3114. begin++;
  3115. }
  3116. if (begin >= end) {
  3117. return s;
  3118. }
  3119. while (end - begin < p_digits) {
  3120. s = s.insert(begin, "0");
  3121. end++;
  3122. }
  3123. return s;
  3124. }
  3125. String String::trim_prefix(const String &p_prefix) const {
  3126. String s = *this;
  3127. if (s.begins_with(p_prefix)) {
  3128. return s.substr(p_prefix.length(), s.length() - p_prefix.length());
  3129. }
  3130. return s;
  3131. }
  3132. String String::trim_suffix(const String &p_suffix) const {
  3133. String s = *this;
  3134. if (s.ends_with(p_suffix)) {
  3135. return s.substr(0, s.length() - p_suffix.length());
  3136. }
  3137. return s;
  3138. }
  3139. bool String::is_valid_integer() const {
  3140. int len = length();
  3141. if (len == 0) {
  3142. return false;
  3143. }
  3144. int from = 0;
  3145. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  3146. from++;
  3147. }
  3148. for (int i = from; i < len; i++) {
  3149. if (operator[](i) < '0' || operator[](i) > '9') {
  3150. return false; // no start with number plz
  3151. }
  3152. }
  3153. return true;
  3154. }
  3155. bool String::is_valid_hex_number(bool p_with_prefix) const {
  3156. int len = length();
  3157. if (len == 0) {
  3158. return false;
  3159. }
  3160. int from = 0;
  3161. if (len != 1 && (operator[](0) == '+' || operator[](0) == '-')) {
  3162. from++;
  3163. }
  3164. if (p_with_prefix) {
  3165. if (len < 3) {
  3166. return false;
  3167. }
  3168. if (operator[](from) != '0' || operator[](from + 1) != 'x') {
  3169. return false;
  3170. }
  3171. from += 2;
  3172. }
  3173. for (int i = from; i < len; i++) {
  3174. CharType c = operator[](i);
  3175. if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
  3176. continue;
  3177. }
  3178. return false;
  3179. }
  3180. return true;
  3181. };
  3182. bool String::is_valid_float() const {
  3183. int len = length();
  3184. if (len == 0) {
  3185. return false;
  3186. }
  3187. int from = 0;
  3188. if (operator[](0) == '+' || operator[](0) == '-') {
  3189. from++;
  3190. }
  3191. bool exponent_found = false;
  3192. bool period_found = false;
  3193. bool sign_found = false;
  3194. bool exponent_values_found = false;
  3195. bool numbers_found = false;
  3196. for (int i = from; i < len; i++) {
  3197. if (operator[](i) >= '0' && operator[](i) <= '9') {
  3198. if (exponent_found) {
  3199. exponent_values_found = true;
  3200. } else {
  3201. numbers_found = true;
  3202. }
  3203. } else if (numbers_found && !exponent_found && operator[](i) == 'e') {
  3204. exponent_found = true;
  3205. } else if (!period_found && !exponent_found && operator[](i) == '.') {
  3206. period_found = true;
  3207. } else if ((operator[](i) == '-' || operator[](i) == '+') && exponent_found && !exponent_values_found && !sign_found) {
  3208. sign_found = true;
  3209. } else {
  3210. return false; // no start with number plz
  3211. }
  3212. }
  3213. return numbers_found;
  3214. }
  3215. String String::path_to_file(const String &p_path) const {
  3216. // Don't get base dir for src, this is expected to be a dir already.
  3217. String src = this->replace("\\", "/");
  3218. String dst = p_path.replace("\\", "/").get_base_dir();
  3219. String rel = src.path_to(dst);
  3220. if (rel == dst) { // failed
  3221. return p_path;
  3222. } else {
  3223. return rel + p_path.get_file();
  3224. }
  3225. }
  3226. String String::path_to(const String &p_path) const {
  3227. String src = this->replace("\\", "/");
  3228. String dst = p_path.replace("\\", "/");
  3229. if (!src.ends_with("/")) {
  3230. src += "/";
  3231. }
  3232. if (!dst.ends_with("/")) {
  3233. dst += "/";
  3234. }
  3235. String base;
  3236. if (src.begins_with("res://") && dst.begins_with("res://")) {
  3237. base = "res:/";
  3238. src = src.replace("res://", "/");
  3239. dst = dst.replace("res://", "/");
  3240. } else if (src.begins_with("user://") && dst.begins_with("user://")) {
  3241. base = "user:/";
  3242. src = src.replace("user://", "/");
  3243. dst = dst.replace("user://", "/");
  3244. } else if (src.begins_with("/") && dst.begins_with("/")) {
  3245. //nothing
  3246. } else {
  3247. //dos style
  3248. String src_begin = src.get_slicec('/', 0);
  3249. String dst_begin = dst.get_slicec('/', 0);
  3250. if (src_begin != dst_begin) {
  3251. return p_path; //impossible to do this
  3252. }
  3253. base = src_begin;
  3254. src = src.substr(src_begin.length(), src.length());
  3255. dst = dst.substr(dst_begin.length(), dst.length());
  3256. }
  3257. //remove leading and trailing slash and split
  3258. Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/");
  3259. Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/");
  3260. //find common parent
  3261. int common_parent = 0;
  3262. while (true) {
  3263. if (src_dirs.size() == common_parent) {
  3264. break;
  3265. }
  3266. if (dst_dirs.size() == common_parent) {
  3267. break;
  3268. }
  3269. if (src_dirs[common_parent] != dst_dirs[common_parent]) {
  3270. break;
  3271. }
  3272. common_parent++;
  3273. }
  3274. common_parent--;
  3275. String dir;
  3276. for (int i = src_dirs.size() - 1; i > common_parent; i--) {
  3277. dir += "../";
  3278. }
  3279. for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
  3280. dir += dst_dirs[i] + "/";
  3281. }
  3282. if (dir.length() == 0) {
  3283. dir = "./";
  3284. }
  3285. return dir;
  3286. }
  3287. bool String::is_valid_html_color() const {
  3288. return Color::html_is_valid(*this);
  3289. }
  3290. bool String::is_valid_filename() const {
  3291. String stripped = strip_edges();
  3292. if (*this != stripped) {
  3293. return false;
  3294. }
  3295. if (stripped == String()) {
  3296. return false;
  3297. }
  3298. return !(find(":") != -1 || find("/") != -1 || find("\\") != -1 || find("?") != -1 || find("*") != -1 || find("\"") != -1 || find("|") != -1 || find("%") != -1 || find("<") != -1 || find(">") != -1);
  3299. }
  3300. bool String::is_valid_ip_address() const {
  3301. if (find(":") >= 0) {
  3302. Vector<String> ip = split(":");
  3303. for (int i = 0; i < ip.size(); i++) {
  3304. String n = ip[i];
  3305. if (n.empty()) {
  3306. continue;
  3307. }
  3308. if (n.is_valid_hex_number(false)) {
  3309. int nint = n.hex_to_int(false);
  3310. if (nint < 0 || nint > 0xffff) {
  3311. return false;
  3312. }
  3313. continue;
  3314. };
  3315. if (!n.is_valid_ip_address()) {
  3316. return false;
  3317. }
  3318. };
  3319. } else {
  3320. Vector<String> ip = split(".");
  3321. if (ip.size() != 4) {
  3322. return false;
  3323. }
  3324. for (int i = 0; i < ip.size(); i++) {
  3325. String n = ip[i];
  3326. if (!n.is_valid_integer()) {
  3327. return false;
  3328. }
  3329. int val = n.to_int();
  3330. if (val < 0 || val > 255) {
  3331. return false;
  3332. }
  3333. }
  3334. };
  3335. return true;
  3336. }
  3337. bool String::is_resource_file() const {
  3338. return begins_with("res://") && find("::") == -1;
  3339. }
  3340. bool String::is_rel_path() const {
  3341. return !is_abs_path();
  3342. }
  3343. String String::get_base_dir() const {
  3344. int end = 0;
  3345. // URL scheme style base.
  3346. int basepos = find("://");
  3347. if (basepos != -1) {
  3348. end = basepos + 3;
  3349. }
  3350. // Windows top level directory base.
  3351. if (end == 0) {
  3352. basepos = find(":/");
  3353. if (basepos == -1) {
  3354. basepos = find(":\\");
  3355. }
  3356. if (basepos != -1) {
  3357. end = basepos + 2;
  3358. }
  3359. }
  3360. // Windows UNC network share path.
  3361. if (end == 0) {
  3362. if (is_network_share_path()) {
  3363. basepos = find("/", 2);
  3364. if (basepos == -1) {
  3365. basepos = find("\\", 2);
  3366. }
  3367. int servpos = find("/", basepos + 1);
  3368. if (servpos == -1) {
  3369. servpos = find("\\", basepos + 1);
  3370. }
  3371. if (servpos != -1) {
  3372. end = servpos + 1;
  3373. }
  3374. }
  3375. }
  3376. // Unix root directory base.
  3377. if (end == 0) {
  3378. if (begins_with("/")) {
  3379. end = 1;
  3380. }
  3381. }
  3382. String rs;
  3383. String base;
  3384. if (end != 0) {
  3385. rs = substr(end, length());
  3386. base = substr(0, end);
  3387. } else {
  3388. rs = *this;
  3389. }
  3390. int sep = MAX(rs.rfind("/"), rs.rfind("\\"));
  3391. if (sep == -1) {
  3392. return base;
  3393. }
  3394. return base + rs.substr(0, sep);
  3395. }
  3396. String String::get_file() const {
  3397. int sep = MAX(rfind("/"), rfind("\\"));
  3398. if (sep == -1) {
  3399. return *this;
  3400. }
  3401. return substr(sep + 1, length());
  3402. }
  3403. String String::get_extension() const {
  3404. int pos = rfind(".");
  3405. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  3406. return "";
  3407. }
  3408. return substr(pos + 1, length());
  3409. }
  3410. String String::plus_file(const String &p_file) const {
  3411. if (empty()) {
  3412. return p_file;
  3413. }
  3414. if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/')) {
  3415. return *this + p_file;
  3416. }
  3417. return *this + "/" + p_file;
  3418. }
  3419. String String::percent_encode() const {
  3420. CharString cs = utf8();
  3421. String encoded;
  3422. for (int i = 0; i < cs.length(); i++) {
  3423. uint8_t c = cs[i];
  3424. if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '~' || c == '.') {
  3425. char p[2] = { (char)c, 0 };
  3426. encoded += p;
  3427. } else {
  3428. char p[4] = { '%', 0, 0, 0 };
  3429. static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  3430. p[1] = hex[c >> 4];
  3431. p[2] = hex[c & 0xF];
  3432. encoded += p;
  3433. }
  3434. }
  3435. return encoded;
  3436. }
  3437. String String::percent_decode() const {
  3438. CharString pe;
  3439. CharString cs = utf8();
  3440. for (int i = 0; i < cs.length(); i++) {
  3441. uint8_t c = cs[i];
  3442. if (c == '%' && i < length() - 2) {
  3443. uint8_t a = LOWERCASE(cs[i + 1]);
  3444. uint8_t b = LOWERCASE(cs[i + 2]);
  3445. if (a >= '0' && a <= '9') {
  3446. c = (a - '0') << 4;
  3447. } else if (a >= 'a' && a <= 'f') {
  3448. c = (a - 'a' + 10) << 4;
  3449. } else {
  3450. continue;
  3451. }
  3452. uint8_t d = 0;
  3453. if (b >= '0' && b <= '9') {
  3454. d = (b - '0');
  3455. } else if (b >= 'a' && b <= 'f') {
  3456. d = (b - 'a' + 10);
  3457. } else {
  3458. continue;
  3459. }
  3460. c += d;
  3461. i += 2;
  3462. }
  3463. pe += c;
  3464. }
  3465. return String::utf8(pe.ptr());
  3466. }
  3467. String String::property_name_encode() const {
  3468. // Escape and quote strings with extended ASCII or further Unicode characters
  3469. // as well as '"', '=' or ' ' (32)
  3470. const CharType *cstr = c_str();
  3471. for (int i = 0; cstr[i]; i++) {
  3472. if (cstr[i] == '=' || cstr[i] == '"' || cstr[i] == ';' || cstr[i] == '[' || cstr[i] == ']' || cstr[i] < 33 || cstr[i] > 126) {
  3473. return "\"" + c_escape_multiline() + "\"";
  3474. }
  3475. }
  3476. // Keep as is
  3477. return *this;
  3478. }
  3479. // Changes made to the set of invalid characters must also be reflected in the String documentation.
  3480. const String String::invalid_node_name_characters = ". : @ / \" " UNIQUE_NODE_PREFIX;
  3481. ;
  3482. String String::validate_node_name() const {
  3483. Vector<String> chars = String::invalid_node_name_characters.split(" ");
  3484. String name = this->replace(chars[0], "");
  3485. for (int i = 1; i < chars.size(); i++) {
  3486. name = name.replace(chars[i], "");
  3487. }
  3488. return name;
  3489. }
  3490. String String::get_basename() const {
  3491. int pos = rfind(".");
  3492. if (pos < 0 || pos < MAX(rfind("/"), rfind("\\"))) {
  3493. return *this;
  3494. }
  3495. return substr(0, pos);
  3496. }
  3497. String itos(int64_t p_val) {
  3498. return String::num_int64(p_val);
  3499. }
  3500. String uitos(uint64_t p_val) {
  3501. return String::num_uint64(p_val);
  3502. }
  3503. String rtos(double p_val) {
  3504. return String::num(p_val);
  3505. }
  3506. String rtoss(double p_val) {
  3507. return String::num_scientific(p_val);
  3508. }
  3509. // Right-pad with a character.
  3510. String String::rpad(int min_length, const String &character) const {
  3511. String s = *this;
  3512. int padding = min_length - s.length();
  3513. if (padding > 0) {
  3514. for (int i = 0; i < padding; i++) {
  3515. s = s + character;
  3516. }
  3517. }
  3518. return s;
  3519. }
  3520. // Left-pad with a character.
  3521. String String::lpad(int min_length, const String &character) const {
  3522. String s = *this;
  3523. int padding = min_length - s.length();
  3524. if (padding > 0) {
  3525. for (int i = 0; i < padding; i++) {
  3526. s = character + s;
  3527. }
  3528. }
  3529. return s;
  3530. }
  3531. // sprintf is implemented in GDScript via:
  3532. // "fish %s pie" % "frog"
  3533. // "fish %s %d pie" % ["frog", 12]
  3534. // In case of an error, the string returned is the error description and "error" is true.
  3535. String String::sprintf(const Array &values, bool *error) const {
  3536. String formatted;
  3537. CharType *self = (CharType *)c_str();
  3538. bool in_format = false;
  3539. int value_index = 0;
  3540. int min_chars = 0;
  3541. int min_decimals = 0;
  3542. bool in_decimals = false;
  3543. bool pad_with_zeros = false;
  3544. bool left_justified = false;
  3545. bool show_sign = false;
  3546. *error = true;
  3547. for (; *self; self++) {
  3548. const CharType c = *self;
  3549. if (in_format) { // We have % - lets see what else we get.
  3550. switch (c) {
  3551. case '%': { // Replace %% with %
  3552. formatted += chr(c);
  3553. in_format = false;
  3554. break;
  3555. }
  3556. case 'd': // Integer (signed)
  3557. case 'o': // Octal
  3558. case 'x': // Hexadecimal (lowercase)
  3559. case 'X': { // Hexadecimal (uppercase)
  3560. if (value_index >= values.size()) {
  3561. return "not enough arguments for format string";
  3562. }
  3563. if (!values[value_index].is_num()) {
  3564. return "a number is required";
  3565. }
  3566. int64_t value = values[value_index];
  3567. int base = 16;
  3568. bool capitalize = false;
  3569. switch (c) {
  3570. case 'd':
  3571. base = 10;
  3572. break;
  3573. case 'o':
  3574. base = 8;
  3575. break;
  3576. case 'x':
  3577. break;
  3578. case 'X':
  3579. base = 16;
  3580. capitalize = true;
  3581. break;
  3582. }
  3583. // Get basic number.
  3584. String str = String::num_int64(ABS(value), base, capitalize);
  3585. int number_len = str.length();
  3586. // Padding.
  3587. int pad_chars_count = (value < 0 || show_sign) ? min_chars - 1 : min_chars;
  3588. String pad_char = pad_with_zeros ? String("0") : String(" ");
  3589. if (left_justified) {
  3590. str = str.rpad(pad_chars_count, pad_char);
  3591. } else {
  3592. str = str.lpad(pad_chars_count, pad_char);
  3593. }
  3594. // Sign.
  3595. if (show_sign || value < 0) {
  3596. String sign_char = value < 0 ? "-" : "+";
  3597. if (left_justified) {
  3598. str = str.insert(0, sign_char);
  3599. } else {
  3600. str = str.insert(pad_with_zeros ? 0 : str.length() - number_len, sign_char);
  3601. }
  3602. }
  3603. formatted += str;
  3604. ++value_index;
  3605. in_format = false;
  3606. break;
  3607. }
  3608. case 'f': { // Float
  3609. if (value_index >= values.size()) {
  3610. return "not enough arguments for format string";
  3611. }
  3612. if (!values[value_index].is_num()) {
  3613. return "a number is required";
  3614. }
  3615. double value = values[value_index];
  3616. bool is_negative = (value < 0);
  3617. String str = String::num(ABS(value), min_decimals);
  3618. // Pad decimals out.
  3619. str = str.pad_decimals(min_decimals);
  3620. int initial_len = str.length();
  3621. // Padding. Leave room for sign later if required.
  3622. int pad_chars_count = (is_negative || show_sign) ? min_chars - 1 : min_chars;
  3623. String pad_char = pad_with_zeros ? String("0") : String(" ");
  3624. if (left_justified) {
  3625. str = str.rpad(pad_chars_count, pad_char);
  3626. } else {
  3627. str = str.lpad(pad_chars_count, pad_char);
  3628. }
  3629. // Add sign if needed.
  3630. if (show_sign || is_negative) {
  3631. String sign_char = is_negative ? "-" : "+";
  3632. if (left_justified) {
  3633. str = str.insert(0, sign_char);
  3634. } else {
  3635. str = str.insert(pad_with_zeros ? 0 : str.length() - initial_len, sign_char);
  3636. }
  3637. }
  3638. formatted += str;
  3639. ++value_index;
  3640. in_format = false;
  3641. break;
  3642. }
  3643. case 's': { // String
  3644. if (value_index >= values.size()) {
  3645. return "not enough arguments for format string";
  3646. }
  3647. String str = values[value_index];
  3648. // Padding.
  3649. if (left_justified) {
  3650. str = str.rpad(min_chars);
  3651. } else {
  3652. str = str.lpad(min_chars);
  3653. }
  3654. formatted += str;
  3655. ++value_index;
  3656. in_format = false;
  3657. break;
  3658. }
  3659. case 'c': {
  3660. if (value_index >= values.size()) {
  3661. return "not enough arguments for format string";
  3662. }
  3663. // Convert to character.
  3664. String str;
  3665. if (values[value_index].is_num()) {
  3666. int value = values[value_index];
  3667. if (value < 0) {
  3668. return "unsigned byte integer is lower than maximum";
  3669. } else if (value > 255) {
  3670. return "unsigned byte integer is greater than maximum";
  3671. }
  3672. str = chr(values[value_index]);
  3673. } else if (values[value_index].get_type() == Variant::STRING) {
  3674. str = values[value_index];
  3675. if (str.length() != 1) {
  3676. return "%c requires number or single-character string";
  3677. }
  3678. } else {
  3679. return "%c requires number or single-character string";
  3680. }
  3681. // Padding.
  3682. if (left_justified) {
  3683. str = str.rpad(min_chars);
  3684. } else {
  3685. str = str.lpad(min_chars);
  3686. }
  3687. formatted += str;
  3688. ++value_index;
  3689. in_format = false;
  3690. break;
  3691. }
  3692. case '-': { // Left justify
  3693. left_justified = true;
  3694. break;
  3695. }
  3696. case '+': { // Show + if positive.
  3697. show_sign = true;
  3698. break;
  3699. }
  3700. case '0':
  3701. case '1':
  3702. case '2':
  3703. case '3':
  3704. case '4':
  3705. case '5':
  3706. case '6':
  3707. case '7':
  3708. case '8':
  3709. case '9': {
  3710. int n = c - '0';
  3711. if (in_decimals) {
  3712. min_decimals *= 10;
  3713. min_decimals += n;
  3714. } else {
  3715. if (c == '0' && min_chars == 0) {
  3716. if (left_justified) {
  3717. WARN_PRINT("'0' flag ignored with '-' flag in string format");
  3718. } else {
  3719. pad_with_zeros = true;
  3720. }
  3721. } else {
  3722. min_chars *= 10;
  3723. min_chars += n;
  3724. }
  3725. }
  3726. break;
  3727. }
  3728. case '.': { // Float separator.
  3729. if (in_decimals) {
  3730. return "too many decimal points in format";
  3731. }
  3732. in_decimals = true;
  3733. min_decimals = 0; // We want to add the value manually.
  3734. break;
  3735. }
  3736. case '*': { // Dynamic width, based on value.
  3737. if (value_index >= values.size()) {
  3738. return "not enough arguments for format string";
  3739. }
  3740. if (!values[value_index].is_num()) {
  3741. return "* wants number";
  3742. }
  3743. int size = values[value_index];
  3744. if (in_decimals) {
  3745. min_decimals = size;
  3746. } else {
  3747. min_chars = size;
  3748. }
  3749. ++value_index;
  3750. break;
  3751. }
  3752. default: {
  3753. return "unsupported format character";
  3754. }
  3755. }
  3756. } else { // Not in format string.
  3757. switch (c) {
  3758. case '%':
  3759. in_format = true;
  3760. // Back to defaults:
  3761. min_chars = 0;
  3762. min_decimals = 6;
  3763. pad_with_zeros = false;
  3764. left_justified = false;
  3765. show_sign = false;
  3766. in_decimals = false;
  3767. break;
  3768. default:
  3769. formatted += chr(c);
  3770. }
  3771. }
  3772. }
  3773. if (in_format) {
  3774. return "incomplete format";
  3775. }
  3776. if (value_index != values.size()) {
  3777. return "not all arguments converted during string formatting";
  3778. }
  3779. *error = false;
  3780. return formatted;
  3781. }
  3782. String String::quote(String quotechar) const {
  3783. return quotechar + *this + quotechar;
  3784. }
  3785. String String::unquote() const {
  3786. if (!is_quoted()) {
  3787. return *this;
  3788. }
  3789. return substr(1, length() - 2);
  3790. }
  3791. #ifdef TOOLS_ENABLED
  3792. String TTR(const String &p_text, const String &p_context) {
  3793. if (TranslationServer::get_singleton()) {
  3794. return TranslationServer::get_singleton()->tool_translate(p_text, p_context);
  3795. }
  3796. return p_text;
  3797. }
  3798. /* DTR is used for the documentation, handling descriptions extracted from the XML.
  3799. * It also replaces `$DOCS_URL` with the actual URL to the documentation's branch,
  3800. * to allow dehardcoding it in the XML and doing proper substitutions everywhere.
  3801. */
  3802. String DTR(const String &p_text) {
  3803. // Comes straight from the XML, so remove indentation and any trailing whitespace.
  3804. const String text = p_text.dedent().strip_edges();
  3805. if (TranslationServer::get_singleton()) {
  3806. return String(TranslationServer::get_singleton()->doc_translate(text)).replace("$DOCS_URL", VERSION_DOCS_URL);
  3807. }
  3808. return text.replace("$DOCS_URL", VERSION_DOCS_URL);
  3809. }
  3810. #endif
  3811. String RTR(const String &p_text) {
  3812. if (TranslationServer::get_singleton()) {
  3813. String rtr = TranslationServer::get_singleton()->tool_translate(p_text, StringName());
  3814. if (rtr == String() || rtr == p_text) {
  3815. return TranslationServer::get_singleton()->translate(p_text);
  3816. } else {
  3817. return rtr;
  3818. }
  3819. }
  3820. return p_text;
  3821. }