ustring.cpp 87 KB

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