ustring.cpp 81 KB

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