ustring.cpp 82 KB

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