ustring.cpp 86 KB

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