ustring.cpp 81 KB

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