ustring.cpp 87 KB

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