ustring.cpp 89 KB

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